Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.
Rename your file back.
The text from the Tortoise reference:
Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.
If you want to undo an earlier change permanently, use Revert to this revision instead.
Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.
If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.
What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.
If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.
If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.
In addition to David M's answer, while doing cleanup -> check 'break locks' option. This will ensure release of locks. Then do svn update. This worked for me.
If this (https://stackoverflow.com/a/11764922/3045875) does not help: Check if another SVN tool is interfering and close the tool. We just struggled a couple of hours at merging using TortoiseSVN and had dozens of such lock errors. Eventually we figured that Matlabs SVN integration is interfering and after closing it all worked out.
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
You need to add your files to your working copy, before you commit your changes to the repository:
svn add <file|folder>
Afterwards:
svn commit
See here for detailed information about svn add
.
TortoiseSVN
It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):
If you want to include an unversioned file, just check that file to add it to the commit.
I had this under TortoiseSVN and the error was related to a new directory I'd created under a new project. I had just created this project, so there was no way this directory had existed before. I looked in the repository browser and the new folder was indeed already in the repository, but TortoiseSVN didn't show it as committed.
In order to get around it, since I'd just created the folder anyway, I deleted it in the repository, and then did a commit. It worked fine.
Since I did this outside of Visual Studio, I then had to restart Visual Studio for it to figure everything out again.
In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationIf you are getting following exception:
Error: Commit failed (details follow):
Error: Commit blocked by pre-commit hook (exit code 1) with output:
Error: svnlook: Path 'trunk/Development/ProjectName' is not a file
Then first check-in all the the directories and then all the files. It will work.
In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)
I realize this is an old question, but the same issue happened to me, but for a completely different reason.
It could be that cvs-dude changed certificates, so it no longer matches the certificate you have cached.
You can go to TortoiseSVN->Settings->Saved Data and click the 'Clear' button next to 'Authentication data' and then try again.
cd to folder containing .svn
rm -rf .svn
svn co http://mon.svn/mondepot/ . --force
Depending on what you need to do, automating TortoiseSVN may be a good solution. For example, the following will update a repository and close the TortoiseSVN window if there were no errors or conflicts:
TortoiseProc.exe /command:update /path:"c:\path\to\repo\" /closeonend:2
Replace the line in htpasswd file:
Go to: http://www.htaccesstools.com/htpasswd-generator-windows/
(If the link is expired, search another generator from google.com.)
Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".
You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.
You can fix it with only one step.
Step 1 : Open terminal and go to your project then fire command "svn cleanup" then "svn update"
I am not using AnkhSVN but got a similar problem after cancelling a Tortoise SVN update. It left two directories "already locked". Similar to Roman C's solution. Use Get lock to to lock one file in each directory that is "already locked" and then release those locks, then do a cleanup on the highest directory. That seemed to fix the problem.
Use the svn move
command to move file/folder.
My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.
If the problem lies client side, this could be one of the causes of the error.
On clients TortoiseSVN
saves client credentials under
Tortoise settings / saved data / authentication data.
I got the same error trying to commit my files, but my credentials were changed. Clearing this cache here will give you a popup on next commit attempt for re-entering your correct credentials.
They showed up after installing Ankh SVN
Take a look at svnmerge.py. It's command-line, can't be invoked by TortoiseSVN, but it's more powerful. From the FAQ:
Traditional subversion will let you merge changes, but it doesn't "remember" what you've already merged. It also doesn't provide a convenient way to exclude a change set from being merged. svnmerge.py automates some of the work, and simplifies it. Svnmerge also creates a commit message with the log messages from all of the things it merged.
Saw your problems.
Solutions:
First Download Subversion 1.8.13 ( 1.8 ) client Download link (https://subversion.apache.org/packages.html) at the time of this post the android studio version is less than 1.4 in my case 1.3.2 so you must avoid the issues here subversion command line client version is too old so just download the 1.8 preferably.
Then unzipped in a folder. There will have one folder "bin".
Then
Go to settings - > Version control -> Subversion
Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.
follow the picture:
Don't forget to give the end name like svn.exe last as per image.
Apply -> Ok
Restart your android studio now.
Happy Coding!
svn status | grep ^M will list files which are modified. M - stands for modified :)
If you're using Tortoise SVN, you should be able to revert changes from just that revision into your working copy (effectively performing a reverse-merge), then do another commit to re-add the file. Steps to follow are:
You should never use TortoiseProc.exe as a command-line Subversion client! TortoiseProc should be utilized only for automating TortoiseSVN's GUI. See the note in TortoiseSVN's Manual:
Remember that TortoiseSVN is a GUI client, and this automation guide shows you how to make the TortoiseSVN dialogs appear to collect user input. If you want to write a script which requires no input, you should use the official Subversion command line client instead.
Use the Subversion command-line svn.exe client. With the command-line client, you can
checkout a working copy in REV revision:
svn checkout --revision REV https://svn.example.com/svn/MyRepo/trunk/
svn checkout https://svn.example.com/svn/MyRepo/trunk/@REV
update your local working copy to REV revision:
export (i.e. download) a file or a development branch in REV revision:
svn export --revision REV https://svn.example.com/svn/MyRepo/trunk/
svn export https://svn.example.com/MyRepo/trunk/@REV
You may notice that with svn checkout
and svn export
you can enter REV number as --revision REV
argument and as trailing @REV
after URL. The first one is called operative revision, and the second one is called peg revision. Read SVNBook for more information about peg and operative revisions concept.
They display fine here. Are you using the 64-bit version of Windows 7 along with the 32-bit version of TortoiseSVN? If so, then they will only show up in the 32-bit Explorer (or in the CFDs of 32-bit applications). You can install both 32-bit and 64-bit versions side-by-side, though.
If I'm not wrong starting from version 1.5 SVN can track moved files\folders. In TortoiseSVN use can move file via drag&drop.
My solution was to use DOSKEY to set up some aliases to for the commands I use the most:
DOSKEY svc=TortoiseProc.exe /command:commit /path:.
DOSKEY svu=TortoiseProc.exe /command:update /path:.
DOSKEY svl=TortoiseProc.exe /command:log /path:.
DOSKEY svd=TortoiseProc.exe /command:diff /path:$*
Google "doskey persist" for tips on how to set up a .cmd file that runs every time you open the command prompt like a .*rc file in Unix.
I changed windows password today then Tortoise declined to connect me to SVN server. I got around it by opening a Dos box and doing an "svn co ...". It prompted for the new credential then happily did its work. After that, Tortoise works also.
If you have Tortoise SVN, like I do, take the google link, and ONLY copy the URL.
Regular- (svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only)
Modified to URL- (http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter)
Create a folder, right click the empty space. You can Browse Repo or just download it all via checkout.
I don't know whether you have to be a Google member or not, but I signed up just in case. Have fun with the code.
Misanthropy
For free private SVN hosting try the following:
Or use BitBucket for free private git/mercurial repositories
You need to determine whether this is a problem with TortoiseSVN, your Subversion repository, or your network connection.
http://<server>/svn/<module>
and not http://<server>/svn/
usvn
/<module>
. Is that /usvn/
directory suppose to be there?
I had the same issue, what worked for me:
Check your monitor scaling.
My problem turned out to be this:
It turned out to be different DPI-scaling on the primary and secondary monitor. When the secondary monitor was set to 125% (same as the primary monitor) the icons appeared again.
Answer actually provided by User3163 posting on SuperUser.com
You can use code as below when
using Image as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
using Text as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
I think you could use an actual space or tab directly in XML document, but if you are looking for special characters to represent them so that text processors can't mess them up, then it's:
space =  
tab = 	
How about this?
Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.
If you have an oracle client intalled on your machine, you can executed the command
imp help=y
to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.
This prevent from the multiple inclusion of same header file multiple time.
#ifndef __COMMON_H__
#define __COMMON_H__
//header file content
#endif
Suppose you have included this header file in multiple files. So first time __COMMON_H__ is not defined, it will get defined and header file included.
Next time __COMMON_H__ is defined, so it will not include again.
Use summarise
in the dplyr
package:
library(dplyr)
summarise(df, Average = mean(col_name, na.rm = T))
note: dplyr
supports both summarise
and summarize
.
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
I will advise to use first check if my.ini exist in mysql folder in c drive or in windows folder mysqld -install (Service successfully installed) mysqld --initialize (no prompt) Also another advise is not to use mysql 8, since it is not compatible with wordpress or any other opensource yet, there are lot of changes between version 5 and version 8, so if you are using mysql please use version 5.x.
People are saying that a Dictionary is the same as a hash table.
This is not necessarily true. A hash table is one way to implement a dictionary. A typical one at that, and it may be the default one in .NET in the Dictionary
class, but it's not by definition the only one.
You could equally well implement a dictionary using a linked list or a search tree, it just wouldn't be as efficient (for some metric of efficient).
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
On a side note:
I had the similar issues where many times I get the error Action method not found, but clearly it is define in controller.
The issue is not in controller, but rather how routes.php file is setup
Lets say you have Controller class set as a resource in route.php file
Route::resource('example', 'ExampleController');
then '/example' will have all RESTful Resource listed here: http://laravel.com/docs/5.0/controllers#restful-resource-controllers
but now you want to have some definition in form e.g: 'action'=>'ExampleController@postStore' then you have to change this route (in route.php file) to:
Route::controller('example', 'ExampleController');
Since the img is an inline element, Just use text-center
on it's container. Using mx-auto
will center the container (column) too.
<div class="row">
<div class="col-4 mx-auto text-center">
<img src="..">
</div>
</div>
By default, images are display:inline
. If you only want the center the image (and not the other column content), make the image display:block
using the d-block
class, and then mx-auto
will work.
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="..">
</div>
</div>
Whenever I attempt to remove the constraints that the system had to break, my constraints are no longer enough to satisfy the IB (ie "missing constraints" shows in the IB, which means they're incomplete and won't be used). I actually got around this by setting the constraint it wants to break to low priority, which (and this is an assumption) allows the system to break the constraint gracefully. It's probably not the best solution, but it solved my problem and the resulting constraints worked perfectly.
Kotlin Users,
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
})
Update 2020 for ViewPager2
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrollStateChanged(state: Int) {
println(state)
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
println(position)
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
println(position)
}
})
They always say it depends but when it comes to mirroring a website The best exists httrack. It is super fast and easy to work. The only downside is it's so called support forum but you can find your way using official documentation. It has both GUI and CLI interface and it Supports cookies just read the docs This is the best.(Be cureful with this tool you can download the whole web on your harddrive)
httrack -c8 [url]
By default maximum number of simultaneous connections limited to 8 to avoid server overload
The advantage of lists appears if you need to insert items in the middle and don't want to start resizing the array and shifting things around.
You're correct in that this is typically not the case. I've had a few very specific cases like that, but not too many.
To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING
and CHAR_LENGTH
functions together:
SELECT col
, /* ANSI Syntax */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
, /* MySQL Syntax */ SUBSTRING(col, 1, CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl
To remove a specific substring from the end of string, use the TRIM
function:
SELECT col
, TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt
For non MAMP or XAMPP users on OSX (with homebrew installed):
brew install homebrew/php/php56-mcrypt
Cheers!
I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.
Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.
After this, Windows started prioritize Ethernet adapter.
The basic difference between Web Services and Web APIs
Web Service:
1) It is a SOAP-based service and returns data as XML.
2) It only supports the HTTP protocol.
3) It is not open source but can be used by any client that understands XML.
5) It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.
Web API:
1) A Web API is an HTTP based service and returns JSON or XML data by default.
2) It supports the HTTP protocol.
3) It can be hosted within an application or IIS.
4) It is open source and it can be used by any client that understands JSON or XML.
5) It has light-weight architecture and good for devices which have limited bandwidth, like mobile devices.
And just in case, if you want to find the coordinates of 'nan' for all the columns instead (supposing they are all numericals), here you go:
df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])
df
0 1 2 3 4 5
0 0 1 3 4.0 NaN 2
1 3 5 6 NaN 3.0 3
np.where(np.asanyarray(np.isnan(df)))
(array([0, 1]), array([4, 3]))
Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value
.
A practical example:
SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...
The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.
In Firefox the onchange fires only when you tab or else click outside the input field. The same is true of Onblur. The difference is that onblur will fire whether you changed anything in the field or not. It is possible that ENTER will fire one or both of these, but you wouldn't know that if you disable the ENTER in your forms to prevent unexpected submits.
Since START is the only way to execute something in the background from a CMD script, I would recommend you keep using it. Instead of the /B modifier, try /MIN so the newly created window won't bother you. Also, you can set the priority to something lower with /LOW or /BELOWNORMAL, which should improve your system responsiveness.
What the hell of all this work anthers
it's too simple
if you want a list of how much productId in each keyword here it's the code
SELECT count(productId), keyword FROM `Table_name` GROUP BY keyword;
try this code
using hidden field we can pass php varibale to another page
page1.php
<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
<input type="hidden" name="text" value="<?php echo $myVariable; ?>">
<button type="submit">Submit</button>
</form>
pass php variable to hidden field value so you can access this variable into another page
page2.php
<?php
$text=$_POST['text'];
echo $text;
?>
On Centos 6.5/PostgreSQL 9.3:
Change the value of "PGDATA=/var/lib/pgsql/data"
to whatever location you want in the initial script file /etc/init.d/postgresql
.
Remember to chmod 700
and chown postgres:postgres
to the new location and you're the boss.
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Added below "Conclusion" paragraph
I've went down the pipenv
rabbit hole (it's a deep and dark hole indeed...) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I've found.
This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It's about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.
As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: "Changed in version 3.5: The use of venv is now recommended for creating virtual environments".
pipenv- like venv - can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt
, pipenv
delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile
is to supplant requirements.txt
.
HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.
So if settling on a virtual envelope solution wasn't difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.
The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:
prefer built-in venv: if the target python has venv we'll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)
So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv- which uses virtualenv
- varies materially from venv
.
Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.
An oft repeated criticism of Pipenv I saw when producing this analysis was that it was not actively maintained. Indeed, what's the point of using a solution whose future could be seen questionable due to lack of continuous development? After a dry spell of about 18 months, Pipenv is once again being actively developed. Indeed, large and material updates have since been released.
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
I used a for and while loop on a solid test machine (no non-standard 3rd party background processes running). I ran a for loop
vs while loop
as it relates to changing the style property of 10,000 <button>
nodes.
The test is was run consecutively 10 times, with 1 run timed out for 1500 milliseconds before execution:
Here is the very simple javascript I made for this purpose
function runPerfTest() {
"use strict";
function perfTest(fn, ns) {
console.time(ns);
fn();
console.timeEnd(ns);
}
var target = document.getElementsByTagName('button');
function whileDisplayNone() {
var x = 0;
while (target.length > x) {
target[x].style.display = 'none';
x++;
}
}
function forLoopDisplayNone() {
for (var i = 0; i < target.length; i++) {
target[i].style.display = 'none';
}
}
function reset() {
for (var i = 0; i < target.length; i++) {
target[i].style.display = 'inline-block';
}
}
perfTest(function() {
whileDisplayNone();
}, 'whileDisplayNone');
reset();
perfTest(function() {
forLoopDisplayNone();
}, 'forLoopDisplayNone');
reset();
};
$(function(){
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
setTimeout(function(){
console.log('cool run');
runPerfTest();
}, 1500);
});
Here are the results I got
pen.js:8 whileDisplayNone: 36.987ms
pen.js:8 forLoopDisplayNone: 20.825ms
pen.js:8 whileDisplayNone: 19.072ms
pen.js:8 forLoopDisplayNone: 25.701ms
pen.js:8 whileDisplayNone: 21.534ms
pen.js:8 forLoopDisplayNone: 22.570ms
pen.js:8 whileDisplayNone: 16.339ms
pen.js:8 forLoopDisplayNone: 21.083ms
pen.js:8 whileDisplayNone: 16.971ms
pen.js:8 forLoopDisplayNone: 16.394ms
pen.js:8 whileDisplayNone: 15.734ms
pen.js:8 forLoopDisplayNone: 21.363ms
pen.js:8 whileDisplayNone: 18.682ms
pen.js:8 forLoopDisplayNone: 18.206ms
pen.js:8 whileDisplayNone: 19.371ms
pen.js:8 forLoopDisplayNone: 17.401ms
pen.js:8 whileDisplayNone: 26.123ms
pen.js:8 forLoopDisplayNone: 19.004ms
pen.js:61 cool run
pen.js:8 whileDisplayNone: 20.315ms
pen.js:8 forLoopDisplayNone: 17.462ms
Here is the demo link
Update
A separate test I have conducted is located below, which implements 2 differently written factorial algorithms, 1 using a for loop, the other using a while loop.
Here is the code:
function runPerfTest() {
"use strict";
function perfTest(fn, ns) {
console.time(ns);
fn();
console.timeEnd(ns);
}
function whileFactorial(num) {
if (num < 0) {
return -1;
}
else if (num === 0) {
return 1;
}
var factl = num;
while (num-- > 2) {
factl *= num;
}
return factl;
}
function forFactorial(num) {
var factl = 1;
for (var cur = 1; cur <= num; cur++) {
factl *= cur;
}
return factl;
}
perfTest(function(){
console.log('Result (100000):'+forFactorial(80));
}, 'forFactorial100');
perfTest(function(){
console.log('Result (100000):'+whileFactorial(80));
}, 'whileFactorial100');
};
(function(){
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
console.log('cold run @1500ms timeout:');
setTimeout(runPerfTest, 1500);
})();
And the results for the factorial benchmark:
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.280ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.241ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.254ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.254ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.285ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.294ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.181ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.172ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.195ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.279ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.185ms
pen.js:55 cold run @1500ms timeout:
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.404ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.314ms
Conclusion: No matter the sample size or specific task type tested, there is no clear winner in terms of performance between a while and for loop. Testing done on a MacAir with OS X Mavericks on Chrome evergreen.
Query params are used like this:
use Illuminate\Http\Request;
class MyController extends BaseController{
public function index(Request $request){
$param = $request->query('param');
}
Tabview is really good. Worked with 200+MB files that displayed nicely which were buggy with LibreOffice as well as csv plugin in gvim.
The Anaconda version is available here: https://anaconda.org/bioconda/tabview
To check if LocalDb is installed or not:
cmd
and type in sqllocaldb i
this should give you the installed sqllocaldb instances if found.(localdb)\V11.0
using windows authentication.If an error is raised Cannot connect to (localdb)\V11.0.
change the instance name to (localdb)\MSSQLLocalDB
and try again to connect, if you still get the same error.
Follow these steps to install LocalDb:
Start Menu
and type in search sqlLocalDb
.sqlLocalDb.msi
and click it.after finishing the installation re-run SSMS
and try connecting to either of the instances (localdb)\V11.0
or (localdb)\MSSQLLocalDB
, one of it should work depending on what Visual Studio version you have.
You can also verify that localdb
is installed using Visual Studio by simply creating new sql file and go to the connect icon on the top header of the file which by default lists all the servers you can connect to including localdb
if installed.
In addition to the above mentioned ways of finding if localdb is installed, you can also use the MS windows power shell
or windows command processor CMD
or even NuGet package manager console
on your server machine and run these commands sqllocaldb i
and sqllocaldb v
that will show you the localdb name if it is installed and the MSSQL server version installed and running on your machine.
Try this
function split_at_index(value, index)
{
return value.substring(0, index) + "," + value.substring(index);
}
console.log(split_at_index('3123124', 2));
_x000D_
The solution to the absence of BLAS/LAPACK libraries for SciPy installations on Windows 7 64-bit is described here:
http://www.scipy.org/scipylib/building/windows.html
Installing Anaconda is much easier, but you still don't get Intel MKL or GPU support without paying for it (they are in the MKL Optimizations and Accelerate add-ons for Anaconda - I'm not sure if they use PLASMA and MAGMA either). With MKL optimization, numpy has outperformed IDL on large matrix computations by 10-fold. MATLAB uses the Intel MKL library internally and supports GPU computing, so one might as well use that for the price if they're a student ($50 for MATLAB + $10 for the Parallel Computing Toolbox). If you get the free trial of Intel Parallel Studio, it comes with the MKL library, as well as C++ and FORTRAN compilers that will come in handy if you want to install BLAS and LAPACK from MKL or ATLAS on Windows:
http://icl.cs.utk.edu/lapack-for-windows/lapack/
Parallel Studio also comes with the Intel MPI library, useful for cluster computing applications and their latest Xeon processsors. While the process of building BLAS and LAPACK with MKL optimization is not trivial, the benefits of doing so for Python and R are quite large, as described in this Intel webinar:
Anaconda and Enthought have built businesses out of making this functionality and a few other things easier to deploy. However, it is freely available to those willing to do a little work (and a little learning).
For those who use R, you can now get MKL optimized BLAS and LAPACK for free with R Open from Revolution Analytics.
EDIT: Anaconda Python now ships with MKL optimization, as well as support for a number of other Intel library optimizations through the Intel Python distribution. However, GPU support for Anaconda in the Accelerate library (formerly known as NumbaPro) is still over $10k USD! The best alternatives for that are probably PyCUDA and scikit-cuda, as copperhead (essentially a free version of Anaconda Accelerate) unfortunately ceased development five years ago. It can be found here if anybody wants to pick up where they left off.
In addition to Jon Skeet's answer, you can also use the group by expressions to get the unique groups along w/ a count for each groups iterations:
var query = from e in doc.Elements("whatever")
group e by new { id = e.Key, val = e.Value } into g
select new { id = g.Key.id, val = g.Key.val, count = g.Count() };
How about netstat?
http://support.microsoft.com/kb/907980
The command is netstat -anob
.
(Make sure you run command as admin)
I get:
C:\Windows\system32>netstat -anob
Active Connections
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 692
RpcSs
[svchost.exe]
TCP 0.0.0.0:443 0.0.0.0:0 LISTENING 7540
[Skype.exe]
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:623 0.0.0.0:0 LISTENING 564
[LMS.exe]
TCP 0.0.0.0:912 0.0.0.0:0 LISTENING 4480
[vmware-authd.exe]
And If you want to check for the particular port, command to use is: netstat -aon | findstr 8080 from the same path
Of course you can.
One thing should be noted however: The INSERT INTO SELECT
statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR
into INT
, or TINYINT
intoINT
) the MySQL server will throw an SQL Error (1366)
.
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT
, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST()
is synonym of CONVERT()
) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.
If you allocate the array on the heap you should be fine, assuming your machine has enough memory.
int* array = new int[1000000];
But remember that this will require you to delete[]
the array. A better solution would be to use std::vector<int>
and resize it to 1000000 elements.
This is actually quite tricky. A different total number of days can result in the same result. For example:
19th June 2008 to 19th June 2010 = 2 years, but also 365 * 2 days
19th June 2006 to 19th June 2008 = 2 years, but also 365 + 366 days due to leap years
You may well want to subtract years until you get to the point where you've got two dates which are less than a year apart. Then subtract months until you get to the point where you've got two dates which are less than a month apart.
Further confusion: subtracting (or adding) months is tricky when you might start with a date of "30th March" - what's a month earlier than that?
Even further confusion (may not be relevant): even a day isn't always 24 hours. Daylight saving anyone?
Even further confusion (almost certainly not relevant): even a minute isn't always 60 seconds. Leap seconds are highly confusing...
I don't have the time to work out the exact right way of doing this right now - this answer is mostly to raise the fact that it's not nearly as simple as it might sound.
EDIT: Unfortunately I'm not going to have enough time to answer this fully. I would suggest you start off by defining a struct representing a Period
:
public struct Period
{
private readonly int days;
public int Days { get { return days; } }
private readonly int months;
public int Months { get { return months; } }
private readonly int years;
public int Years { get { return years; } }
public Period(int years, int months, int days)
{
this.years = years;
this.months = months;
this.days = days;
}
public Period WithDays(int newDays)
{
return new Period(years, months, newDays);
}
public Period WithMonths(int newMonths)
{
return new Period(years, newMonths, days);
}
public Period WithYears(int newYears)
{
return new Period(newYears, months, days);
}
public static DateTime operator +(DateTime date, Period period)
{
// TODO: Implement this!
}
public static Period Difference(DateTime first, DateTime second)
{
// TODO: Implement this!
}
}
I suggest you implement the + operator first, which should inform the Difference
method - you should make sure that first + (Period.Difference(first, second)) == second
for all first
/second
values.
Start with writing a whole slew of unit tests - initially "easy" cases, then move on to tricky ones involving leap years. I know the normal approach is to write one test at a time, but I'd personally brainstorm a bunch of them before you start any implementation work.
Allow yourself a day to implement this properly. It's tricky stuff.
Note that I've omitted weeks here - that value at least is easy, because it's always 7 days. So given a (positive) period, you'd have:
int years = period.Years;
int months = period.Months;
int weeks = period.Days / 7;
int daysWithinWeek = period.Days % 7;
(I suggest you avoid even thinking about negative periods - make sure everything is positive, all the time.)
You could use the timeout
setting in the ajax options like this:
$.ajax({
url: "test.html",
timeout: 3000,
error: function(){
//do something
},
success: function(){
//do something
}
});
Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/
Remember that when a timeout occurs, the error
handler is triggered and not the success
handler :)
There are some online services for obfuscate php to hide the code from others. This is one Right Coder's Free Obfuscator Online
@Glavic is right. "Nothing is bulletproof". You can encode your source code and hide from bigger programmers, not from experts.
1)From OS level(UNIX):-
dataserver -v
2)From Syabse isql:-
select @@version
go
sp_version
go
Here is a useful article by Michael J. Swart on the matter, which covers different patterns and antipatterns for implementing UPSERT
in SQL Server:
https://michaeljswart.com/2017/07/sql-server-upsert-patterns-and-antipatterns/
It addresses associated concurrency issues (primary key violations, deadlocks) - all of the answers provided here yet are considered antipatterns in the article (except for the @Bridge solution using triggers, which is not covered there).
Here is an extract from the article with the solution preferred by the author:
Inside a serializable transaction with lock hints:
CREATE PROCEDURE s_AccountDetails_Upsert ( @Email nvarchar(4000), @Etc nvarchar(max) )
AS
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRAN
IF EXISTS ( SELECT * FROM dbo.AccountDetails WITH (UPDLOCK) WHERE Email = @Email )
UPDATE dbo.AccountDetails
SET Etc = @Etc
WHERE Email = @Email;
ELSE
INSERT dbo.AccountDetails ( Email, Etc )
VALUES ( @Email, @Etc );
COMMIT
There is also related question with answers here on stackoverflow: Insert Update stored proc on SQL Server
You can also provide a negative number as an argument to the round
method to round to the nearest multiple of 10, 100 and so on.
# Round to the nearest multiple of 10.
12.3453.round(-1) # Output: 10
# Round to the nearest multiple of 100.
124.3453.round(-2) # Output: 100
with assuming below setting in .config file:
<configuration>
<appSettings>
<add key="PFUserName" value="myusername"/>
<add key="PFPassWord" value="mypassword"/>
</appSettings>
</configuration>
try this:
public class myController : Controller
{
NameValueCollection myKeys = ConfigurationManager.AppSettings;
public void MyMethod()
{
var myUsername = myKeys["PFUserName"];
var myPassword = myKeys["PFPassWord"];
}
}
Capture route change events in the following manner...
import { Component, OnInit, Output, ViewChild } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event as NavigationEvent } from '@angular/router';
@Component({
selector: "my-app",
templateUrl: "app/app.component.html",
styleUrls: ["app/app.component.css"]
})
export class AppComponent {
constructor(private cacheComponentObj: CacheComponent,
private router: Router) {
/* Route event types
NavigationEnd
NavigationCancel
NavigationError
RoutesRecognized
*/
router.events.forEach((event: NavigationEvent) => {
//Before Navigation
if (event instanceof NavigationStart) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
//After Navigation
if (event instanceof NavigationEnd) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
});
}
}
The best way is to user sass-loader. It is available as npm package. It resolves all path related issues and make it super easy.
The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.
I think ADTC's solution is better, but mine's also works.
Here is the other solution I found
select p.name
from person p
where instr(p.name,chr(8211)) > 0; --contains the character chr(8211)
--at least 1 time
Thank you.
I believe telnet 74.255.12.25 8089
. Why don't u try both
An alternative to using environment variables, which can get messy if you have a lot of them, is to use volumes to make a directory on the host accessible in the container.
If you put all your credentials as files in that folder, then the container can read the files and use them as it pleases.
For example:
$ echo "secret" > /root/configs/password.txt
$ docker run -v /root/configs:/cfg ...
In the Docker container:
# echo Password is `cat /cfg/password.txt`
Password is secret
Many programs can read their credentials from a separate file, so this way you can just point the program to one of the files.
We have M2_HOME,MAVEN_HOME,M3_HOME all are available in market
Previously M2_HOME is the only environment variable used by all as a standard.
But,due latest releases the MAVEN_Home came as standard but some old tools are still trying to find only M2_HOME
so we should have both M2_HOME,MAVEN_HOME to sustain with old and new tools.
M2_HOME can be used for both as well
<script type="text/javascript">
$(document).ready(function() {
showWarning('@ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
Best way is to use list comprehension:
def map_to_list(my_list, n):
# multiply every value in my_list by n
# Use list comprehension!
my_new_list = [i * n for i in my_list]
return my_new_list
# To test:
print(map_to_list([1,2,3], -1))
Returns: [-1, -2, -3]
Secure_path is your friend, but if you want to exempt yourself from secure_path just do
sudo visudo
And append
Defaults exempt_group=your_goup
If you want to exempt a bunch of users create a group, add all the users to it, and use that as your exempt_group. man 5 sudoers for more.
Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it’ll look nice. You might use it on your data reports, showing information, etc.
You can use :
basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables
Striped rows Table :
<table class="table table-striped" width="647">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Address</th>
<th>mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Thomas bell</td>
<td>Brick lane, London</td>
<td>[email protected]</td>
</tr>
<tr>
<td height="29">2</td>
<td>Yan Chapel</td>
<td>Toronto Australia</td>
<td>[email protected]</td>
</tr>
<tr>
<td>3</td>
<td>Pit Sampras</td>
<td>Berlin, Germany</td>
<td>Pit @yahoo.com</td>
</tr>
</tbody>
</table>
Condensed table :
Compacting a table you need to add class class=”table table-condensed” .
<table class="table table-condensed" width="647">
<thead>
<tr>
<th>#</th>
<th>Sample Name</th>
<th>Address</th>
<th>Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Thomas bell</td>
<td>Brick lane, London</td>
<td>[email protected]</td>
</tr>
<tr>
<td height="29">2</td>
<td>Yan Chapel</td>
<td>Toronto Australia</td>
<td>[email protected]</td>
</tr>
<tr>
<td>3</td>
<td>Pit Sampras</td>
<td>Berlin, Germany</td>
<td>Pit @yahoo.com</td>
</tr>
<tr>
<td></td>
<td colspan="3" align="center"></td>
</tr>
</tbody>
</table>
Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial
::
is a operator of defining the namespace.
For example, if you want to use cout without mentioning using namespace std;
in your code you write this:
std::cout << "test";
When no namespace is mentioned, that it is said that class belongs to global namespace.
I use this for my npm Process
#!/bin/bash
for (( ; ; ))
do
date +"%T"
echo Start Process
cd /toFolder
sudo process
date +"%T"
echo Crash
sleep 1
done
In my case, I want to exclude an existing file. Only modifying .gitignore not work. I followed these steps:
git rm --cached dirToFile/file.php
vim .gitignore
git commit -a
In this way, I cleaned from cache the file that I wanted to exclude and after I added it to .gitignore.
Use strpos()
:
if (strpos($string2, 'http') === 0) {
// It starts with 'http'
}
Remember the three equals signs (===
). It will not work properly if you only use two. This is because strpos()
will return false
if the needle cannot be found in the haystack.
Best way to do is :
[self performSelector:@selector(YourFunctionName)
withObject:(can be Self or Object from other Classes)
afterDelay:(Time Of Delay)];
you can also pass nil as withObject parameter.
example :
[self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ];
You should follow the Google guide;
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
You can check the documentation here
@Raphael your solution does work. I encountered the same problem and solved it by increasing the maximum execution time to 180. There is an easier way to do it though:
Open the Xampp control panel
Click on 'config' behind 'Apache'
Select 'PHP (php.ini)' from the dropdown -> A file should now open in your text editor
Press ctrl+f and search for 'max_execution_time', you should fine a line which only says
max_execution_time=30
Change 30 to a bigger number (180 worked for me), like this:
max_execution_time=180
Save the file
'Stop' Apache server
Close Xampp
Restart Xampp
'Start' Apache server
Update Wordpress from the Admin dashboard
Enjoy ;)
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
Easy peasy. Your data frame will look like this:
df <- data.frame(sex=c('M','F','M'),
occupation=c('Student','Analyst','Analyst'))
You can then do the equivalent of a COUNTIF
by first specifying the IF
part, like so:
df$sex == 'M'
This will give you a boolean vector, i.e. a vector of TRUE
and FALSE
. What you want is to count the observations for which the condition is TRUE
. Since in R TRUE
and FALSE
double as 1 and 0 you can simply sum()
over the boolean vector. The equivalent of COUNTIF(sex='M')
is therefore
sum(df$sex == 'M')
Should there be rows in which the sex
is not specified the above will give back NA
. In that case, if you just want to ignore the missing observations use
sum(df$sex == 'M', na.rm=TRUE)
The u in u'Some String'
means that your string is a Unicode string.
Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.
A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.
Q: sry no time code pls
A: Fine. try str('Some String')
or 'Some String'.encode('ascii', 'ignore')
. But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.
Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.
In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:
const isEmptyValue = (value) => {
if (value === '' || value === null || value === undefined) {
return true
} else {
return false
}
}
For red lines an points
plt.plot(dates, values, '.r-')
or for x markers and blue lines
plt.plot(dates, values, 'xb-')
I spent hours trying to convert a windows form listbox ToString value to a standard string so that I could use it with fstream to output to a txt file. My Visual Studio didn't come with marshal header files which several answers I found said to use. After so much trial and error I finally found a solution to the problem that just uses System::Runtime::InteropServices:
void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
//this is the code to use the function:
scheduleBox->SetSelected(0,true);
string a = "test";
String ^ c = gcnew String(scheduleBox->SelectedItem->ToString());
MarshalString(c, a);
filestream << a;
And here is the MSDN page with the example: http://msdn.microsoft.com/en-us/library/1b4az623(v=vs.80).aspx
I know it's a pretty simple solution but this took me HOURS of troubleshooting and visiting several forums to finally find something that worked.
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
@Override
public void processFinish(String data) {
// do things
}
Sometimes, default values for parameters is enough for multiple constructors. And when that doesn't suffice, I try to wrap most of the constructor functionality into an init(other-params) function that is called afterwards. Also consider using the factory concept to make an object that can effectively create the other objects you want.
http://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=363482142#Javascript
This is likely because you haven't set your compileSdkVersion
to 21 in your build.gradle file. You also probably want to change your targetSdkVersion
to 21.
android {
//...
compileSdkVersion 21
defaultConfig {
targetSdkVersion 21
}
//...
}
This requires you to have downloaded the latest SDK updates to begin with.
Once you've downloaded all the updates (don't forget to also update the Android Support Library/Repository, too!) and updated your compileSdkVersion, re-sync your Gradle project.
Edit: For Eclipse or general IntelliJ users
See reVerse's answer. He has a very thorough walk through!
This polyfill code working in modern (2017) browsers (IE11, Opera, Chrome, FireFox, Yandex):
printStackTrace: function () {
var err = new Error();
var stack = err.stack || /*old opera*/ err.stacktrace || ( /*IE11*/ console.trace ? console.trace() : "no stack info");
return stack;
}
Other answers:
function stackTrace() {
var err = new Error();
return err.stack;
}
not working in IE 11 !
Using arguments.callee.caller - not working in strict mode in any browser!
Try this in Swift :
var urlString = myUrl.absoluteString
Objective-C:
NSString *urlString = [myURL absoluteString];
Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:
Other than syntax, a switch can be implemented using a tree which makes it O(log n)
, while a if/else has to be implemented with an O(n)
procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?
With this, you won't even have to type "source ~/.bashrc":
Include your bashrc file:
alias rc="vim ~/.bashrc && source ~/.bashrc"
Every time you want to edit your bashrc, just run the alias "rc"
With ?# 6.0
var myDict = new Dictionary<string, string>
{
["Key1"] = "Value1",
["Key2"] = "Value2"
};
Unobtrusive JavaScript approach was good in the PAST - especially events handler bind in HTML was considered as bad practice (mainly because onclick events run in the global scope and may cause unexpected error
what was mention by YiddishNinja)
Currently it seems that this approach is a little outdated and needs some update. If someone want to be professional frontend developper and write large and complicated apps then he need to use frameworks like Angular, Vue.js, etc... However that frameworks usually use (or allow to use) HTML-templates where event handlers are bind in html-template code directly and this is very handy, clear and effective - e.g. in angular template usually people write:
<button (click)="someAction()">Click Me</button>
In raw js/html the equivalent of this will be
<button onclick="someAction()">Click Me</button>
The difference is that in raw js onclick
event is run in the global scope - but the frameworks provide encapsulation.
The problem is when novice programmer who always heard that html-onclick is bad and who always use btn.addEventListener("onclick", ... )
wants to use some framework with templates (addEventListener
also have drawbacks - if we update DOM in dynamic way using innerHTML=
(which is pretty fast) - then we loose events handlers bind in that way). Then he will face something like bad-habits or wrong-approach to framework usage - and he will use framework in very bad way - because he will focus mainly on js-part and no on template-part (and produce unclear and hard to maintain code). To change this habits he will loose a lot of time (and probably he will need some luck and teacher).
So in my opinion, based on experience with my students, better would be for them if they use html-handlers-bind at the beginning. As I say it is true that handlers are call in global scope but a this stage students usually create small applications which are easy to control. To write bigger applications they choose some frameworks.
We can UPDATE the Unobtrusive JavaScript approach and allow bind event handlers (eventually with simple parameters) in html (but only bind handler - not put logic into onclick like in OP quesiton). So in my opinion in raw js/html this should be allowed
<button onclick="someAction(3)">Click Me</button>
or
function popup(num,str,event) {_x000D_
let re=new RegExp(str); _x000D_
// ... _x000D_
event.preventDefault();_x000D_
console.log("link was clicked");_x000D_
}
_x000D_
<a href="https://example.com" onclick="popup(300,'map',event)">link</a>
_x000D_
But below examples should NOT be allowed
<button onclick="console.log('xx'); someAction(); return true">Click Me</button>
<a href="#" onclick="popup('/map/', 300, 300, 'map'); return false;">link</a>
The reality changes, our point of view should too
It works in Python too:
>>> 1+\
2+\
3
6
>>> (1+
2+
3)
6
put these in values/colors.xml
<resources>
<color name="light_font">#FBFBFB</color>
<color name="grey_font">#ff9e9e9e</color>
<color name="text_shadow">#7F000000</color>
<color name="text_shadow_white">#FFFFFF</color>
</resources>
Then in your layout xml here are some example TextView's
Example of Floating text on Light with Dark shadow
<TextView android:id="@+id/txt_example1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/light_font"
android:shadowColor="@color/text_shadow"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="2" />
Example of Etched text on Light with Dark shadow
<TextView android:id="@+id/txt_example2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/light_font"
android:shadowColor="@color/text_shadow"
android:shadowDx="-1"
android:shadowDy="-1"
android:shadowRadius="1" />
Example of Crisp text on Light with Dark shadow
<TextView android:id="@+id/txt_example3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/grey_font"
android:shadowColor="@color/text_shadow_white"
android:shadowDx="-2"
android:shadowDy="-2"
android:shadowRadius="1" />
Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.
Try using the following:
Window parentWindow = Window.GetWindow(userControlReference);
The GetWindow
method will walk the VisualTree for you and locate the window that is hosting your control.
You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow
method from returning null
. E.g. wire up an event:
this.Loaded += new RoutedEventHandler(UserControl_Loaded);
Initializing a simple array :
<?php $array1=array(10,20,30,40,50); ?>
Initializing array within array :
<?php $array2=array(6,"santosh","rahul",array("x","y","z")); ?>
Source : Sorce for the code
None of the answers worked for me. If you just want to disable the message, go to Intellij Preferences -> Editor -> General -> Appearance, uncheck "Show Spring Boot metadata panel".
However, you can also live with that message, if it does not bother you too much, so to make sure you don't miss any other Spring Boot metadata messages you may be interested in.
What's happening is that since the the TextView is filling the whole width of the inner LinearLayout it is already in the horizontal center of the layout. When you use android:layout_gravity
it places the widget, as a whole, in the gravity specified. Instead of placing the whole widget center what you're really trying to do is place the content in the center which can be accomplished with android:gravity="center_horizontal"
and the android:layout_gravity
attribute can be removed.
I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2
.
If you don't mind using your mouse a little bit:
This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell
and exit).
I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.
That means:
then link the two together:
public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException
{
FileReader fr = null;
try {
fr = new FileReader(source);
XMLReader reader = new NamespaceFilterXMLReader();
InputSource is = new InputSource(fr);
SAXSource ss = new SAXSource(reader, is);
return unmarshaller.unmarshal(ss);
} catch (SAXException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} catch (ParserConfigurationException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} finally {
FileUtil.close(fr); //replace with this some safe close method you have
}
}
I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations:
In your case, I guess you have confused m
with n
. Here m
denotes the number of examples in your training set, not the number of features.
Let's have a look at my variation of your code:
import numpy as np
import random
# m denotes the number of examples here, not the number of features
def gradientDescent(x, y, theta, alpha, m, numIterations):
xTrans = x.transpose()
for i in range(0, numIterations):
hypothesis = np.dot(x, theta)
loss = hypothesis - y
# avg cost per example (the 2 in 2*m doesn't really matter here.
# But to be consistent with the gradient, I include it)
cost = np.sum(loss ** 2) / (2 * m)
print("Iteration %d | Cost: %f" % (i, cost))
# avg gradient per example
gradient = np.dot(xTrans, loss) / m
# update
theta = theta - alpha * gradient
return theta
def genData(numPoints, bias, variance):
x = np.zeros(shape=(numPoints, 2))
y = np.zeros(shape=numPoints)
# basically a straight line
for i in range(0, numPoints):
# bias feature
x[i][0] = 1
x[i][1] = i
# our target variable
y[i] = (i + bias) + random.uniform(0, 1) * variance
return x, y
# gen 100 points with a bias of 25 and 10 variance as a bit of noise
x, y = genData(100, 25, 10)
m, n = np.shape(x)
numIterations= 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)
At first I create a small random dataset which should look like this:
As you can see I also added the generated regression line and formula that was calculated by excel.
You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by m
.
The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it.
If you run my example, the theta returned will look like this:
Iteration 99997 | Cost: 47883.706462
Iteration 99998 | Cost: 47883.706462
Iteration 99999 | Cost: 47883.706462
[ 29.25567368 1.01108458]
Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.
The javadoc says this:
"Returns an immutable list containing only the specified object. The returned list is serializable."
You ask:
Why would I want to have a separate method to do that?
Primarily as a convenience ... to save you having to write a sequence of statements to:
It may also be a bit faster and/or save a bit of memory, but it is unlikely that these small savings will be significant. (An application that creates vast numbers of singleton lists is unusual to say the least.)
How does immutability play a role here?
It is part of the specification of the method; see above.
Are there any special useful use-cases for this method, rather than just being a convenience method?
Clearly, there are use-cases where it is convenient to use the singletonList
method. But I don't know how you would (objectively) distinguish between an ordinary use-case and a "specially useful" one ...
SOAP - Simple Object Access Protocol is a protocol!
REST - REpresentational State Transfer is an architectural style!
SOAP
is an XML protocol used to transfer messages, typically over HTTP
REST
and SOAP
are arguably not mutually exclusive. A RESTful architecture might use HTTP
or SOAP
or some other communication protocol. REST
is optimized for the web and thus HTTP
is a perfect choice. HTTP
is also the only protocol discussed in Roy Fielding's paper.
Although REST and SOAP are clearly very different, the question does illuminate the fact that REST
and HTTP
are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.
Client-Server Communication
Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in princple.
Stateless
Each each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.
Cacheable
Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.
Uniform Interface
All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!
The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.
See this blog post on REST Design Principals for more details on REST and the above stated bullets.
The best way I have found to get a feel for things like this is to try them out:
import java.io.File;
public class PathTesting {
public static void main(String [] args) {
File f = new File("test/.././file.txt");
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
try {
System.out.println(f.getCanonicalPath());
}
catch(Exception e) {}
}
}
Your output will be something like:
test\..\.\file.txt
C:\projects\sandbox\trunk\test\..\.\file.txt
C:\projects\sandbox\trunk\file.txt
So, getPath()
gives you the path based on the File object, which may or may not be relative; getAbsolutePath()
gives you an absolute path to the file; and getCanonicalPath()
gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.
When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Files
are pointing at the same file on disk, you could compare their canonical paths. Just one example.
Just see this page
in cmd type:
Command | clip
Then open a *.Txt
file and Paste
. That's it. Done.
Use this code it works perfectly for odd or even list sizes. Hope it help somebody .
int listSize = listOfArtist.size();
int mid = 0;
if (listSize % 2 == 0) {
mid = listSize / 2;
Log.e("Parting", "You entered an even number. mid " + mid
+ " size is " + listSize);
} else {
mid = (listSize + 1) / 2;
Log.e("Parting", "You entered an odd number. mid " + mid
+ " size is " + listSize);
}
//sublist returns List convert it into arraylist * very important
leftArray = new ArrayList<ArtistModel>(listOfArtist.subList(0, mid));
rightArray = new ArrayList<ArtistModel>(listOfArtist.subList(mid,
listSize));
Solution for Swift 4:
yourLabel.layer.borderColor = UIColor.green.cgColor
import math #imports math module
import math as m
print(m.sqrt(25))
from math import sqrt #imports a method from math module
print(sqrt(25))
from math import sqrt as s
print(s(25))
from math import *
print(sqrt(25))
See the C# Test Coverage tool from my company, Semantic Designs:
It has very low overhead, handles huge systems of files, intuitive GUI, howing coverage on specific files, and generated report with coverage breakdown at method, class and package levels.
Another advantage of extracting a magic number as a constant gives the possibility to clearly document the business information.
public class Foo {
/**
* Max age in year to get child rate for airline tickets
*
* The value of the constant is {@value}
*/
public static final int MAX_AGE_FOR_CHILD_RATE = 2;
public void computeRate() {
if (person.getAge() < MAX_AGE_FOR_CHILD_RATE) {
applyChildRate();
}
}
}
Here's an example that looks for certain HTML tags so it's clear that /someregex/.test()
returns a boolean:
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
String s1 = "a";
String s2 = "c";
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));
This prints -2 and false
String s1 = "c";
String s2 = "a";
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));
This prints 2 and false
String s1 = "c";
String s2 = "c";
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));
This prints 0 and true
equals returns boolean if and only if both strings match.
compareTo is meant to not just tell if they match but also to tell which String is lesser than the other, and also by how much, lexicographically. This is mostly used while sorting in collection.
Use a BindingList and set the DataPropertyName-Property of the column.
Try the following:
...
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewCell cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
{
CellTemplate = cell,
Name = "Value",
HeaderText = "File Name",
DataPropertyName = "Value" // Tell the column which property of FileName it should use
};
gvFilesOnServer.Columns.Add(colFileName);
var filelist = GetFileListOnWebServer().ToList();
var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList
//Bind BindingList directly to the DataGrid, no need of BindingSource
gvFilesOnServer.DataSource = filenamesList
}
SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;
What is gone is gone. The only protection I know of is regular backup.
strTestString = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
full credit: http://mariaevert.dk/vba/?p=162
I think it's wise to use a textbox with no border and background as an easy and fast way to reach center aligned textblock
<TextBox
TextWrapping="Wrap"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Background="{x:Null}"
BorderBrush="{x:Null}"
/>
In your client SOAP handler you need to set javax.xml.ws.security.auth.username and javax.xml.ws.security.auth.password property as follow:
public class ClientHandler implements SOAPHandler<SOAPMessageContext>{
public boolean handleMessage(final SOAPMessageContext soapMessageContext)
{
final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outInd.booleanValue())
{
try
{
soapMessageContext.put("javax.xml.ws.security.auth.username", <ClientUserName>);
soapMessageContext.put("javax.xml.ws.security.auth.password", <ClientPassword>);
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
return true;
}
}
Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore).
Instead, since in your example tag
is the unique key, use:
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;
on duplicate key produces:
Query OK, 0 rows affected (0.07 sec)
For Python 3.x you can convert your text to raw bytes through:
bytes("my data", "encoding")
For example:
bytes("attack at dawn", "utf-8")
The object returned will work with outfile.write
.
If all the above answers failed to solve your problem, try rebooting the router.
Worked for me.
You can create a startTime and endTime of DateTime, then do endTime.Subtract(startTime). Then output your span.Seconds.
I think that should work.
I'm not totally satisfied with the other answers given. They've all got some kind of flaw to them.
Using keyPress
with event.which
is unreliable because you can't catch a backspace or a delete (as mentioned by Tarl).
Using keyDown
(as in Niva's and Tarl's answers) is a bit better, but the solution is flawed because it attempts to use event.keyCode
with String.fromCharCode()
(keyCode and charCode are not the same!).
However, what we DO have with the keydown
or keyup
event is the actual key that was pressed (event.key
).
As far as I can tell, any key
with a length of 1 is a character (number or letter) regardless of which language keyboard you're using. Please correct me if that's not true!
Then there's that very long answer from asdf. That might work perfectly, but it seems like overkill.
So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyup
or keydown
will work here, but keypress
will not)
$("input").keydown(function(event) {
var isWordCharacter = event.key.length === 1;
var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;
if (isWordCharacter || isBackspaceOrDelete) {
// do something
}
});
label
and checkbox
inputKeeps the selected item opened and togglable.
.collapse{_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
label
and named radio
inputSimilar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio"
on both inputs.
.collapse{_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
tabindex
and :focus
Similar to radio
inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.
.collapse > a{_x000D_
background: #cdf;_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
<a>Collapse 1</a>_x000D_
<div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
<a>Collapse 2</a>_x000D_
<div>Content 2....</div>_x000D_
</div>
_x000D_
:target
Similar to using radio
input, you can additionally use Tab and ⏎ keys to operate
.collapse a{_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
<a href="#targ_1">Collapse 1</a>_x000D_
<div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
<a href="#targ_2">Collapse 2</a>_x000D_
<div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
<detail>
and <summary>
tags (pure HTML)You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.
<details>_x000D_
<summary>Collapse 1</summary>_x000D_
<p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
<summary>Collapse 2</summary>_x000D_
<p>Content 2...</p>_x000D_
</details>
_x000D_
If you're referencing assemblies for projects that are in the same solution, add a Project reference (using the "Projects" tab) rather than browsing for the dll in the \bin\Debug (or \bin\Release) folder (using the "Browse" tab). See screen shot below. Only browse for the assembly/dll file if it's considered an external assembly.
I wonder same. The API of Assert is not very symmetric; for testing whether objects are the same, it provides assertSame
and assertNotSame
.
Of course, it is not too long to write:
assertFalse(foo.equals(bar));
With such an assertion, the only informative part of the output is unfortunately the name of the test method, so descriptive message should be formed separately:
String msg = "Expected <" + foo + "> to be unequal to <" + bar +">";
assertFalse(msg, foo.equals(bar));
That is of course so tedious, that it is better to roll your own assertNotEqual
. Luckily in future it will maybe be part of the JUnit: JUnit issue 22
Sample:
Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;
jQuery.fn.make_me_red = function() {
alert($(this).attr('id'));
$(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
//$(this).siblings(".hello").make_me_red();
$(this).make_me_red();
$(this).addClass("active");
});
?
Function declaration and callback in jQuery.
I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document
, and fortunately it's solved easier:
Instead of
List<Document> docs = obj.get("documents");
Document doc = docs.get(0)
which gives error on second line, One can use
List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));
OK. This is how I got it to work. I first followed MoMo's advice, that is...
If the LogCat panel is empty in Eclipse the emulator doesn't have the focus. Go to the DDMS perspective and try clicking on the 'emulator' entry in the Devices panel (top-left screen).
But to no avail.
I then attempted to reset adb
(Android Debug Bridge) as suggested by furikuretsu.
How? Window -> Devices -> upside down triangle menu button -> Reset adb.
It also didn't work, but I did get the following message:
Android hierarchyviewer: Unable to get the focused window from device
This meant that MoMo was right in that my Android device or emulator didn't have focus. However, the solution I did in my case is different.
What worked for me:
1) Replugged my Android device, which was connected to my computer via USB.
2) Restarted Eclipse, as mentioned by Abu Hamzah (although since I didn't know I can do File -> Restart
, I manually closed down Eclipse, and then restarted the application again.)
I can now see logs in my logcat.
Hope this helps you too.
It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.
My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.
Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.
For those who (unlike OP) are using the express lib:
http.get('*',function(req,res){
res.redirect('http://exmple.com'+req.url)
})
Here is a great way to build dynamic fields for a pivot query:
--summarize values to a tmp table
declare @STR varchar(1000)
SELECT @STr = COALESCE(@STr +', ', '')
+ QUOTENAME(DateRange)
from (select distinct DateRange, ID from ##pivot)d order by ID
---see the fields generated
print @STr
exec(' .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')
Firstly you need to change credentials from your local machine
git config [--global] user.name "Your Name"
git config [--global] user.email "[email protected]"
You coud use your own custom AjaxExceptionHandler or primefaces-extensions
Update your faces-config.xml
...
<factory>
<exception-handler-factory>org.primefaces.extensions.component.ajaxerrorhandler.AjaxExceptionHandlerFactory</exception-handler-factory>
</factory>
...
Add following code in your jsf page
...
<pe:ajaxErrorHandler />
...
Just try this instead:
res.sendFile('public/index1.html' , { root : __dirname});
This worked for me. the root:__dirname will take the address where server.js is in the above example and then to get to the index1.html ( in this case) the returned path is to get to the directory where public folder is.
Have a look at this picture: Graphical Projections
The glOrtho
command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.
I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);
This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.
Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.
This answer is for SO users who browse here after searching for the error.
In my case, nothing worked because I changed my username in Bitbucket.
Atlassian and Bitbucket are not completely integrated. Bitbucket uses the Atlassian user email and web app password, but allows you to have a different username.
There seems to be a bug in this process, especially since it's not clear which application or process is generating the authentication and where it's stored or editable. Changing the username breaks authentication.
There may be a way to update the username used by the credentials and Bitbucket, but I was already several hours behind when I discovered that changing my username back to what it was before restored authentication.
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
"But i want to know a better way to do this, if there is one ?"
Yes, since you seem to already have the original object, there's no reason to fetch it again from the Array.
function Update(keyValue, newKey, newValue)
{
keyValue.Key = newKey;
keyValue.Value = newValue;
}
Here is another way to convert Drawable resource into Bitmap in android:
Drawable drawable = getResources().getDrawable(R.drawable.input);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
For Visual Studio 2019 you may not find Project -> Add Reference option. Use Project -> Add Project Reference. Then in dialog window navigate to Browse tab and use Browse to find and attach your dll.
It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal
and oldVal
refer to the same object. Vue will not keep an old copy of an object that you mutated.
Had you replaced the object with another one, Vue would have provided you with correct references.
Read the Note
section in the docs. (vm.$watch
)
public Point2D(Point2D point) : this(point.X, point.Y) { }
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
It is matter of performance and memory usage, compile and keep the complied pattern if you need to use it a lot. A typical usage of regex is to validated user input (format), and also format output data for users, in these classes, saving the complied pattern, seems quite logical as they usually called a lot.
Below is a sample validator, which is really called a lot :)
public class AmountValidator {
//Accept 123 - 123,456 - 123,345.34
private static final String AMOUNT_REGEX="\\d{1,3}(,\\d{3})*(\\.\\d{1,4})?|\\.\\d{1,4}";
//Compile and save the pattern
private static final Pattern AMOUNT_PATTERN = Pattern.compile(AMOUNT_REGEX);
public boolean validate(String amount){
if (!AMOUNT_PATTERN.matcher(amount).matches()) {
return false;
}
return true;
}
}
As mentioned by @Alan Moore, if you have reusable regex in your code, (before a loop for example), you must compile and save pattern for reuse.
Here is my solution:
public static String encode(String key, String data) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
public static void main(String [] args) throws Exception {
System.out.println(encode("key", "The quick brown fox jumps over the lazy dog"));
}
Or you can return the hash encoded in Base64:
Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
The output in hex is as expected:
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'
; worked for me.
closing the varchar
/string
with two pairs of single quotes did the trick. Other option could be to use using
keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'
; Remember using
keyword will not work, if you are using EXECUTE IMMEDIATE
to execute DDL's with parameters, however, using quotes will work for DDL's.
Or this:
f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}
Maybe the condition you are using is incorrect:
$str1 == "taste" && $str2 == "waste"
The program will enter into THEN
part only when both of the stated conditions are true.
You can try with $str1 == "taste" || $str2 == "waste"
. This will execute the THEN
part if anyone of the above conditions are true.
Try this on Rails
Time.new + 10.days
Try this on Ruby
require 'date'
DateTime.now.next_day(10).to_time
ObjectFactory fact = new ObjectFactory();
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());
public class SecondandThirdHighestElement {
public static void main(String[] args) {
int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
// create three temp variable and store arr of first element in that temp variable so that it will compare with other element
int firsttemp = arr[0];
int secondtemp = arr[0];
int thirdtemp = arr[0];
//check and find first highest value from array by comparing with other elements if found than save in the first temp variable
for (int i = 0; i < arr.length; i++) {
if(firsttemp <arr[i]){
firsttemp = arr[i];
}//if
}//for
//check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
for (int i = 0; i < arr.length; i++) {
if(secondtemp < arr[i] && firsttemp>arr[i]){
secondtemp = arr[i];
}//if
}//for
//check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array
for (int i = 0; i < arr.length; i++) {
if(thirdtemp < arr[i] && secondtemp>arr[i]){
thirdtemp = arr[i];
}//if
}//for
System.out.println("First Highest Value:"+firsttemp);
System.out.println("Second Highest Value:"+secondtemp);
System.out.println("Third Highest Value:"+thirdtemp);
}//main
}//class
I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png
worked.
// Page.aspx //
// To count checklist item
int a = ChkMonth.Items.Count;
int count = 0;
for (var i = 0; i < a; i++)
{
if (ChkMonth.Items[i].Selected == true)
{
count++;
}
}
// Page.aspx.cs //
// To access checkbox list item's value //
string YrStrList = "";
foreach (ListItem listItem in ChkMonth.Items)
{
if (listItem.Selected)
{
YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
}
}
sMonthStr = YrStrList.ToString();
Yes, you can change the default shell from Explorer.exe to a specific application.
In Regedit, navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon. The current shell should be Explorer.exe. Change it to YourApp.exe. That will change the shell for all users who log on to the machine. If you only want to change it for a specific user, go to the same key in HKEY_CURRENT_USER instead.
It work for Mac also
import os
path="/Users/HOME/Desktop/Addl Work/TimeSeries-Done"
os.chdir(path)
To check working directory
os.getcwd()
It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.
git clone <Repo> <DestinationDirectory>
Clone the repository located at Repo into the folder called DestinationDirectory on the local machine.
You can use jsonpipe if you just need the output (and more comfortable with command line):
cat bookmarks.json | jsonpipe |grep uri
jQuery('input[name="inputName"]:checked').val()
Note: static synchronized methods and blocks work on the Class object.
public class MyClass {
// locks MyClass.class
public static synchronized void foo() {
// do something
}
// similar
public static void foo() {
synchronized(MyClass.class) {
// do something
}
}
}
VideoView can only Stream 3gp videos I recommend this code to stream your video or try a higher version of android. Try Video Online Streaming.
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
String videourl = "http://something.com/blah.mp4";
Uri uri = Uri.parse(videourl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setDataAndType(uri, "video/mp4");
startActivity(intent);
}
If you came across the error when tried to generate a jks file (keystore), so try adding
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool
before running the command, like so:
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
Other answers explain how to insert a string at the beginning of another String
or StringBuilder
(or StringBuffer
).
However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.
When you write:
String s = "Jam";
s = "Hello " + s;
you are actually causing a new String
object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String
object at all.
1 - It is technically possible to use reflection to break abstraction on String
objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String
object was created explicitly via new String(...)
it could be shared, or it could share internal state with other String
objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final
is undefined. Mutation of String
objects is dangerous.
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
To check from the command-line, in one single command, but include major, minor, micro version, releaselevel and serial, then invoke the same Python interpreter (i.e. same path) as you're using for your script:
> path/to/your/python -c "import sys; print('{}.{}.{}-{}-{}'.format(*sys.version_info))"
3.7.6-final-0
Note: .format()
instead of f-strings or '.'.join()
allows you to use arbitrary formatting and separator chars, e.g. to make this a greppable one-word string. I put this inside a bash utility script that reports all important versions: python, numpy, pandas, sklearn, MacOS, xcode, clang, brew, conda, anaconda, gcc/g++ etc. Useful for logging, replicability, troubleshootingm bug-reporting etc.
You can put a ^
in the beginning of a character set to match anything but those characters.
[^=]*
will match everything but =
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
First of all, in your device go to Dev. Option -> ADB over Network after do it:
$ adb connect <your device adb network>
$ react-native run-android
(or run-ios, by the way)
if this has successfully your device has installed app-debug.apk, open app-debug and go to Dev. Settings -> Debug server host & port for device, type in your machine's IP address (generally, System preference -> Network), as in the example below < your machine's IP address >:8081 (whihout inequality)
finally, execute the command below
$ react-native start --port=8081
try another ports, and verify that you machine and your device are same network.
This more verbose solution provides greater control on what happens in case of duplicate maximum value (in this example, it will take one of the corresponding rows randomly)
library(dplyr)
df %>% group_by(A, B) %>%
mutate(the_rank = rank(-value, ties.method = "random")) %>%
filter(the_rank == 1) %>% select(-the_rank)
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
There is no difference, except that Pragma
is only defined as applicable to the requests by the client, whereas Cache-Control
may be used by both the requests of the clients and the replies of the servers.
So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:
HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.
Note: because the meaning of "Pragma: no-cache as a response header field is not actually specified, it does not provide a reliable replacement for "Cache-Control: no-cache" in a response
The way I would read the above:
if you're writing a client and need no-cache
:
Pragma: no-cache
in your requests, since you may not know if Cache-Control
is supported by the server;Cache-Control
if you're writing a server:
Cache-Control
; if not found, check for Pragma: no-cache
, and execute the Cache-Control: no-cache
logic;Cache-Control
.Of course, reality might be different from what's written or implied in the RFC!
More about "load average" showing CPU load over 1 minute, 5 minutes and 15 minutes
Linux, Mac, and other Unix-like systems display “load average” numbers. These numbers tell you how busy your system’s CPU, disk, and other resources are. They’re not self-explanatory at first, but it’s easy to become familiar with them.
WIKI: example, one can interpret a load average of "1.73 0.60 7.98" on a single-CPU system as:
during the last minute, the system was overloaded by 73% on average (1.73 runnable processes, so that 0.73 processes had to wait for a turn for a single CPU system on average).
during the last 5 minutes, the CPU was idling 40% of the time on average.
during the last 15 minutes, the system was overloaded 698% on average (7.98 runnable processes, so that 6.98 processes had to wait for a turn for a single CPU system on average) if dual core mean: 798% - 200% = 598%.
You probably have a system with multiple CPUs or a multi-core CPU. The load average numbers work a bit differently on such a system. For example, if you have a load average of 2 on a single-CPU system, this means your system was overloaded by 100 percent — the entire period of time, one process was using the CPU while one other process was waiting. On a system with two CPUs, this would be complete usage — two different processes were using two different CPUs the entire time. On a system with four CPUs, this would be half usage — two processes were using two CPUs, while two CPUs were sitting idle.
To understand the load average number, you need to know how many CPUs your system has. A load average of 6.03 would indicate a system with a single CPU was massively overloaded, but it would be fine on a computer with 8 CPUs.
more info : Link
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")
I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.
Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.
As Sanf0rd mentioned, Google launched the BottomNavigationView as part of the Design Support Library version 25.0.0. The limitations he mentioned are mostly true, except that you CAN change the background color of the view and even the text color and icon tint color. It also has an animation when you add more than 4 items (sadly it cannot be enabled or disabled manually).
I wrote a detailed tutorial about it with examples and an accompanying repository, which you can read here: https://blog.autsoft.hu/now-you-can-use-the-bottom-navigation-view-in-the-design-support-library/
You have to add these in your app level build.gradle
:
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
You can include it in your layout like this:
<android.support.design.widget.BottomNavigationView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="@color/darkGrey"
app:itemIconTint="@color/bottom_navigation_item_background_colors"
app:itemTextColor="@color/bottom_navigation_item_background_colors"
app:menu="@menu/menu_bottom_navigation" />
You can specify the items via a menu resource like this:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_one"
android:icon="@android:drawable/ic_dialog_map"
android:title="One"/>
<item
android:id="@+id/action_two"
android:icon="@android:drawable/ic_dialog_info"
android:title="Two"/>
<item
android:id="@+id/action_three"
android:icon="@android:drawable/ic_dialog_email"
android:title="Three"/>
<item
android:id="@+id/action_four"
android:icon="@android:drawable/ic_popup_reminder"
android:title="Four"/>
</menu>
And you can set the tint and text color as a color list, so the currently selected item is highlighted:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:color="@color/colorAccent"
android:state_checked="false"/>
<item
android:color="@android:color/white"
android:state_checked="true"/>
</selector>
Finally, you can handle the selection of the items with an OnNavigationItemSelectedListener:
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_one:
// Switch to page one
break;
case R.id.action_two:
// Switch to page two
break;
case R.id.action_three:
// Switch to page three
break;
}
return true;
}
});
Oracle
's locking concept is quite different from that of the other systems.
When a row in Oracle
gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.
This means that locking a record in Oracle
means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE
on a read only tablespace.
More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.
This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.
Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.
You can obtain some special locks, like locked metadata objects (using v$locked_object
), lock waits (using v$session
) etc, but not the list of all locks on all objects in the database.
There's a function that does exactly this:
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
You can use a TextView and change its background to the image you want to use
You can use FormData API https://developer.mozilla.org/en-US/docs/Web/API/FormData
var data = new FormData;
data.append('from', from);
data.append('to', to);
$http({
url: '/path',
method: 'POST',
data: data,
transformRequest: false,
headers: { 'Content-Type': undefined }
})
This solution from http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ")
private WebElementFacade emailLinkToVerifyAccount;
This approach will work for you, hopefully.
just set the hidden field with javascript :
document.getElementById('elementId').value = 'whatever';
or do I miss something?
Found the answer on a blog and it's as simple as:
strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
And you'll get the days between the 2 dates.
There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )
The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.
To make this work, your function needs to loop through each of the Areas
in the input ranges. For example:
Function calculateIt(Sessions As Range, Customers As Range) As Single
' check we passed the same number of areas
If (Sessions.Areas.Count <> Customers.Areas.Count) Then
calculateIt = CVErr(xlErrNA)
Exit Function
End If
Dim mySession, myCustomers As Range
' run through each area and calculate
For a = 1 To Sessions.Areas.Count
Set mySession = Sessions.Areas(a)
Set myCustomers = Customers.Areas(a)
' calculate them...
Next a
End Function
The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9)
.
Hope that helps :)
Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.
This, however works:
<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>
If you are looking in linux..
npm update will not work mostly am not sure reason but following steps will help you to resolve issue...
Terminal process to upgrade node 4.x to 6.x.
$ node -v
v4.x
Check node path
$ which node
/usr/bin/node
Download latest(6.x) node files from [Download][1]
[1]: https://nodejs.org/dist/v6.9.2/node-v6.9.2-linux-x64.tar.xz and unzip files keep in /opt/node-v6.9.2-linux-x64/.
Now unlink current node and link with latest as following
$ unlink /usr/bin/node
$ ln -s /opt/node-v6.9.2-linux-x64/bin/node node
$ node -v
$ v6.9.2
Check the file permissions, if edited
Fail:
$ sudo chmod 776 /etc/mysql/my.cnf
$ sudo service mysql restart
mysql stop/waiting
start: Job failed to start
Ok:
$ sudo chmod 774 /etc/mysql/my.cnf
$ sudo service mysql restart
stop: Unknown instance:
mysql start/running, process 9564
I faced the same problem. Found the fix here.
Basically just install this.
shasum output:
3e0de8af516c15547602977db939d8c2e44fcc0b visualcppbuildtools_full.exe
md5sum output:
MD5 (visualcppbuildtools_full.exe) = 8d4afd3b226babecaa4effb10d69eb2e
Run your pip installation command again. If everything works fine, its good. Or you might face the following error like me:
Finished generating code
LINK : fatal error LNK1158: cannot run 'rc.exe'
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158
Found the fix for the above problem here: Visual Studio can't build due to rc.exe
That basically says
Add this to your PATH environment variables:
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
Copy these files:
rc.exe
rcdll.dll
From
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
To
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin
It works like a charm
Create custom error pages through .htaccess file
1. 404 - page not found
RewriteEngine On
ErrorDocument 404 /404.html
2. 500 - Internal Server Error
RewriteEngine On
ErrorDocument 500 /500.html
3. 403 - Forbidden
RewriteEngine On
ErrorDocument 403 /403.html
4. 400 - Bad request
RewriteEngine On
ErrorDocument 400 /400.html
5. 401 - Authorization Required
RewriteEngine On
ErrorDocument 401 /401.html
You can also redirect all error to single page. like
RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html
I've written this little plugin for jQuery which will make all calls to .val(value)
update the angular element if present:
(function($, ng) {
'use strict';
var $val = $.fn.val; // save original jQuery function
// override jQuery function
$.fn.val = function (value) {
// if getter, just return original
if (!arguments.length) {
return $val.call(this);
}
// get result of original function
var result = $val.call(this, value);
// trigger angular input (this[0] is the DOM object)
ng.element(this[0]).triggerHandler('input');
// return the original result
return result;
}
})(window.jQuery, window.angular);
Just pop this script in after jQuery and angular.js and val(value)
updates should now play nice.
Minified version:
!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);
Example:
// the function_x000D_
(function($, ng) {_x000D_
'use strict';_x000D_
_x000D_
var $val = $.fn.val;_x000D_
_x000D_
$.fn.val = function (value) {_x000D_
if (!arguments.length) {_x000D_
return $val.call(this);_x000D_
}_x000D_
_x000D_
var result = $val.call(this, value);_x000D_
_x000D_
ng.element(this[0]).triggerHandler('input');_x000D_
_x000D_
return result;_x000D_
_x000D_
}_x000D_
})(window.jQuery, window.angular);_x000D_
_x000D_
(function(ng){ _x000D_
ng.module('example', [])_x000D_
.controller('ExampleController', function($scope) {_x000D_
$scope.output = "output";_x000D_
_x000D_
$scope.change = function() {_x000D_
$scope.output = "" + $scope.input;_x000D_
}_x000D_
});_x000D_
})(window.angular);_x000D_
_x000D_
(function($){ _x000D_
$(function() {_x000D_
var button = $('#button');_x000D_
_x000D_
if (button.length)_x000D_
console.log('hello, button');_x000D_
_x000D_
button.click(function() {_x000D_
var input = $('#input');_x000D_
_x000D_
var value = parseInt(input.val());_x000D_
value = isNaN(value) ? 0 : value;_x000D_
_x000D_
input.val(value + 1);_x000D_
});_x000D_
});_x000D_
})(window.jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div ng-app="example" ng-controller="ExampleController">_x000D_
<input type="number" id="input" ng-model="input" ng-change="change()" />_x000D_
<span>{{output}}</span>_x000D_
<button id="button">+</button>_x000D_
</div>
_x000D_
sleep()
causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield()
basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
You can use == to compare with a zero value composite literal because all fields are comparable:
if (Session{}) == session {
fmt.Println("is zero value")
}
Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.
The use of ==
above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.
An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use
if session.playerId == "" {
fmt.Println("is zero value")
}
Layout or view to bitmap:
private Bitmap createBitmapFromLayout(View tv) {
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
tv.measure(spec, spec);
tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.getMeasuredWidth(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.translate((-tv.getScrollX()), (-tv.getScrollY()));
tv.draw(c);
return b;
}
Calling Method:
Bitmap src = createBitmapFromLayout(View.inflate(this, R.layout.sample, null)/* or pass your view object*/);
According to Parsing HTML documents - The end,
The browser parses the HTML source and runs deferred scripts.
A DOMContentLoaded
is dispatched at the document
when all the HTML has been parsed and have run. The event bubbles to the window
.
The browser loads resources (like images) that delay the load event.
A load
event is dispatched at the window
.
Therefore, the order of execution will be
DOMContentLoaded
event listeners of window
in the capture phaseDOMContentLoaded
event listeners of document
DOMContentLoaded
event listeners of window
in the bubble phaseload
event listeners (including onload
event handler) of window
A bubble load
event listener (including onload
event handler) in document
should never be invoked. Only capture load
listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.
window.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('window - DOMContentLoaded - capture'); // 1st_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('document - DOMContentLoaded - capture'); // 2nd_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('document - DOMContentLoaded - bubble'); // 2nd_x000D_
});_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('window - DOMContentLoaded - bubble'); // 3rd_x000D_
});_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
console.log('window - load - capture'); // 4th_x000D_
}, true);_x000D_
document.addEventListener('load', function(e) {_x000D_
/* Filter out load events not related to the document */_x000D_
if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0)_x000D_
console.log('document - load - capture'); // DOES NOT HAPPEN_x000D_
}, true);_x000D_
document.addEventListener('load', function() {_x000D_
console.log('document - load - bubble'); // DOES NOT HAPPEN_x000D_
});_x000D_
window.addEventListener('load', function() {_x000D_
console.log('window - load - bubble'); // 4th_x000D_
});_x000D_
_x000D_
window.onload = function() {_x000D_
console.log('window - onload'); // 4th_x000D_
};_x000D_
document.onload = function() {_x000D_
console.log('document - onload'); // DOES NOT HAPPEN_x000D_
};
_x000D_
May be this is useful to you.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}
Take a step back! Firstly, you're assuming the user is using a foreign locale on their device, which is not a sound assumption for justifying taking over the button text of the file picker, and making it say what you want it to.
It is reasonable that you want to control every item of language visible on your page. The content of the File Upload control is not part of the HTML though. There is more content behind this control, for example, in WebKit, it also says "No file chosen" next to the button.
There are very hacky workarounds that attempt this (e.g. like those mentioned in @ChristopheD's answer), but none of them truly succeed:
Deviating from the native controls is always a risky thing, there is a whole host of different devices your users could be using, and whatever workaround you choose, you will not have tested it in every one of those devices.
However, there is an even bigger reason why all attempts fail from a User Experience perspective: there is even more non-localized content behind this control, the file selection dialog itself. Once the user is subject to traversing their file system or what not to select a file to upload, they will be subjected to the host Operating System locale.
Are you sure you're doing your user any justice by deviating from the native control, just to localize the text, when as soon as they click it, they're just going to get the Operating System locale anyway?
The best you can do for your users is to ensure you have adequate localised guidance surrounding your file input control. (e.g. Form field label, hint text, tooltip text).
Sorry. :-(
--
This answer is for those looking for any justification not to localise the file upload control.
I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:
Creating Event Handlers on the Windows Forms Designer
Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:
- Click the form or control that you want to create an event handler for.
- In the Properties window, click the Events button
- In the list of available events, click the event that you want to create an event handler for.
- In the box to the right of the event name, type the name of the handler and press ENTER
Remove the width:100%;
declarations.
Block elements should take up the whole available width by default.
But as your system grows in size and functionality... i think that returning always a json is not a bad idea at all. Is more a architectural / "big scale design" matter.
You can think about returing always a JSON with two know fields : code and data. Where code is a numeric code specifying the success of the operation to be done and data is any aditional data related with the operation / service requested.
Come on, when we use a backend a service provider, any service can be checked to see if it worked well.
So i stick, to not let spring manage this, exposing hybrid returning operations (Some returns data other nothing...).. instaed make sure that your server expose a more homogeneous interface. Is more simple at the end of the day.
Given Array:
int[] givenArray = {2,2,3,3,4,5};
Converting integer array to Integer List
One way: boxed() -> returns the IntStream
List<Integer> givenIntArray1 = Arrays.stream(givenArray)
.boxed()
.collect(Collectors.toList());
Second Way: map each element of the stream to Integer and then collect
NOTE: Using mapToObj you can covert each int element into string stream, char stream etc by casing i to (char)i
List<Integer> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->i)
.collect(Collectors.toList());
Converting One array Type to Another Type Example:
List<Character> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->(char)i)
.collect(Collectors.toList());
This happened to work in my case:
$text = utf8_decode($text)
I turns the black diamond character into a question mark so you can:
$text = str_replace('?', '', utf8_decode($text));
IIRC the purpose of the form method attribute was to define different transport methods. Consequently, HTML 5.2 only defines GET, POST, and DIALOG methods for transport and dialog action, not how the server should process the data.
Ruby-on-rails solves this problem by using POST/GET for everything and adding a hidden form variable that defines the actual ReST method. This approach is more clumsy and error-prone, but does remove the burden from both the HTML standard and browser developers.
The form method was defined before ReST, so you cannot define ReST in HTML, even after enabling Apache and PHP because the browsers conform to HTML and therefore default to GET/POST for all non-HTML defined values. That means, when you send a form to the browser with a PUT method, the browser changes that to GET and uses that instead. The hidden variable, however, passes through everything unchanged, so you can use that to customise your form handling process.
Hope that helps
WITH uniq AS (
SELECT DISTINCT posts.id as post_id
FROM posts
JOIN votes ON votes.post_id = posts.id
-- GROUP BY not needed anymore
-- GROUP BY posts.id
)
SELECT COUNT(*)
FROM uniq;
You can do that like this:
from datetime import datetime
from threading import Timer
x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
This will execute a function (eg. hello_world) in the next day at 1a.m.
EDIT:
As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:
from datetime import datetime, timedelta
from threading import Timer
x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x
secs=delta_t.total_seconds()
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()