Others have answered in terms of how to handle the specific escaping in this case.
A broader answer is not to try to do it yourself. Use an XML API - there are plenty available for just about every modern programming platform in existence.
XML APIs will handle things like this for you automatically, making it a lot harder to go wrong. Unless you're writing an XML API yourself, you should rarely need to worry about the details like this.
What you need to know in one place:
ASPNETCORE_
. :
as a separater. If the platform doesn't allow colons in environment variable keys, use __
instead.ApplicationHost.config
. Using the IIS Configuration Editor will cause your inputs to be written to the application's Web.config
-- and will be overwritten with the next deployment!For modifying ApplicationHost.config
, you want to use appcmd.exe
to make sure your modifications are consistent. Example: %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /+"environmentVariables.[name='ASPNETCORE_AWS:Region',value='eu-central-1']" /commit:site
Characters that are not URL-safe can be escaped as Unicode, like %u007b
for left curly bracket.
%systemroot%\system32\inetsrv\appcmd.exe list config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore
%systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /-"environmentVariables.[name='ASPNETCORE_MyKey',value='value-to-be-removed']" /commit:site
.You can use this
WebView browser = (WebView) findViewById(R.id.webview);
browser.getSettings().setLoadWithOverviewMode(true);
browser.getSettings().setUseWideViewPort(true);
this fixes size based on screen size.
I had the same problem. I want to create custom result for my api controllers, to call them like
return Ok("some text");
Then i did this: 1) Create custom result type with singletone
public sealed class EmptyResult : IHttpActionResult
{
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent) { Content = new StringContent("Empty result") });
}
}
2) Create custom controller with new method:
public class CustomApiController : ApiController
{
public IHttpActionResult EmptyResult()
{
return new EmptyResult();
}
}
And then i can call them in my controllers, like this:
public IHttpActionResult SomeMethod()
{
return EmptyResult();
}
Try this request :
SELECT column_name, data_type FROM information_schema.columns WHERE
table_name = 'YOUR_TABLE' AND column_name = 'YOUR_FIELD';
Add this to your XML layout:
android:ellipsize="marquee"
android:focusable="false"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="To Make An textView Scrollable Inside The TextView Using Marquee"
And in code you have to write the following lines:
textview.setSelected(true);
textView.setMovementMethod(new ScrollingMovementMethod());
It will depend on the implementation, but from the Sun Java 6 source code:
int newCapacity = (oldCapacity * 3)/2 + 1;
That's in the ensureCapacity
method. Other JDK implementations may vary.
One more simple variant -
$ while read line
do
set $line # assigns words in line to positional parameters
echo "$3 $5"
done < file
Perhaps you're trying to modularize your package. I'm assuming that package1
and package2
are, in a way, part of the same package but for readability you're splitting those into multiple files.
If the previous case was yours, you could use the same package name into those multiples files and it will be like if there were the same file.
This is an example:
add.go
package math
func add(n1, n2 int) int {
return n1 + n2
}
subtract.go
package math
func subtract(n1, n2 int) int {
return n1 - n2
}
donothing.go
package math
func donothing(n1, n2 int) int {
s := add(n1, n2)
s = subtract(n1, n2)
return s
}
I am not a Go expert and this is my first post in StackOveflow, so if you have some advice it will be well received.
Today :
DateTime.Today
Tomorrow :
DateTime.Today.AddDays(1)
Yesterday :
DateTime.Today.AddDays(-1)
I use the following to rewrite the author for an entire repository, including tags and all branches:
git filter-branch --tag-name-filter cat --env-filter "
export GIT_AUTHOR_NAME='New name';
export GIT_AUTHOR_EMAIL='New email'
" -- --all
Then, as described in the MAN page of filter-branch, remove all original refs backed up by filter-branch
(this is destructive, backup first):
git for-each-ref --format="%(refname)" refs/original/ | \
xargs -n 1 git update-ref -d
Essentially it means you don't have the index you are trying to reference. For example:
df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)
will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:
df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)
Hope that answers your question!
Use
#pragma once
at the top of header files, so if they're included more than once in a translation unit, the text of the header will only get included and parsed once.
Why can't we make a unique id as below.
We can use DateTime.Now.Ticks and Guid.NewGuid().ToString() to combine together and make a unique id.
As the DateTime.Now.Ticks is added, we can find out the Date and Time in seconds at which the unique id is created.
Please see the code.
var ticks = DateTime.Now.Ticks;
var guid = Guid.NewGuid().ToString();
var uniqueSessionId = ticks.ToString() +'-'+ guid; //guid created by combining ticks and guid
var datetime = new DateTime(ticks);//for checking purpose
var datetimenow = DateTime.Now; //both these date times are different.
We can even take the part of ticks in unique id and check for the date and time later for future reference.
Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.
The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.
The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).
What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?
Sub AddReferences(wbk As Workbook)
' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub
Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
Dim i As Integer
On Error GoTo EH
With wbk.VBProject.References
For i = 1 To .Count
If .Item(i).Name = sRefName Then
Exit For
End If
Next i
If i > .Count Then
.AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
End If
End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
Resume EX
Resume ' debug code
End Sub
Public Sub DebugPrintExistingRefs()
Dim i As Integer
With Application.ThisWorkbook.VBProject.References
For i = 1 To .Count
Debug.Print " AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
Next i
End With
End Sub
The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.
Swift 2.x answer:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.getResultSetFromDB(docids)
}
I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:
const today = moment(1557697070824.94).toObject();
You should obtain an object with this properties:
today: {
date: 15,
hours: 2,
milliseconds: 207,
minutes: 31,
months: 4
seconds: 22,
years: 2019
}
It is very useful when you have to calculate dates.
For non MAMP or XAMPP users on OSX (with homebrew installed):
brew install homebrew/php/php56-mcrypt
Cheers!
Try the below logic to find out the median:
Consider a table with the below numbers: 1,1,2,3,4,5
THE MEDIAN is 2.5
with tempa as ( select num,count(num) over() as Cnt, row_number() over (order by num) as Rnum from temp), tempb as ( select round(cnt/2) as ref_value from tempa where mod(cnt,2)<>0 union all select round(cnt/2) from tempa where mod(cnt,2)=0 union all select round(cnt/2+1) from tempa where mod(cnt,2)=0 ) select avg(num) from tempa where rnum in (select * from tempb);
Error with Uncaught SyntaxError: Unexpected token <
using @Mario answer but that was only part of my problem. Another problem is, javascript doesn't get any data from PHP file. That was solved using this code, inside PHP file: header("Content-Type: text/javascript; charset=utf-8");
This answer is found on this link, where I opened another question to solve this issue: Can't receive json data from PHP in Chrome and Opera
just add in your backend API new property's into response body. from example .net core:
[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
var users = await _repo.GetUsers(userParams);
var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);
// create new object and add into it total count param etc
var UsersListResult = new
{
usersToReturn,
currentPage = users.CurrentPage,
pageSize = users.PageSize,
totalCount = users.TotalCount,
totalPages = users.TotalPages
};
return Ok(UsersListResult);
}
In body response it look like this
{
"usersToReturn": [
{
"userId": 1,
"username": "[email protected]",
"firstName": "Joann",
"lastName": "Wilson",
"city": "Armstrong",
"phoneNumber": "+1 (893) 515-2172"
},
{
"userId": 2,
"username": "[email protected]",
"firstName": "Booth",
"lastName": "Drake",
"city": "Franks",
"phoneNumber": "+1 (800) 493-2168"
}
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44
}
Three ways:
1.
int main ()
{
for (int i=2; i<100; i++)
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
break;
else if (j+1 > sqrt(i)) {
cout << i << " ";
}
}
return 0;
}
2.
int main ()
{
for (int i=2; i<100; i++)
{
bool prime=true;
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << " ";
}
return 0;
}
3.
#include <vector>
int main()
{
std::vector<int> primes;
primes.push_back(2);
for(int i=3; i < 100; i++)
{
bool prime=true;
for(int j=0;j<primes.size() && primes[j]*primes[j] <= i;j++)
{
if(i % primes[j] == 0)
{
prime=false;
break;
}
}
if(prime)
{
primes.push_back(i);
cout << i << " ";
}
}
return 0;
}
Edit: In the third example, we keep track of all of our previously calculated primes. If a number is divisible by a non-prime number, there is also some prime <= that divisor which it is also divisble by. This reduces computation by a factor of primes_in_range/total_range.
There is a much easier way to run Java, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.Building on @Adrien Be's answer above and using the code that Brian Huisman & David koelle created, here is a modified prototype sorting for an array of objects:
//Usage: unsortedArrayOfObjects.alphaNumObjectSort("name");
//Test Case: var unsortedArrayOfObjects = [{name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a10"}, {name: "a5"}, {name: "a13"}, {name: "a20"}, {name: "a8"}, {name: "8b7uaf5q11"}];
//Sorted: [{name: "8b7uaf5q11"}, {name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a5"}, {name: "a8"}, {name: "a10"}, {name: "a13"}, {name: "a20"}]
// **Sorts in place**
Array.prototype.alphaNumObjectSort = function(attribute, caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z].sortArray = new Array();
var x = 0, y = -1, n = 0, i, j;
while (i = (j = t[attribute].charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z].sortArray[++y] = "";
n = m;
}
this[z].sortArray[y] += j;
}
}
this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a.sortArray[x]) && (bb = b.sortArray[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else {
return (aa > bb) ? 1 : -1;
}
}
}
return a.sortArray.length - b.sortArray.length;
});
for (var z = 0; z < this.length; z++) {
// Here we're deleting the unused "sortArray" instead of joining the string parts
delete this[z]["sortArray"];
}
}
You can also use my app, App Detective to view the manifest file of any app you have installed on your device.
My solution is to set the environment variable as spring.profiles.active=development
. So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows
application.properties
system properties
environment variable
The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).
There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".
The difference between both has been explained here. But what has not been explained is the fact that <<include>>
and <<extend>>
should simply not be used at all.
If you read Bittner/Spence you know that use cases are about synthesis, not analysis. A re-use of use cases is nonsense. It clearly shows that you have cut your domain wrongly. Added value must be unique per se. The only re-use of added value I know is franchise. So if you are in burger business, nice. But everywhere else your task as BA is to try to find an USP. And that must be presented in good use cases.
Whenever I see people using one of those relations it is when they try to do functional decomposition. And that's plain wrong.
To put it simple: if you can answer your boss without hesitation "I have done ..." then the "..." is your use case since you got money for doing it. (That will also make clear that "login" is not a use case at all.)
In that respect, finding self standing use cases that are included or extend other use cases is very unlikely. Eventually you can use <<extend>>
to show optionality of your system, i.e. some licensing schema which allows to include use cases for some licenses or to omit them. But else - just avoid them.
OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could do that using the oid column.
OIDs are implemented using 4-byte unsigned integers. They are not unique–OID counter will wrap around at 2³²-1. OID are also used to identify data types (see /usr/include/postgresql/server/catalog/pg_type_d.h
).
In my experience, the feature is generally unused in most postgres-backed applications (probably in part because they're non-standard), and their use is essentially deprecated:
In PostgreSQL 8.1 default_with_oids is off by default; in prior versions of PostgreSQL, it was on by default.
The use of OIDs in user tables is considered deprecated, so most installations should leave this variable disabled. Applications that require OIDs for a particular table should specify WITH OIDS when creating the table. This variable can be enabled for compatibility with old applications that do not follow this behavior.
Here is a non-numpy solution:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]
As you want a C++ solution, you could use Qt. It has a QHttp class you can use.
You can check the docs:
http->setHost("qt.nokia.com");
http->get(QUrl::toPercentEncoding("/index.html"));
Qt also has a lot more to it that you could use in a common C++ app.
I think the possibilities are less, but FireBug (addon of FireFox) has some network analysis tools, too.
func post() {
NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"),
object: nil,
userInfo:["key0": "value", "key1": 1234])
}
func addObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(someMethod),
name: Notification.Name("SomeNotificationName"),
object: nil)
}
@objc func someMethod(_ notification: Notification) {
let info0 = notification.userInfo?["key0"]
let info1 = notification.userInfo?["key1"]
}
Replace Notification.Name("SomeNotificationName")
with .someNotificationName
:
extension Notification.Name {
static let someNotificationName = Notification.Name("SomeNotificationName")
}
Replace "key0"
and "key1"
with Notification.Key.key0
and Notification.Key.key1
:
extension Notification {
enum Key: String {
case key0
case key1
}
}
Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...
Regarding 4., you still need to ensure that your "dummy script stub" is actually the target URL after all the rewriting is done, or you won't see anything!
A similar/related trick (see this question) is to insert a temporary rule such as:
RewriteRule (.*) /show.php?url=$1 [END]
Where show.php
is some very simple script that just displays its $_GET
parameters (you can display environment variables too, if you want).
This will stop the rewriting at the point you insert it into the ruleset, rather like a breakpoint in a debugger.
If you're using Apache <2.3.9, you'll need to use [L]
rather than [END]
, and you may then need to add:
RewriteRule ^show.php$ - [L]
At the very top of your ruleset, if the URL /show.php
is itself being rewritten.
In many workflows where you want to attach a default / initial value for arbitrary keys, you don't need to hash each key individually ahead of time. You can use collections.defaultdict
. For example:
from collections import defaultdict
d = defaultdict(lambda: None)
print(d[1]) # None
print(d[2]) # None
print(d[3]) # None
This is more efficient, it saves having to hash all your keys at instantiation. Moreover, defaultdict
is a subclass of dict
, so there's usually no need to convert back to a regular dictionary.
For workflows where you require controls on permissible keys, you can use dict.fromkeys
as per the accepted answer:
d = dict.fromkeys([1, 2, 3, 4])
Yes, template member functions are perfectly legal and useful on numerous occasions.
The only caveat is that template member functions cannot be virtual.
For Mapping Composite primary key using Entity framework we can use two approaches.
1) By Overriding the OnModelCreating() Method
For ex: I have the model class named VehicleFeature as shown below.
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
The Code in my DBContext would be like ,
public class VegaDbContext : DbContext
{
public DbSet<Make> Makes{get;set;}
public DbSet<Feature> Features{get;set;}
public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)
{
}
// we override the OnModelCreating method here.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}
}
2) By Data Annotations.
public class VehicleFeature
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int VehicleId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
Please refer the below links for the more information.
1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
It is a little rough, but here is something I put together that is comprised entirely of CSS and HTML.
This example also makes use of the :hover
pseudo class for each data cell <td>
. Elements can be easily updated to meet your needs, and the hover can quickly be disabled.
(However, I have not yet gotten the :hover
to properly work for full rows <tr>
. The last hovered row does not display with rounded corners on the bottom. I'm sure there is something simple that is getting overlooked.)
table.dltrc {_x000D_
width: 95%;_x000D_
border-collapse: separate;_x000D_
border-spacing: 0px;_x000D_
border: solid black 2px;_x000D_
border-radius: 8px;_x000D_
}_x000D_
_x000D_
tr.dlheader {_x000D_
text-align: center;_x000D_
font-weight: bold;_x000D_
border-left: solid black 1px;_x000D_
padding: 2px_x000D_
}_x000D_
_x000D_
td.dlheader {_x000D_
background: #d9d9d9;_x000D_
text-align: center;_x000D_
font-weight: bold;_x000D_
border-left: solid black 1px;_x000D_
border-radius: 0px;_x000D_
padding: 2px_x000D_
}_x000D_
_x000D_
tr.dlinfo,_x000D_
td.dlinfo {_x000D_
text-align: center;_x000D_
border-left: solid black 1px;_x000D_
border-top: solid black 1px;_x000D_
padding: 2px_x000D_
}_x000D_
_x000D_
td.dlinfo:first-child,_x000D_
td.dlheader:first-child {_x000D_
border-left: none;_x000D_
}_x000D_
_x000D_
td.dlheader:first-child {_x000D_
border-radius: 5px 0 0 0;_x000D_
}_x000D_
_x000D_
td.dlheader:last-child {_x000D_
border-radius: 0 5px 0 0;_x000D_
}_x000D_
_x000D_
_x000D_
/*===== hover effects =====*/_x000D_
_x000D_
_x000D_
/*tr.hover01:hover,_x000D_
tr.hover02:hover {_x000D_
background-color: #dde6ee;_x000D_
}*/_x000D_
_x000D_
_x000D_
/* === ROW HOVER === */_x000D_
_x000D_
_x000D_
/*tr.hover02:hover:last-child {_x000D_
background-color: #dde6ee;_x000D_
border-radius: 0 0 6px 6px;_x000D_
}*/_x000D_
_x000D_
_x000D_
/* === CELL HOVER === */_x000D_
_x000D_
td.hover01:hover {_x000D_
background-color: #dde6ee;_x000D_
}_x000D_
_x000D_
td.hover02:hover {_x000D_
background-color: #dde6ee;_x000D_
}_x000D_
_x000D_
td.hover02:first-child {_x000D_
border-radius: 0 0 0 6px;_x000D_
}_x000D_
_x000D_
td.hover02:last-child {_x000D_
border-radius: 0 0 6px 0;_x000D_
}
_x000D_
<body style="background:white">_x000D_
<br>_x000D_
<center>_x000D_
<table class="dltrc" style="background:none">_x000D_
<tbody>_x000D_
<tr class="dlheader">_x000D_
<td class="dlheader">Subject</td>_x000D_
<td class="dlheader">Title</td>_x000D_
<td class="dlheader">Format</td>_x000D_
</tr>_x000D_
<tr class="dlinfo hover01">_x000D_
<td class="dlinfo hover01">One</td>_x000D_
<td class="dlinfo hover01">Two</td>_x000D_
<td class="dlinfo hover01">Three</td>_x000D_
</tr>_x000D_
<tr class="dlinfo hover01">_x000D_
<td class="dlinfo hover01">Four</td>_x000D_
<td class="dlinfo hover01">Five</td>_x000D_
<td class="dlinfo hover01">Six</td>_x000D_
</tr>_x000D_
<tr class="dlinfo hover01">_x000D_
<td class="dlinfo hover01">Seven</td>_x000D_
<td class="dlinfo hover01">Eight</td>_x000D_
<td class="dlinfo hover01">Nine</td>_x000D_
</tr>_x000D_
<tr class="dlinfo2 hover02">_x000D_
<td class="dlinfo hover02">Ten</td>_x000D_
<td class="dlinfo hover01">Eleven</td>_x000D_
<td class="dlinfo hover02">Twelve</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</center>_x000D_
</body>
_x000D_
For some database like DB2 and PostgreSQL, you have to use the key word LATERAL
for specifying a sub query in the LEFT JOIN
: (here, it's for DB2)
SELECT f.*, a.*
FROM feeds f
LEFT JOIN LATERAL
(
SELECT artist_id, feed_id
FROM feeds_artists sfa
WHERE sfa.feed_id = f.id
fetch first 1 rows only
) fa ON fa.feed_id = f.id
LEFT JOIN artists a ON a.artist_id = fa.artist_id
The markup for that document could look like the following:
<body>
<header>...</header>
<nav>...</nav>
<article>
<section>
...
</section>
</article>
<aside>...</aside>
<footer>...</footer>
</body>
You may find more information in this article on A List Apart.
Try using "w+"
as the write mode instead of just "w"
:
File.open("out.txt", "w+") { |file| file.write("boo!") }
From the term "automatic login" I suppose security (password protection) is not of key importance here.
The guidelines for solution could be to use a JavaScript bookmark (idea borrowed form a nice game published on M&M's DK site).
The idea is to create a javascript file and store it locally. It should do the login data entering depending on current site address. Just an example using jQuery:
// dont forget to include jQuery code
// preferably with .noConflict() in order not to break the site scripts
if (window.location.indexOf("mail.google.com") > -1) {
// Lets login to Gmail
jQuery("#Email").val("[email protected]");
jQuery("#Passwd").val("superSecretPassowrd");
jQuery("#gaia_loginform").submit();
}
Now save this as say login.js
Then create a bookmark (in any browser) with this (as an) url:
javascript:document.write("<script type='text/javascript' src='file:///path/to/login.js'></script>");
Now when you go to Gmail and click this bookmark you will get automatically logged in by your script.
Multiply the code blocks in your script, to add more sites in the similar manner. You could even combine it with window.open(...)
functionality to open more sites, but that may get the script inclusion more complicated.
Note: This only illustrates an idea and needs lots of further work, it's not a complete solution.
I use PyDev/LiClipse and haven't really figured out how to run all tests at once from the GUI. (edit: you right click the root test folder and choose Run as -> Python unit-test
This is my current workaround:
import unittest
def load_tests(loader, tests, pattern):
return loader.discover('.')
if __name__ == '__main__':
unittest.main()
I put this code in a module called all
in my test directory. If I run this module as a unittest from LiClipse then all tests are run. If I ask to only repeat specific or failed tests then only those tests are run. It doesn't interfere with my commandline test runner either (nosetests) -- it's ignored.
You may need to change the arguments to discover
based on your project setup.
As @Ming mentioned:
pip install -r file.txt
Here's a simple line to force update all dependencies:
while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt
You need xlutils.copy
. Try something like this:
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
Keep in mind you can't overwrite cells by default as noted in this question.
Suppose you want to install Laravel Collective. It's currently at version 6.x but you want version 5.8. You can run the following command:
composer require "laravelcollective/html":"^5.8.0"
A good example is shown here in the documentation: https://laravelcollective.com/docs/5.5/html
Assuming the OP wants a Java answer:
As of JDBC3 / Java 6 there's the isValid() method which should be used rather than inventing one's own method.
The implementer of the driver is required to execute some sort of query against the database when this method id called. You - as a mere JDBC user - do not have to know or understand what this query is. All you have to do is to trust that the creator of the JDBC driver has done his/her work properly.
If you are using Eloquent, in your model put:
public function getPriceAttribute($price)
{
return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));
}
Where getPriceAttribute is your field on database. getSomethingAttribute.
For student level programs, Clang has the benefit that it is, by default, stricter wrt. the C standard. For example, the following K&R version of Hello World is accepted without warning by GCC, but rejected by Clang with some pretty descriptive error messages:
main()
{
puts("Hello, world!");
}
With GCC, you have to give it -Werror
to get it to really make a point about this not being a valid C89 program. Also, you still need to use c99
or gcc -std=c99
to get the C99 language.
Example: In a simple terms if you have a web service of calculator.
WSDL: WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on.
SOAP: Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.
Why we use SOAP and WSDL: For platform independent data exchange.
EDIT: In a normal day to day life example:
WSDL: When we go to a restaurant we see the Menu Items, those are the WSDL's.
Proxy Classes: Now after seeing the Menu Items we make up our Mind (Process our mind on what to order): So, basically we make Proxy classes based on WSDL Document.
SOAP: Then when we actually order the food based on the Menu's: Meaning we use proxy classes to call upon the service methods which is done using SOAP. :)
C++ and Java are different languages.
The Java C-style cast operator is much more restricted than the C/C++ version. Effectively the Java cast is like the C++ dynamic_cast if the object you have cannot be cast to the new class you will get a run time (or if there is enough information in the code a compile time) exception. Thus the C++ idea of not using C type casts is not a good idea in Java
Try the following commands in terminal, this will work better:
apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
On Ubuntu :
Try
$ cat /usr/local/cuda/version.txt
or
$ cat /usr/local/cuda-8.0/version.txt
Sometimes the folder is named "Cuda-version".
If none of above works, try going to
$ /usr/local/
And find the correct name of your Cuda folder.
Output should be similar to:
CUDA Version 8.0.61
It works for me with $(window).focus().
var w;
var src = 'http://pagetoprint';
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
w = $('<iframe></iframe>');
w.attr('src', src);
w.css('display', 'none');
$('body').append(w);
w.load(function() {
w[0].focus();
w[0].contentWindow.print();
});
$(window).focus(function() {
console.log('After print');
});
}
else {
w = window.open(src);
$(w).unload(function() {
console.log('After print');
});
}
You can split the string into characters and filter it.
<?php
function filter_alphanum($string) {
$characters = str_split($string);
$alphaNumeric = array_filter($characters,"ctype_alnum");
return join($alphaNumeric);
}
$res = filter_alphanum("a!bc!#123");
print_r($res); // abc123
?>
Although the z-index of the .modal
is higher than that of the .modal-backdrop
, that .modal
is in a parent div #content-wrap
which has a lower z-index than .modal-backdrop
(z-index: 1002 vs z-index: 1030).
Because the parent has lower z-index than the .modal-backdrop
everything in it will be behind the modal, irrespective of any z-index given to the children.
If you remove the z-index
you have set on both the body div#fullContainer #content-wrap
and also on the #ctrlNavPanel
, everything seems to work ok.
body div#fullContainer #content-wrap {
background: #ffffff;
bottom: 0;
box-shadow: -5px 0px 8px #000000;
position: absolute;
top: 0;
width: 100%;
}
#ctrlNavPanel {
background: #333333;
bottom: 0;
box-sizing: content-box;
height: 100%;
overflow-y: auto;
position: absolute;
top: 0;
width: 250px;
}
NOTE: I think that you may have initially used z-indexes on the #content-wrap and #ctrlNavPanel to ensure the nav sits behind, but that's not necessary because the nav element comes before the content-wrap in the HTML, so you only need to position them, not explicitly set a stacking order.
EDIT As Schmalzy picked up on, the links are no longer clickable. This is because the full-container is 100% wide and so covers the navigation. The quickest way to fix this is to place the navigation inside that div:
<div id="fullContainer">
<aside id="ctrlNavPanel">
<ul class="nav-link-list">
<li><label>Menu</label></li>
<li><a href="/"><span class="fa fa-lg fa-home"></span> Home</a></li>
<li><a><span class="fa fa-lg fa-group"></span>About Us</a></li>
<li><a><span class="fa fa-lg fa-book"></span> Contacts</a></li>
</ul>
</aside>
<div id="content-wrap">
...
</div>
</div>
Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:
public abstract class CollectionBase<T> : IList<T>
{
...
public Type ElementType
{
get
{
return typeof(T);
}
}
}
I have found this approach useful, and is easy to understand for any newcomers to generics.
Short answer: H.264 MPEG (MP4)
Long answer from Apple.com:
Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,
Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
In C++20 you'll be able to do:
std::cout << std::format("{:03}", 25); // prints 025
In the meantime you can use the {fmt} library, std::format
is based on.
Disclaimer: I'm the author of {fmt} and C++20 std::format
.
An old question but I recently needed to do an AS3>JS port, and for the sake of speed I wrote a simple AS3-style Dictionary object for JS:
http://jsfiddle.net/MickMalone1983/VEpFf/2/
If you didn't know, the AS3 dictionary allows you to use any object as the key, as opposed to just strings. They come in very handy once you've found a use for them.
It's not as fast as a native object would be, but I've not found any significant problems with it in that respect.
API:
//Constructor
var dict = new Dict(overwrite:Boolean);
//If overwrite, allows over-writing of duplicate keys,
//otherwise, will not add duplicate keys to dictionary.
dict.put(key, value);//Add a pair
dict.get(key);//Get value from key
dict.remove(key);//Remove pair by key
dict.clearAll(value);//Remove all pairs with this value
dict.iterate(function(key, value){//Send all pairs as arguments to this function:
console.log(key+' is key for '+value);
});
dict.get(key);//Get value from key
To be clear on the bits vs byte, vs characters.
2**8
possible combinations: 256 combinationsWhen you look at a hex character,
[0-9] + [a-f]
: the full range of 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
2**4
: that means one hex character can store 4 bits in a byte (half a byte).2**8
combinations.[0-9a-f][0-9a-f]
and that represents both halfs of a byte (we call a half-byte a nibble).When you look at a regular single-byte character, (we're totally going to skip multi-byte and wide-characters here)
2**8
range.md5()
could store all that, you'd see all the lowercase letters, all the uppercase letters, all the punctuation and things like ¡°ÀÐàð
, whitespace like (newlines, and tabs), and control characters (which you can't even see and many of which aren't in use).So they're clearly different and I hope that provides the best break down of the differences.
Given returned json from your://site.com:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below,
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java
In your case the jsp name is error.jsp so the path should be something like below
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java
in line no 124 you are trying to access a null object which results in null pointer exception.
I got this error when I restored a database and didn't add the user account and privileges back in. Another site gave me an authentication error, so I didn't think to check that, but as soon as I added the user account back everything worked again!
Try using this:-
mkdir -p dir;
NOTE:- This will also create any intermediate directories that don't exist; for instance,
Check out mkdir -p
or try this:-
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$Message" 1>&2
fi
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
//Step1 - Using string funClass to convert to class
String funClass = "package.myclass";
Class c = Class.forName(funClass);
//Step2 - instantiate an object of the class abov
Object o = c.newInstance();
//Prepare array of the arguments that your function accepts, lets say only one string here
Class[] paramTypes = new Class[1];
paramTypes[0]=String.class;
String methodName = "mymethod";
//Instantiate an object of type method that returns you method name
Method m = c.getDeclaredMethod(methodName, paramTypes);
//invoke method with actual params
m.invoke(o, "testparam");
I know I'm late to this party but the simplest solution I've come across is to split your text area content on new line characters and update the rows for the textarea element.
<textarea id="my-text-area"></textarea>
<script>
$(function() {
const txtArea = $('#my-text-area')
const val = txtArea.val()
const rowLength = val.split('\n')
txtArea.attr('rows', rowLength)
})
</script>
What I just did, to open a simple python script by double clicking. I just added a batch file to the directory containing the script:
@echo off
python exercise.py
pause>nul
(I have the python executable on my system path. If not one would need include its complete path of course.)
Then I just can double click on the batch file to run the script. The third line keeps the cmd window from being dismissed as soon as the script ends, so you can see the results. :) When you're done just close the command window.
iostream doesn't know it's at the end of the file until it tries to read that first character past the end of the file.
The sample code at cplusplus.com says to do it like this: (But you shouldn't actually do it this way)
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
}
A better idiom is to move the read into the loop condition, like so:
(You can do this with all istream
read operations that return *this
, including the >>
operator)
char c;
while(is.get(c))
cout << c;
The whole :action =>, :controller =>
bit that I've seen around a lot didn't work for me.
Spent hours digging and this method definitely worked for me in a loop.
<%=link_to( image_tag(participant.user.profile_pic.url(:small)), user_path(participant.user), :class=>"work") %>
Ruby on Rails using link_to with image_tag
Also, I'm using Rails 4.
%time%
should work, provided enough time has elapsed between calls:
@echo OFF
@echo %time%
ping -n 1 -w 1 127.0.0.1 1>nul
@echo %time%
On my system I get the following output:
6:46:13.50
6:46:13.60
Try This:
using System;
using System.Configuration;
using System.Web.Configuration;
namespace SampleApplication.WebConfig
{
public partial class webConfigFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
//Save the Modified settings of AppSettings.
webConfigApp.Save();
}
}
}
You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(...)
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(...)
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(...)
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(...)
For more info have a look here: http://matplotlib.org/examples/pylab_examples/subplots_demo.html
For complex layouts, you should consider using gridspec: http://matplotlib.org/users/gridspec.html
var obj=[
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["id"]+"</td>";
var td2="<td>"+obj[i]["name"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3);
}
font-size: 0
to parent container
(Source: https://twitter.com/garand/status/183253526313566208)
Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm
$('#myFile').change(function () {
LoadFile("myFile");//function to do processing of file.
$('#myFile').val('');// set the value to empty of myfile control.
});
like wrote here:
I just ran into this problem, even without transferring from Eclipse, and was frustrated because I kept showing no compile or packageDebug errors. Somehow it all fixes itself if you clean and THEN run packageDebug. Don't worry about the deprecated method statement - it seems to be a generic notice to developers.
Open up a commandline, and in your project's root directory, run:
./gradlew clean packageDebug
Obviously, if either of these steps shows errors, you should fix those...But when they both succeed you should now be able to find the apk when you navigate the local path -- and even better, your program should install/run on the device/emulator!
I have a Samsung Galaxy and I had the same issue as you. Here's how to fix it:
In device manager on your Windows PC, even though it might say the USB drivers are installed correctly, there may exist corruption.
I went into device manager and uninstalled SAMSUNG Android USB Composite Device and made sure to check the box 'delete driver software'. Now the device will have an exclamation mark etc. I right clicked and installed the driver again (refresh copy). This finally made adb acknowledge my phone as an emulator.
As others noted, for Nexus 4, you can also try this fix.
If you feel like reading here is "My introduction to OO methods"
The idea behind Object Oriented paradigm is to "threat" the software is composed of .. well "objects". Objects in real world have properties, for instance if you have an Employee, the employee has a name, an employee id, a position, he belongs to a department etc. etc.
The object also know how to deal with its attributes and perform some operations on them. Let say if we want to know what an employee is doing right now we would ask him.
employe whatAreYouDoing.
That "whatAreYouDoing" is a "message" sent to the object. The object knows how to answer to that questions, it is said it has a "method" to resolve the question.
So, the way objects have to expose its behavior are called methods. Methods thus are the artifact object have to "do" something.
Other possible methods are
employee whatIsYourName
employee whatIsYourDepartmentsName
etc.
Functions in the other hand are ways a programming language has to compute some data, for instance you might have the function addValues( 8 , 8 ) that returns 16
// pseudo-code
function addValues( int x, int y ) return x + y
// call it
result = addValues( 8,8 )
print result // output is 16...
Since first popular programming languages ( such as fortran, c, pascal ) didn't cover the OO paradigm, they only call to these artifacts "functions".
for instance the previous function in C would be:
int addValues( int x, int y )
{
return x + y;
}
It is not "natural" to say an object has a "function" to perform some action, because functions are more related to mathematical stuff while an Employee has little mathematic on it, but you can have methods that do exactly the same as functions, for instance in Java this would be the equivalent addValues function.
public static int addValues( int x, int y ) {
return x + y;
}
Looks familiar? That´s because Java have its roots on C++ and C++ on C.
At the end is just a concept, in implementation they might look the same, but in the OO documentation these are called method.
Here´s an example of the previously Employee object in Java.
public class Employee {
Department department;
String name;
public String whatsYourName(){
return this.name;
}
public String whatsYourDeparmentsName(){
return this.department.name();
}
public String whatAreYouDoing(){
return "nothing";
}
// Ignore the following, only set here for completness
public Employee( String name ) {
this.name = name;
}
}
// Usage sample.
Employee employee = new Employee( "John" ); // Creates an employee called John
// If I want to display what is this employee doing I could use its methods.
// to know it.
String name = employee.whatIsYourName():
String doingWhat = employee.whatAreYouDoint();
// Print the info to the console.
System.out.printf("Employee %s is doing: %s", name, doingWhat );
Output:
Employee John is doing nothing.
The difference then, is on the "domain" where it is applied.
AppleScript have the idea of "natural language" matphor , that at some point OO had. For instance Smalltalk. I hope it may be reasonable easier for you to understand methods in objects after reading this.
NOTE: The code is not to be compiled, just to serve as an example. Feel free to modify the post and add Python example.
You can use the INSERT ... SELECT
statement to get the MAX()+1
value and insert at the same time:
INSERT INTO
customers( customer_id, firstname, surname )
SELECT MAX( customer_id ) + 1, 'jim', 'sock' FROM customers;
Note: You need to drop the VALUES
from your INSERT
and make sure the SELECT
selected fields match the INSERT
declared fields.
Above answer is useful but, I found code which helps you to download text file directly on button click.
In this code you can also change filename
as you wish. It's pure javascript function with HTML5.
Works for me!
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
Try this:
<img src="images/background.jpg"
style="width:100%;height:100%;position:absolute;top:0;left:0;z-index:-5000;">
http://thewebthought.blogspot.com/2010/10/css-making-background-image-fit-any.html
ZoneId z = ZoneId.of( "America/Montreal" ); // A date only has meaning within a specific time zone. At any given moment, the date varies around the globe by zone.
LocalDate ld =
givenJavaUtilDate.toInstant() // Convert from legacy class `Date` to modern class `Instant` using new methods added to old classes.
.atZone( z ) // Adjust into the time zone in order to determine date.
.toLocalDate(); // Extract date-only value.
LocalDate today = LocalDate.now( z ); // Get today’s date for specific time zone.
LocalDate kwanzaaStart = today.withMonth( Month.DECEMBER ).withDayOfMonth( 26 ); // Kwanzaa starts on Boxing Day, day after Christmas.
LocalDate kwanzaaStop = kwanzaaStart.plusWeeks( 1 ); // Kwanzaa lasts one week.
Boolean isDateInKwanzaaThisYear = (
( ! today.isBefore( kwanzaaStart ) ) // Short way to say "is equal to or is after".
&&
today.isBefore( kwanzaaStop ) // Half-Open span of time, beginning inclusive, ending is *exclusive*.
)
Date-time work commonly employs the "Half-Open" approach to defining a span of time. The beginning is inclusive while the ending is exclusive. So a week starting on a Monday runs up to, but does not include, the following Monday.
Java 8 and later comes with the java.time
framework built-in. Supplants the old troublesome classes including java.util.Date/.Calendar
and SimpleDateFormat
. Inspired by the successful Joda-Time library. Defined by JSR 310. Extended by the ThreeTen-Extra project.
An Instant
is a moment on the timeline in UTC with nanosecond resolution.
Instant
Convert your java.util.Date
objects to Instant objects.
Instant start = myJUDateStart.toInstant();
Instant stop = …
If getting java.sql.Timestamp
objects through JDBC from a database, convert to java.time.Instant in a similar way. A java.sql.Timestamp
is already in UTC so no need to worry about time zones.
Instant start = mySqlTimestamp.toInstant() ;
Instant stop = …
Get the current moment for comparison.
Instant now = Instant.now();
Compare using the methods isBefore, isAfter, and equals.
Boolean containsNow = ( ! now.isBefore( start ) ) && ( now.isBefore( stop ) ) ;
LocalDate
Perhaps you want to work with only the date, not the time-of-day.
The LocalDate
class represents a date-only value, without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;
To get the current date, specify a time zone. At any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
We can use the isEqual
, isBefore
, and isAfter
methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.
Boolean containsToday = ( ! today.isBefore( start ) ) && ( today.isBefore( stop ) ) ;
Interval
If you chose to add the ThreeTen-Extra library to your project, you could use the Interval
class to define a span of time. That class offers methods to test if the interval contains, abuts, encloses, or overlaps other date-times/intervals.
The Interval
class works on Instant
objects. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
We can adjust the LocalDate
into a specific moment, the first moment of the day, by specifying a time zone to get a ZonedDateTime
. From there we can get back to UTC by extracting a Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Interval interval =
Interval.of(
start.atStartOfDay( z ).toInstant() ,
stop.atStartOfDay( z ).toInstant() );
Instant now = Instant.now();
Boolean containsNow = interval.contains( now );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time
classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time
classes?
java.time
functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.The ThreeTen-Extra project extends java.time
with additional classes. This project is a proving ground for possible future additions to java.time
. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You only need to add .Returns(Task.FromResult(0));
after the Callback.
Example:
mock.Setup(arg => arg.DoSomethingAsync())
.Callback(() => { <my code here> })
.Returns(Task.FromResult(0));
For safety, I always parenthesise my comparisons and space them out. That way, I don't have to rely on operator precedence:
if(
((i==0) && (b==2))
||
((c==3) && !(f==5))
)
Very easy step by step (100% working and tested)
step1: Create method on first view controller
func updateProcessStatus(isCompleted : Bool){
if isCompleted{
self.labelStatus.text = "Process is completed"
}else{
self.labelStatus.text = "Process is in progress"
}
}
step2: Set delegate while push to second view controller
@IBAction func buttonAction(_ sender: Any) {
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
secondViewController.delegate = self
self.navigationController?.pushViewController(secondViewController, animated: true)
}
step3: set delegate like
class ViewController: UIViewController,ProcessStatusDelegate {
step4: Create protocol
protocol ProcessStatusDelegate:NSObjectProtocol{
func updateProcessStatus(isCompleted : Bool)
}
step5: take a variable
var delegate:ProcessStatusDelegate?
step6: While go back to previous view controller call delegate method so first view controller notify with data
@IBAction func buttonActionBack(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: true)
self.navigationController?.popViewController(animated: true)
}
@IBAction func buttonProgress(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: false)
self.navigationController?.popViewController(animated: true)
}
The android:gravity
sets the gravity (position) of the children whereas the android:layout_gravity
sets the position of the view itself. Hope it helps
In my case I am running 3 nodes in VM's by using Hyper-V. By using the following steps I was able to "restart" the cluster after restarting all VM's.
(Optional) Swap off
$ swapoff -a
You have to restart all Docker containers
$ docker restart $(docker ps -a -q)
Check the nodes status after you performed step 1 and 2 on all nodes (the status is NotReady)
$ kubectl get nodes
Restart the node
$ systemctl restart kubelet
Check again the status (now should be in Ready status)
Note: I do not know if it does metter the order of nodes restarting, but I choose to start with the k8s master node and after with the minions. Also it will take a little bit to change the node state from NotReady to Ready
My experience with this was that when I had this in every execution it was fine using the provider as a string like this
Security.addProvider(new BounctCastleProvider());
new JcaPEMKeyConverter().setProvider("BC");
But when I optimized and put the following in the constructor:
if(bounctCastleProvider == null) {
bounctCastleProvider = new BouncyCastleProvider();
}
if(Security.getProvider(bouncyCastleProvider.getName()) == null) {
Security.addProvider(bouncyCastleProvider);
}
Then I had to use provider like this or I would get the above error:
new JcaPEMKeyConverter().setProvider(bouncyCastleProvider);
I am using bcpkix-jdk15on version 1.65
SQL uses three-valued logic for truth values. The IN
query produces the expected result:
SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE col IN (NULL, 1)
-- returns first row
But adding a NOT
does not invert the results:
SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT col IN (NULL, 1)
-- returns zero rows
This is because the above query is equivalent of the following:
SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT (col = NULL OR col = 1)
Here is how the where clause is evaluated:
| col | col = NULL?¹? | col = 1 | col = NULL OR col = 1 | NOT (col = NULL OR col = 1) |
|-----|----------------|---------|-----------------------|-----------------------------|
| 1 | UNKNOWN | TRUE | TRUE | FALSE |
| 2 | UNKNOWN | FALSE | UNKNOWN?²? | UNKNOWN?³? |
Notice that:
NULL
yields UNKNOWN
OR
expression where none of the operands are TRUE
and at least one operand is UNKNOWN
yields UNKNOWN
(ref)NOT
of UNKNOWN
yields UNKNOWN
(ref)You can extend the above example to more than two values (e.g. NULL, 1 and 2) but the result will be same: if one of the values is NULL
then no row will match.
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
This might be redundant but the above most voted answer says .then(function (success)
and that didn't work for me as of Angular version 1.5.8
. Instead use response
then inside the block response.data
got me my json data I was looking for.
$http({
method: 'get',
url: 'data/data.json'
}).then(function (response) {
console.log(response, 'res');
data = response.data;
},function (error){
console.log(error, 'can not get data.');
});
This is an odd solution, but it worked for me.
I wanted to uninstall Visual Studio 2015 and do a clean install afterwards, but when I tried to remove it through the Control Panel, it was giving me a generic error.
I fixed it by deleting the Visual Studio 2015 folder in Program Files (x86). After that, the Control Panel uninstall worked fine.
import platform
is_windows = any(platform.win32_ver())
or
import sys
is_windows = hasattr(sys, 'getwindowsversion')
foreach (array('one', 'two', 'three') as $v) {
switch ($v) {
case (function ($v) {
if ($v == 'two') return $v;
return 'one';
})($v):
echo "$v min \n";
break;
}
}
this works fine for languages supporting enclosures
The use of http.createClient
is now deprecated. You can pass Headers in options collection as below.
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();
The approach you're looking for is FillDown
. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:
Sub FillDown()
Dim strFormulas(1 To 3) As Variant
With ThisWorkbook.Sheets("Sheet1")
strFormulas(1) = "=SUM(A2:B2)"
strFormulas(2) = "=PRODUCT(A2:B2)"
strFormulas(3) = "=A2/B2"
.Range("C2:E2").Formula = strFormulas
.Range("C2:E11").FillDown
End With
End Sub
Screenshots:
Result as of line: .Range("C2:E2").Formula = strFormulas
:
Result as of line: .Range("C2:E11").FillDown
:
Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown
, much like what you did.
Hope this helps!
I know this is a fairly old question, but there is now a nicer API available natively in newer browsers. The fetch()
method allow you to make web requests.
For example, to request some json from /get-data
:
var opts = {
method: 'GET',
headers: {}
};
fetch('/get-data', opts).then(function (response) {
return response.json();
})
.then(function (body) {
//doSomething with body;
});
See here for more details.
import java.io.*;
import java.net.*;
public class filedown {
public static void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(address);
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t" + numWritten);
}
catch (Exception exception) {
exception.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
catch (IOException ioe) {
}
}
}
public static void download(String address) {
int lastSlashIndex = address.lastIndexOf('/');
if (lastSlashIndex >= 0 &&
lastSlashIndex < address.length() - 1) {
download(address, (new URL(address)).getFile());
}
else {
System.err.println("Could not figure out local file name for "+address);
}
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
download(args[i]);
}
}
}
If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Kotlin
linearLayout.setBackgroundColor(Color.rgb(0xf4,0x43,0x36))
or
<color name="newColor">#f44336</color>
-
linearLayout.setBackgroundColor(ContextCompat.getColor(vista.context, R.color.newColor))
try this:
<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />
If you are expecting double, decimal, float, integer
why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).
instead of (double)value
use decimal.Parse(value.ToString())
or Convert.ToDecimal(value)
If you're still getting this error message while using the WCF Test Client, it's because the client has a separate MaxBufferSize setting.
To correct the issue:
A list of editable settings will appear, including MaxBufferSize.
Note: Auto-generated proxy clients also set MaxBufferSize to 65536 by default.
CHAR
is a fixed-length data type that uses as much space as possible. So a:= a||'one ';
will require more space than is available. Your problem can be reduced to the following example:
declare
v_foo char(50);
begin
v_foo := 'A';
dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
-- next line will raise:
-- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
v_foo := v_foo || 'B';
dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));
end;
/
Never use char
. For rationale check the following question (read also the links):
You want to check whether Examples exists in Range("A1").Value If it fails then to check Example right? I think mycode will work perfect. Please check.
Sub test()
Dim string1 As String, string2 As String
string1 = "Examples"
string2 = "Example"
If InStr(1, Range("A1").Value, string1) > 0 Then
x = 1
ElseIf InStr(1, Range("A1").Value, string2) > 0 Then
x = 2
End If
End Sub
A lot of answers ask you to use END
, but if that's not working for you, try:
text.delete("1.0", "end-1c")
There is no i
in XPath.
Either you use literal numbers: //img[@title='Modify'][1]
Or you build the expression string dynamically: '//img[@title='Modify']['+i+']'
(but keep in mind that dynamic XPath expressions do not work from within XSLT).
Or does XPath support specified selection of nodes which are not under same parent node?
Yes: (//img[@title='Modify'])[13]
This //img[@title='Modify'][i]
means "any <img>
with a title of 'Modify' and a child element named <i>
."
If you want to write the output to a file you can use the stdout-argument of subprocess.call
.
It takes None
, subprocess.PIPE
, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.
You need to open a file with something like open
and pass the object or file descriptor integer to call
:
f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=f)
I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.
As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT
. Any of the above mentioned values works as well, you can redirect to different places.
Python 3.5, 2018
If you don't know what the encoding but the unicode parser is having issues you can open the file in Notepad++
and in the top bar select Encoding->Convert to ANSI
. Then you can write your python like this
with open('filepath', 'r', encoding='ANSI') as file:
for word in file.read().split():
print(word)
Given a file named Me.Jar:
Use the Java jar
command -- I am using jdk1.8.0_31 so I would type
C:\Program Files (x86)\Java\jdk1.8.0_31\bin\jar xf me.jar
That should extract the file to the folder bin. Look for the file .class in my case my Me.jar contains a Valentine.class
Type java Valentine
and press Enter and your message file will be opened.
Modified question is - What's the difference between A mutex and a "binary" semaphore in "Linux"?
Ans: Following are the differences – i) Scope – The scope of mutex is within a process address space which has created it and is used for synchronization of threads. Whereas semaphore can be used across process space and hence it can be used for interprocess synchronization.
ii) Mutex is lightweight and faster than semaphore. Futex is even faster.
iii) Mutex can be acquired by same thread successfully multiple times with condition that it should release it same number of times. Other thread trying to acquire will block. Whereas in case of semaphore if same process tries to acquire it again it blocks as it can be acquired only once.
One options will be to show the selected option above (or below) the select list like following:
HTML
<div id="selText"><span> </span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#mySelect").change(function(){
//$("#selText").html($($(this).children("option:selected")[0]).text());
var txt = $($(this).children("option:selected")[0]).text();
$("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
});
});
</script>
PS:- Set height of div#selText otherwise it will keep shifting select list downward.
I had a very similar issue with the same error message. "Changes not staged for commit", yet when I do a diff it shows differences. I finally figured out that a while back I had changed a directories case. ex. "PostgeSQL" to "postgresql". As I remember now sometimes git will leave a file or two behind in the old case directory. Then you will commit a new version to the new case.
Thus git doesn't know which one to rely on. So to resolve it, I had to go onto the github's website. Then you're able to view both cases. And you must delete all the files in the incorrect cased directory. Be sure that you have the correct version saved off or in the correct cased directory.
Once you have deleted all the files in the old case directory, that whole directory will disappear. Then do a commit.
At this point you should be able to do a Pull on your local computer and not see the conflicts any more. Thus being able to commit again. :)
RewriteEngine on
RewriteBase /basic_test/
RewriteRule ^index.php$ test.php
I wrote a VBA file to add a tool cleaning these abnormally biggest file. This script clear all columns and rows after the last cells realy used to reset the last cells ( [Ctrl]+[End] ), and it also provides enable images compression.
I dev an AddIns with auto install (just run it with macro enabled) to include in context menu many new buttons:
This is based on KB of Microsoft office 2003 and answer of PP. with personals improvement :
SOLUTION > you can download my *.xlam file ToolsKit
the main code is
Sub ClearExcessRowsAndColumns()
Dim ar As Range, r As Double, c As Double, tr As Double, tc As Double
Dim wksWks As Worksheet, ur As Range, arCount As Integer, i As Integer
Dim blProtCont As Boolean, blProtScen As Boolean, blProtDO As Boolean
Dim shp As Shape
Application.ScreenUpdating = False
On Error Resume Next
For Each wksWks In ActiveWorkbook.Worksheets
Err.Clear
'Store worksheet protection settings and unprotect if protected.
blProtCont = wksWks.ProtectContents
blProtDO = wksWks.ProtectDrawingObjects
blProtScen = wksWks.ProtectScenarios
wksWks.Unprotect ""
If Err.Number = 1004 Then
Err.Clear
MsgBox "'" & wksWks.Name & "' is protected with a password and cannot be checked.", vbInformation
Else
Application.StatusBar = "Checking " & wksWks.Name & ", Please Wait..."
r = 0
c = 0
'Determine if the sheet contains both formulas and constants
Set ur = Union(wksWks.UsedRange.SpecialCells(xlCellTypeConstants), wksWks.UsedRange.SpecialCells(xlCellTypeFormulas))
'If both fails, try constants only
If Err.Number = 1004 Then
Err.Clear
Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeConstants)
End If
'If constants fails then set it to formulas
If Err.Number = 1004 Then
Err.Clear
Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeFormulas)
End If
'If there is still an error then the worksheet is empty
If Err.Number <> 0 Then
Err.Clear
If wksWks.UsedRange.Address <> "$A$1" Then
ur.EntireRow.Delete
Else
Set ur = Nothing
End If
End If
'On Error GoTo 0
If Not ur Is Nothing Then
arCount = ur.Areas.Count
'determine the last column and row that contains data or formula
For Each ar In ur.Areas
i = i + 1
tr = ar.Range("A1").Row + ar.Rows.Count - 1
tc = ar.Range("A1").Column + ar.Columns.Count - 1
If tc > c Then c = tc
If tr > r Then r = tr
Next
'Determine the area covered by shapes
'so we don't remove shading behind shapes
For Each shp In wksWks.Shapes
tr = shp.BottomRightCell.Row
tc = shp.BottomRightCell.Column
If tc > c Then c = tc
If tr > r Then r = tr
Next
Application.StatusBar = "Clearing Excess Cells in " & wksWks.Name & ", Please Wait..."
Set ur = wksWks.Rows(r + 1 & ":" & wksWks.Rows.Count)
'Reset row height which can also cause the lastcell to be innacurate
ur.EntireRow.RowHeight = wksWks.StandardHeight
ur.Clear
Set ur = wksWks.Columns(ColLetter(c + 1) & ":" & ColLetter(wksWks.Columns.Count))
'Reset column width which can also cause the lastcell to be innacurate
ur.EntireColumn.ColumnWidth = wksWks.StandardWidth
ur.Clear
End If
End If
'Reset protection.
wksWks.Protect "", blProtDO, blProtCont, blProtScen
Err.Clear
Next
Application.StatusBar = False
' prepare les combinaison de touches pour la validation automatique de la fenetre
' Application.SendKeys "%(oe)~{TAB}~"
' ouvre la fenetre de compression des images
Application.CommandBars.ExecuteMso "PicturesCompress"
Application.ScreenUpdating = True
End Sub
Function ColLetter(ColNumber As Integer) As String
ColLetter = Left(Cells(1, ColNumber).Address(False, False), Len(Cells(1, ColNumber).Address(False, False)) - 1)
End Function
My bet:
^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$
Explained:
Domain name is built from segments. Here is one segment (except final):
[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?
It can have 1-63 characters, does not start or end with '-'.
Now append '.' to it and repeat at least one time:
(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+
Then attach final segment, which is 2-63 characters long:
[a-z0-9][a-z0-9-]{0,61}[a-z0-9]
Test it here: http://regexr.com/3au3g
I find this explanation quite clear (it's pure copy from Technet):
There are two types of temporary tables: local and global. Local temporary tables are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server. Global temporary tables are visible to any user and any connection after they are created, and are deleted when all users that are referencing the table disconnect from the instance of SQL Server.
In a question tagged 'bash' that explicitly has "in Bash" in the title, I'm a little surprised by all of the replies saying you should avoid [[
...]]
because it only works in bash!
It's true that portability is the primary objection: if you want to write a shell script which works in Bourne-compatible shells even if they aren't bash, you should avoid [[
...]]
. (And if you want to test your shell scripts in a more strictly POSIX shell, I recommend dash
; though it is an incomplete POSIX implementation since it lacks the internationalization support required by the standard, it also lacks support for the many non-POSIX constructs found in bash, ksh, zsh, etc.)
The other objection I see is at least applicable within the assumption of bash: that [[
...]]
has its own special rules which you have to learn, while [
...]
acts like just another command. That is again true (and Mr. Santilli brought the receipts showing all the differences), but it's rather subjective whether the differences are good or bad. I personally find it freeing that the double-bracket construct lets me use (
...)
for grouping, &&
and ||
for Boolean logic, <
and >
for comparison, and unquoted parameter expansions. It's like its own little closed-off world where expressions work more like they do in traditional, non-command-shell programming languages.
A point I haven't seen raised is that this behavior of [[
...]]
is entirely consistent with that of the arithmetic expansion construct $((
...))
, which is specified by POSIX, and also allows unquoted parentheses and Boolean and inequality operators (which here perform numeric instead of lexical comparisons). Essentially, any time you see the doubled bracket characters you get the same quote-shielding effect.
(Bash and its modern relatives also use ((
...))
– without the leading $
– as either a C-style for
loop header or an environment for performing arithmetic operations; neither syntax is part of POSIX.)
So there are some good reasons to prefer [[
...]]
; there are also reasons to avoid it, which may or may not be applicable in your environment. As to your coworker, "our style guide says so" is a valid justification, as far as it goes, but I'd also seek out backstory from someone who understands why the style guide recommends what it does.
/(?![[:alnum:]]|@|-|_|\.)./
Nowadays, if you use a HTML5 form with type=email
then you're already by 80% safe since browser engines have their own validator. To complement it, add this regex to your preg_match_all()
and negate it:
if (!preg_match_all("/(?![[:alnum:]]|@|-|_|\.)./",$email)) { .. }
Find the regex used by HTML5 forms for validation
https://regex101.com/r/mPEKmy/1
haha, man, I just asked this question a few hours ago (kind of)...try this:
example:
someIntList.ForEach(i=>i+5);
ForEach()
is one of the built in .NET methods
This will modify the list, as opposed to returning a new one.
In case that you're interested in specific lines, use a result-array:
declare RESULT=($(./myscript)) # (..) = array
echo "First line: ${RESULT[0]}"
echo "Second line: ${RESULT[1]}"
echo "N-th line: ${RESULT[N]}"
The following command deletes all your stashes:
git stash clear
From the git documentation:
clear
Remove all the stashed states.
IMPORTANT WARNING: Those states will then be subject to pruning, and may be impossible to recover (...).
I would use Android's AccountPicker, introduced in ICS.
Intent googlePicker = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, true, null, null, null, null);
startActivityForResult(googlePicker, REQUEST_CODE);
And then wait for the result:
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
}
}
You should check to make sure the value is not None before trying to perform any calculations on it:
my_value = None
if my_value is not None:
print int(my_value) / 2
Note: my_value
was intentionally set to None to prove the code works and that the check is being performed.
cyclops-react StreamUtils has a reverse Stream method (javadoc).
StreamUtils.reverse(Stream.of("1", "2", "20", "3"))
.forEach(System.out::println);
It works by collecting to an ArrayList and then making use of the ListIterator class which can iterate in either direction, to iterate backwards over the list.
If you already have a List, it will be more efficient
StreamUtils.reversedStream(Arrays.asList("1", "2", "20", "3"))
.forEach(System.out::println);
Go to your mysql bin directory and install mysql service again:
c:
cd \mysql\bin
mysqld-nt.exe --install
or if mysqld-nt.exe is missing (depending on version):
mysqld.exe --install
Then go to services, start the service and set it to automatic start.
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
Create a .bat
file and write two commands:
cd C:\ Path to your tomcat directory \ bin
startup.bat
Now on double-click, Tomcat server will start.
Maybe useful for anyone else running into this issue: When setting the port on the properties:
props.put("mail.smtp.port", smtpPort);
..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.
Use "include" for reusable PHP templates. Use "require" for required libraries.
"*_once" is nice, because it checks whether the file is already loaded or not, but it only makes sense for me in "require_once".
One of the simplest ways to do this is like this
var totalWords = "my name is rahul.";_x000D_
var firstWord = totalWords.replace(/ .*/, '');_x000D_
alert(firstWord);_x000D_
console.log(firstWord);
_x000D_
Hi you can used this code in pure css
as like this
css
.arrow {
cursor: pointer;
color: white;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.arrow:before{
content: "×";
}
HTML
<a href="#" class="arrow">
</a>
? Live demo http://jsfiddle.net/rohitazad/VzZhU/
public static void main(String s[])
{
BufferedImage image = null;
try
{
image = ImageIO.read(new File("your image path"));
} catch (Exception e)
{
e.printStackTrace();
}
ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
jLabel1.setIcon(imageIcon);
}
private Image fitimage(Image img , int w , int h)
{
BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedimage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0,w,h,null);
g2.dispose();
return resizedimage;
}
I don't know about speed but this is my workaday quick fix:
reduce(lambda a, b: a.replace(*b)
, [('o','W'), ('t','X')] #iterable of pairs: (oldval, newval)
, 'tomato' #The string from which to replace values
)
... but I like the #1 regex answer above. Note - if one new value is a substring of another one then the operation is not commutative.
If you are using SharePoint and angular then do it like below:
<a ng-href="{{item.LinkTo.Url}}" target="_blank" ng-bind="item.Title;" ></a>
where LinkTo and Title is SharePoint Column.
In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.
If you are keen on doing this, though, check out this question:
Getting parts of a URL (Regex)
Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like
(?i)\.(jpg|png|gif)$
You can use backslash to quote "funny" characters in your jQuery selectors:
$('#input\\[23\\]')
For attribute values, you can use quotes:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
edit fixed bogosity; thanks @Dancrumb
**This is a simple way of getting the DAYS between two dates**
var d1 = moment($("#StartDate").data("DateTimePicker").date());
var d2 = moment($("#EndDate").data("DateTimePicker").date());
var diffInDays = d2.diff(d1, 'days');
if (diffInDays > 0)
{
$("#Total").val(diffInDays);
}
else
{
$("#Total").val(0);
}
You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:
SELECT
airline, flt_no, fairport, tairport, depart, arrive, fare
FROM
flights
INNER JOIN
airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
airports to_port ON (to_port.code = flights.tairport)
WHERE
from_port.code = '?' OR to_port.code = '?' OR airports.city='?'
Note that the to_port
and from_port
are aliases for the first and second copies of the airports
table.
Maybe you only need a shallow copy, in that case use Object.MemberWiseClone()
.
There are good recommendations in the documentation for MemberWiseClone()
for strategies to deep copy: -
http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx
If you can store the json string in a variable jsn_string
import json
jsn_list = json.loads(json.dumps(jsn_string))
for lis in jsn_list:
for key,val in lis.items():
print(key, val)
Output :
title Baby (Feat. Ludacris) - Justin Bieber
description Baby (Feat. Ludacris) by Justin Bieber on Grooveshark
link http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq
pubDate Wed, 28 Apr 2010 02:37:53 -0400
pubTime 1272436673
TinyLink http://tinysong.com/d3wI
SongID 24447862
SongName Baby (Feat. Ludacris)
ArtistID 1118876
ArtistName Justin Bieber
AlbumID 4104002
AlbumName My World (Part II);
http://tinysong.com/gQsw
LongLink 11578982
GroovesharkLink 11578982
Link http://tinysong.com/d3wI
title Feel Good Inc - Gorillaz
description Feel Good Inc by Gorillaz on Grooveshark
link http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI
pubDate Wed, 28 Apr 2010 02:25:30 -0400
pubTime 1272435930
I know that this is late answer, maybe helpful for researchers
if (!WindowName.IsVisible)
{
WindowName.Show();
WindowName.Activate();
}
wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz
cd Python-2.7.11
Now read the README
file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.
./configure
make
sudo make install
For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
For other versions and the most up to date download links:
http://www.python.org/getit/
Its really helped me to dynamically generate ids of showDetailItem
for the below code.
<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" >
<af:showDetailItem id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>
if you execute this line <af:outputText value="#{ttfVs}"/>
prints the below:
{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}
In case you want to apply the shadow to the inside of the element (inset
) but only want it to appear on one single side you can define a negative value to the "spread" parameter (5th parameter in the second example).
To completely remove it, make it the same size as the shadows blur (4th parameter in the second example) but as a negative value.
Also remember to add the offset to the y-position (3rd parameter in the second example) so that the following:
box-shadow: inset 0px 4px 3px rgba(50, 50, 50, 0.75);
becomes:
box-shadow: inset 0px 7px 3px -3px rgba(50, 50, 50, 0.75);
Check this updated fiddle: http://jsfiddle.net/FrEnY/1282/ and more on the box-shadow parameters here: http://www.w3schools.com/cssref/css3_pr_box-shadow.asp
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
The only real difference here is the size. All of the int types here are signed integer values which have varying sizes
Int16
: 2 bytesInt32
and int
: 4 bytesInt64
: 8 bytesThere is one small difference between Int64
and the rest. On a 32 bit platform assignments to an Int64
storage location are not guaranteed to be atomic. It is guaranteed for all of the other types.
You could also give them all the same name so they are an array, but give them different values:
<div id="checkboxes">
<input type="checkbox" name="c_n[]" value="c_n_0" checked="checked" />Option 1
<input type="checkbox" name="c_n[]" value="c_n_1" />Option 2
<input type="checkbox" name="c_n[]" value="c_n_2" />Option 3
<input type="checkbox" name="c_n[]" value="c_n_3" checked="checked" />Option 4
</div>
You can then get only the value of only the ticked ones using map:
$('#checkboxes input:checked[name="c_n[]"]')
.map(function () { return $(this).val(); }).get()
The error can be caused by access restrictions. Solution:
GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;
This following has worked best for me:
HTML:
<input type="submit"/>
CSS:
input[type=submit] {
background: url(http://yourURLhere) no-repeat;
border: 0;
display: block;
font-size:0;
height: 38px;
width: 171px;
}
If you don't set value
on your <input type="submit"/>
it will place the default text "Submit" inside your button. SO, just set the font-size: 0;
on your submit and then make sure you set a height
and width
for your input type so that your image will display. DON'T forget media queries for your submit if you need them, for example:
CSS:
@media (min-width:600px) {
input[type=submit] {
width:200px;
height: 44px;
}
}
This means when the screen is at exactly 600px wide or greater the button will change it's dimensions
Despite the imprecise nature of the question, here's my interpretive answer.
var html = [
'<div> A line</div>',
'<div> Add more lines</div>',
'<div> To the array as you need.</div>'
].join('');
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = html;
document.getElementById('posts').appendChild(div);
I was getting this error:
The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files
Doing the following fixed it for me:
Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK
You could try:
$(this).closest(".column").prev().find(".inputQty").val();
This GitHub app: https://github.com/apps/priv-page allows users to have private pages for their private repositories.
You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)
From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.
XHTML is evil. Write HTML
You will have to set the MIME type to text/html anyway, so why fooling yourself into believing that you are really writing XML? Whoever is going to download your page is going to believe that it is HTML, so make it HTML.
And with that, feel free and happy to not close your <li>, it isn't necessary. Don't close the html tag, the file is over anyway. It is valid HTML and it can be parsed perfectly.
It will create more readable, less boilerplate code and you don't lose a thing. HTML parsers work good!
And when you are done, move on to HTML5. It is better.
I think the most efficient way to test for "value is null
or undefined
" is
if ( some_variable == null ){
// some_variable is either null or undefined
}
So these two lines are equivalent:
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}
Note 1
As mentioned in the question, the short variant requires that some_variable
has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:
check for optional arguments:
function(foo){
if( foo == null ) {...}
check for properties on an existing object
if(my_obj.foo == null) {...}
On the other hand typeof
can deal with undeclared global variables (simply returns undefined
). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.
Note 2
This - even shorter - variant is not equivalent:
if ( !some_variable ) {
// some_variable is either null, undefined, 0, NaN, false, or an empty string
}
so
if ( some_variable ) {
// we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}
Note 3
In general it is recommended to use ===
instead of ==
.
The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull
option for this reason.
From the jQuery style guide:
Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.
// Check for both undefined and null values, for some important reason. undefOrNull == null;
Localization with default language:
extension String {
func localized() -> String {
let defaultLanguage = "en"
let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
How do you test that a Python function throws an exception?
How does one write a test that fails only if a function doesn't throw an expected exception?
Use the self.assertRaises
method as a context manager:
def test_1_cannot_add_int_and_str(self):
with self.assertRaises(TypeError):
1 + '1'
The best practice approach is fairly easy to demonstrate in a Python shell.
The unittest
library
In Python 2.7 or 3:
import unittest
In Python 2.6, you can install a backport of 2.7's unittest
library, called unittest2, and just alias that as unittest
:
import unittest2 as unittest
Now, paste into your Python shell the following test of Python's type-safety:
class MyTestCase(unittest.TestCase):
def test_1_cannot_add_int_and_str(self):
with self.assertRaises(TypeError):
1 + '1'
def test_2_cannot_add_int_and_str(self):
import operator
self.assertRaises(TypeError, operator.add, 1, '1')
Test one uses assertRaises
as a context manager, which ensures that the error is properly caught and cleaned up, while recorded.
We could also write it without the context manager, see test two. The first argument would be the error type you expect to raise, the second argument, the function you are testing, and the remaining args and keyword args will be passed to that function.
I think it's far more simple, readable, and maintainable to just to use the context manager.
To run the tests:
unittest.main(exit=False)
In Python 2.6, you'll probably need the following:
unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))
And your terminal should output the following:
..
----------------------------------------------------------------------
Ran 2 tests in 0.007s
OK
<unittest2.runner.TextTestResult run=2 errors=0 failures=0>
And we see that as we expect, attempting to add a 1
and a '1'
result in a TypeError
.
For more verbose output, try this:
unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))
Calling preventDefault
on touchmove
while you're actively scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.
Try to call preventDefault()
from touchstart
and everything should be ok.
I was having trouble getting redirection to HTTPS to work on a Windows server which runs version 6 of MS Internet Information Services (IIS). I’m more used to working with Apache on a Linux host so I turned to the Internet for help and this was the highest ranking Stack Overflow question when I searched for “php redirect http to https”. However, the selected answer didn’t work for me.
After some trial and error, I discovered that with IIS, $_SERVER['HTTPS']
is
set to off
for non-TLS connections. I thought the following code should
help any other IIS users who come to this question via search engine.
<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
$redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $redirect_url");
exit();
}
?>
Edit: From another Stack Overflow answer,
a simpler solution is to check if($_SERVER["HTTPS"] != "on")
.
If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:
NSLOOKUP fabrikam.com
Test-NetConnection <IP returned from NSLOOKUP> -port 389
Why is it needed?
When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.
Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires N/2
block accesses (on average), where N
is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at N
block accesses.
Whereas with a sorted field, a Binary Search may be used, which has log2 N
block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.
What is indexing?
Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.
The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.
How does it work?
Firstly, let’s outline a sample database table schema;
Field name Data type Size on disk id (Primary key) Unsigned INT 4 bytes firstName Char(50) 50 bytes lastName Char(50) 50 bytes emailAddress Char(100) 100 bytes
Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field).
Example 1 - sorted vs unsorted fields
Given our sample database of r = 5,000,000
records of a fixed size giving a record length of R = 204
bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024
bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5
records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000
blocks.
A linear search on the id field would require an average of N/2 = 500,000
block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20
block accesses. Instantly we can see this is a drastic improvement.
Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000
block accesses. It is this situation that indexing aims to correct.
Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below;
Field name Data type Size on disk firstName Char(50) 50 bytes (record pointer) Special 4 bytes
Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.
Example 2 - indexing
Given our sample database of r = 5,000,000
records with an index record length of R = 54
bytes and using the default block size B = 1,024
bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18
records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778
blocks.
Now a search using the firstName field can utilize the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19
block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20
block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table.
When should it be used?
Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.
Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.
Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
echo get_content('http://example.com');
Dmytro did a good job, but here is a more concise version.
class Program
{
static void Main(string[] args)
{
LinkedList linkedList = new LinkedList(1);
linkedList.Add(2);
linkedList.Add(3);
linkedList.Add(4);
linkedList.AddFirst(0);
linkedList.Print();
}
}
public class Node
{
public Node(Node next, Object value)
{
this.next = next;
this.value = value;
}
public Node next;
public Object value;
}
public class LinkedList
{
public Node head;
public LinkedList(Object initial)
{
head = new Node(null, initial);
}
public void AddFirst(Object value)
{
head = new Node(head, value);
}
public void Add(Object value)
{
Node current = head;
while (current.next != null)
{
current = current.next;
}
current.next = new Node(null, value);
}
public void Print()
{
Node current = head;
while (current != null)
{
Console.WriteLine(current.value);
current = current.next;
}
}
}
Don't call finish()
in onCreate()
method then it works fine.
Uncomment the line extension=php_mysql.dll
in your "php.ini" file and restart Apache.
Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.
See more about installing MySQL extension in manual.
P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).
In addition to the existing answers, there is also viewport units vh
to use. Simple snippet below. Of course it can be used together with calc()
as well, e.g. min-height: calc(100vh - 200px);
when page header and footer have 200px
height together.
body {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.child {_x000D_
min-height: 100vh;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
There are other ways to parse it rather than the first answer. To parse it:
(1) If you want to grab information about date and time, you can parse it to a ZonedDatetime
(since Java 8) or Date
(old) object:
// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);
or
// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);
Date myDate = df.parse("2011-08-12T20:17:46.384Z");
(2) If you don't care the date and time and just want to treat the information as a moment in nanoseconds, then you can use Instant
:
// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");
Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.
path.join
returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.
For instance:
path.join('app/libs/oauth', '/../ssl')
resolves to app/libs/ssl
path.resolve
, on the other hand, will resolve to an absolute path.
For instance, when you run:
path.resolve('bar', '/foo');
The path returned will be /foo
since that is the first absolute path that can be constructed.
However, if you run:
path.resolve('/bar/bae', '/foo', 'test');
The path returned will be /foo/test
again because that is the first absolute path that can be formed from right to left.
If you don't provide a path that specifies the root directory then the paths given to the resolve
function are appended to the current working directory. So if your working directory was /home/mark/project/
:
path.resolve('test', 'directory', '../back');
resolves to
/home/mark/project/test/back
Using __dirname
is the absolute path to the directory containing the source file. When you use path.resolve
or path.join
they will return the same result if you give the same path following __dirname
. In such cases it's really just a matter of preference.
For the people looking for regular polygons:
function regPolyPath(r,p,ctx){ //Radius, #points, context
//Azurethi was here!
ctx.moveTo(r,0);
for(i=0; i<p+1; i++){
ctx.rotate(2*Math.PI/p);
ctx.lineTo(r,0);
}
ctx.rotate(-2*Math.PI/p);
}
Use:
//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(60,60); //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation); //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx); //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();
public Form1()
{
InitializeComponent();
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
}
Declare myIP and myHost in public Variable and use in any function of the form.
Start mongod server first
mongod
Open another terminal window
Start mongo shell
mongo
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5);
There's my method to multiple upload file:
Nodejs :
router.post('/upload', function(req , res) {
var multiparty = require('multiparty');
var form = new multiparty.Form();
var fs = require('fs');
form.parse(req, function(err, fields, files) {
var imgArray = files.imatges;
for (var i = 0; i < imgArray.length; i++) {
var newPath = './public/uploads/'+fields.imgName+'/';
var singleImg = imgArray[i];
newPath+= singleImg.originalFilename;
readAndWriteFile(singleImg, newPath);
}
res.send("File uploaded to: " + newPath);
});
function readAndWriteFile(singleImg, newPath) {
fs.readFile(singleImg.path , function(err,data) {
fs.writeFile(newPath,data, function(err) {
if (err) console.log('ERRRRRR!! :'+err);
console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
})
})
}
})
Make sure your form has enctype="multipart/form-data"
I hope this gives you a hand ;)
It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.
Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):
SELECT f.value
FROM period as p JOIN facts AS f ON p.id = f.periodid
WHERE p.companyid = 100
AND f.otherid = 17
UNION
SELECT NULL AS value
FROM period as p
WHERE p.companyid = 100
AND NOT EXISTS (
SELECT *
FROM facts AS f
WHERE p.id = f.periodid
AND f.otherid = 17
);
So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).
However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.
Thank you guys for all your help! Finally I was able to make it work perfectly thanks to a friend and also you! Here is the final code so you can also see how we solve it.
Thanks again!
Option Explicit
Sub k()
Dim x As Integer, i As Integer, a As Integer
Dim name As String
'name = InputBox("Please insert the name of the sheet")
i = 1
name = "Reserva"
Sheets(name).Cells(4, 57) = Sheets(name).Cells(4, 56)
On Error GoTo fim
x = Sheets(name).Cells(4, 56).Value
Application.Calculation = xlCalculationManual
Do While Not IsEmpty(Sheets(name).Cells(i + 4, 56))
a = 0
If Sheets(name).Cells(4 + i, 56) <> x Then
If Sheets(name).Cells(4 + i, 56) <> 0 Then
If Sheets(name).Cells(4 + i, 56) = 3 Then
a = x
Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - x
x = Cells(4 + i, 56) - x
End If
Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - a
x = Sheets(name).Cells(4 + i, 56) - a
Else
Cells(4 + i, 57) = ""
End If
Else
Cells(4 + i, 57) = ""
End If
i = i + 1
Loop
Application.Calculation = xlCalculationAutomatic
Exit Sub
fim:
MsgBox Err.Description
Application.Calculation = xlCalculationAutomatic
End Sub
An Ad-hoc query is one created to provide a specific recordset from any or multiple merged tables available on the DB server. These queries usually serve a single-use purpose, and may not be necessary to incorporate into any stored procedure to run again in the future.
Ad-hoc scenario: You receive a request for a specific subset of data with a unique set of variables. If there is no pre-written query that can provide the necessary results, you must write an Ad-hoc query to generate the recordset results.
Beyond a single use Ad-hoc query are stored procedures; i.e. queries which are stored within the DB interface tool. These stored procedures can then be executed in sequence within a module or macro to accomplish a predefined task either on demand, on a schedule, or triggered by another event.
Stored Procedure scenario: Every month you need to generate a report from the same set of tables and with the same variables (these variables may be specific predefined values, computed values such as “end of current month”, or a user’s input values). You would created the procedure as an ad-hoc query the first time. After testing the results to ensure accuracy, you may chose to deploy this query. You would then store the query or series of queries in a module or macro to run again as needed.
It isn't getting called because you have a return statement above it. In the following code:
function test(){
return 1;
doStuff();
}
doStuff() will never be called. What I would suggest is writing a wrapper function
function wrapper(){
if (validateView()){
showDiv();
return true;
}
}
and then call the wrapper function from your onclick
handler.
It is indeed depending on the test runner as @jonzim mentioned.
For NUnit 3 I had to use NUnit.Framework.TestContext.Progress.WriteLine()
to get running output in the Output window of Visual Studio 2017.
NUnit describes how to: here
To my understanding this revolves around the added parallelization of test execution the test runners have received.
You can't use primitive types as generic arguments in Java. Use instead:
Map<String, Integer> myMap = new HashMap<String, Integer>();
With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:
myMap.put("foo", 3);
instead of:
myMap.put("foo", new Integer(3));
Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:
int i = myMap.get("foo");
instead of:
int i = myMap.get("foo").intValue();
The implicit call to intValue()
means if the key isn't found it will generate a NullPointerException
, for example:
int i = myMap.get("bar"); // NullPointerException
The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:
Integer i = (Integer)myMap.get("foo");
To give you an example, this code is perfectly legal:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");
I found it easier to edit the project file directly e.g. YourApp.csproj.
You can do this by modifying ApplicationIcon
property element:
<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>
Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.
I've just gone through this process, and there's a lot of very good help and information in this Q/A, but I found I had to pull together various elements (plus some from other Q/As) to get a working solution in order to successfully migrate.
However, even after combining the existing answers, I found that the Python script did not fully work for me as it did not work where there were multiple boolean occurrences in an INSERT. See here why that was the case.
So, I thought I'd post up my merged answer here. Credit goes to those that have contributed elsewhere, of course. But I wanted to give something back, and save others time that follow.
I'll post the script below. But firstly, here's the instructions for a conversion...
I ran the script on OS X 10.7.5 Lion. Python worked out of the box.
To generate the MySQL input file from your existing SQLite3 database, run the script on your own files as follows,
Snips$ sqlite3 original_database.sqlite3 .dump | python ~/scripts/dump_for_mysql.py > dumped_data.sql
I then copied the resulting dumped_sql.sql file over to a Linux box running Ubuntu 10.04.4 LTS where my MySQL database was to reside.
Another issue I had when importing the MySQL file was that some unicode UTF-8 characters (specifically single quotes) were not being imported correctly, so I had to add a switch to the command to specify UTF-8.
The resulting command to input the data into a spanking new empty MySQL database is as follows:
Snips$ mysql -p -u root -h 127.0.0.1 test_import --default-character-set=utf8 < dumped_data.sql
Let it cook, and that should be it! Don't forget to scrutinise your data, before and after.
So, as the OP requested, it's quick and easy, when you know how! :-)
As an aside, one thing I wasn't sure about before I looked into this migration, was whether created_at and updated_at field values would be preserved - the good news for me is that they are, so I could migrate my existing production data.
Good luck!
UPDATE
Since making this switch, I've noticed a problem that I hadn't noticed before. In my Rails application, my text fields are defined as 'string', and this carries through to the database schema. The process outlined here results in these being defined as VARCHAR(255) in the MySQL database. This places a 255 character limit on these field sizes - and anything beyond this was silently truncated during the import. To support text length greater than 255, the MySQL schema would need to use 'TEXT' rather than VARCHAR(255), I believe. The process defined here does not include this conversion.
Here's the merged and revised Python script that worked for my data:
#!/usr/bin/env python
import re
import fileinput
def this_line_is_useless(line):
useless_es = [
'BEGIN TRANSACTION',
'COMMIT',
'sqlite_sequence',
'CREATE UNIQUE INDEX',
'PRAGMA foreign_keys=OFF'
]
for useless in useless_es:
if re.search(useless, line):
return True
def has_primary_key(line):
return bool(re.search(r'PRIMARY KEY', line))
searching_for_end = False
for line in fileinput.input():
if this_line_is_useless(line): continue
# this line was necessary because ''); was getting
# converted (inappropriately) to \');
if re.match(r".*, ''\);", line):
line = re.sub(r"''\);", r'``);', line)
if re.match(r'^CREATE TABLE.*', line):
searching_for_end = True
m = re.search('CREATE TABLE "?([A-Za-z_]*)"?(.*)', line)
if m:
name, sub = m.groups()
line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
line = line % dict(name=name, sub=sub)
line = line.replace('AUTOINCREMENT','AUTO_INCREMENT')
line = line.replace('UNIQUE','')
line = line.replace('"','')
else:
m = re.search('INSERT INTO "([A-Za-z_]*)"(.*)', line)
if m:
line = 'INSERT INTO %s%s\n' % m.groups()
line = line.replace('"', r'\"')
line = line.replace('"', "'")
line = re.sub(r"(?<!')'t'(?=.)", r"1", line)
line = re.sub(r"(?<!')'f'(?=.)", r"0", line)
# Add auto_increment if it's not there since sqlite auto_increments ALL
# primary keys
if searching_for_end:
if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
# replace " and ' with ` because mysql doesn't like quotes in CREATE commands
# And now we convert it back (see above)
if re.match(r".*, ``\);", line):
line = re.sub(r'``\);', r"'');", line)
if searching_for_end and re.match(r'.*\);', line):
searching_for_end = False
if re.match(r"CREATE INDEX", line):
line = re.sub('"', '`', line)
print line,
Go to phpMyAdmin Directory of your Localhost Software Like Xampp, Mamp or others. Then change the host from localhost to 127.0.0.1 and change the port to 3307 . After that go to your data directory and delete all error log files except ibdata1 which is important file to hold your created database table link. Finaly restart mysql.I think your problem will be solved.
It is whatever member of the enumeration represents the value 0
. Specifically, from the documentation:
The default value of an
enum E
is the value produced by the expression(E)0
.
As an example, take the following enum:
enum E
{
Foo, Bar, Baz, Quux
}
Without overriding the default values, printing default(E)
returns Foo
since it's the first-occurring element.
However, it is not always the case that 0
of an enum is represented by the first member. For example, if you do this:
enum F
{
// Give each element a custom value
Foo = 1, Bar = 2, Baz = 3, Quux = 0
}
Printing default(F)
will give you Quux
, not Foo
.
If none of the elements in an enum G
correspond to 0
:
enum G
{
Foo = 1, Bar = 2, Baz = 3, Quux = 4
}
default(G)
returns literally 0
, although its type remains as G
(as quoted by the docs above, a cast to the given enum type).
Another very basic free profiler: http://expressprofiler.codeplex.com
If you are also interested in commercial implementations, you should take a look at Nirvana from my-channels.
Nirvana is used heavily within the Financial Services industry for large scale low-latency trading and price distribution platforms.
There is support for a wide range of client programming languages across the enterprise, web and mobile domains.
The clustering capabilities are extremely advanced and worth a look if transparent HA or load balancing is important for you.
Nirvana is free to download for development purposes.
You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).
Consider how your application should respond to various cases.
The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.
Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.
PostgreSQL does not define round(double precision, integer)
. For reasons @Mike Sherrill 'Cat Recall' explains in the comments, the version of round that takes a precision is only available for numeric
.
regress=> SELECT round( float8 '3.1415927', 2 );
ERROR: function round(double precision, integer) does not exist
regress=> \df *round*
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+--------+------------------+---------------------+--------
pg_catalog | dround | double precision | double precision | normal
pg_catalog | round | double precision | double precision | normal
pg_catalog | round | numeric | numeric | normal
pg_catalog | round | numeric | numeric, integer | normal
(4 rows)
regress=> SELECT round( CAST(float8 '3.1415927' as numeric), 2);
round
-------
3.14
(1 row)
(In the above, note that float8
is just a shorthand alias for double precision
. You can see that PostgreSQL is expanding it in the output).
You must cast the value to be rounded to numeric
to use the two-argument form of round
. Just append ::numeric
for the shorthand cast, like round(val::numeric,2)
.
If you're formatting for display to the user, don't use round
. Use to_char
(see: data type formatting functions in the manual), which lets you specify a format and gives you a text
result that isn't affected by whatever weirdness your client language might do with numeric
values. For example:
regress=> SELECT to_char(float8 '3.1415927', 'FM999999999.00');
to_char
---------------
3.14
(1 row)
to_char
will round numbers for you as part of formatting. The FM
prefix tells to_char
that you don't want any padding with leading spaces.
Actually, the ticked answer is exactly right, but the answer can be in ES6
shape:
HTMLInputElementObject.oninput = () => {
console.log('run'); // Do something
}
Or can be written like below:
HTMLInputElementObject.addEventListener('input', (evt) => {
console.log('run'); // Do something
});
You can use an Explain Plan to get an objective answer.
For your problem, an Exists filter would probably perform the fastest.
(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.
aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/" --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '
r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)
Another working solution for IE specific styling is
<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">
And then your selector
html[data-useragent*='MSIE 10.0'] body .my-class{
margin-left: -0.4em;
}
A LEFT JOIN
is absolutely not faster than an INNER JOIN
. In fact, it's slower; by definition, an outer join (LEFT JOIN
or RIGHT JOIN
) has to do all the work of an INNER JOIN
plus the extra work of null-extending the results. It would also be expected to return more rows, further increasing the total execution time simply due to the larger size of the result set.
(And even if a LEFT JOIN
were faster in specific situations due to some difficult-to-imagine confluence of factors, it is not functionally equivalent to an INNER JOIN
, so you cannot simply go replacing all instances of one with the other!)
Most likely your performance problems lie elsewhere, such as not having a candidate key or foreign key indexed properly. 9 tables is quite a lot to be joining so the slowdown could literally be almost anywhere. If you post your schema, we might be able to provide more details.
Edit:
Reflecting further on this, I could think of one circumstance under which a LEFT JOIN
might be faster than an INNER JOIN
, and that is when:
Consider this example:
CREATE TABLE #Test1
(
ID int NOT NULL PRIMARY KEY,
Name varchar(50) NOT NULL
)
INSERT #Test1 (ID, Name) VALUES (1, 'One')
INSERT #Test1 (ID, Name) VALUES (2, 'Two')
INSERT #Test1 (ID, Name) VALUES (3, 'Three')
INSERT #Test1 (ID, Name) VALUES (4, 'Four')
INSERT #Test1 (ID, Name) VALUES (5, 'Five')
CREATE TABLE #Test2
(
ID int NOT NULL PRIMARY KEY,
Name varchar(50) NOT NULL
)
INSERT #Test2 (ID, Name) VALUES (1, 'One')
INSERT #Test2 (ID, Name) VALUES (2, 'Two')
INSERT #Test2 (ID, Name) VALUES (3, 'Three')
INSERT #Test2 (ID, Name) VALUES (4, 'Four')
INSERT #Test2 (ID, Name) VALUES (5, 'Five')
SELECT *
FROM #Test1 t1
INNER JOIN #Test2 t2
ON t2.Name = t1.Name
SELECT *
FROM #Test1 t1
LEFT JOIN #Test2 t2
ON t2.Name = t1.Name
DROP TABLE #Test1
DROP TABLE #Test2
If you run this and view the execution plan, you'll see that the INNER JOIN
query does indeed cost more than the LEFT JOIN
, because it satisfies the two criteria above. It's because SQL Server wants to do a hash match for the INNER JOIN
, but does nested loops for the LEFT JOIN
; the former is normally much faster, but since the number of rows is so tiny and there's no index to use, the hashing operation turns out to be the most expensive part of the query.
You can see the same effect by writing a program in your favourite programming language to perform a large number of lookups on a list with 5 elements, vs. a hash table with 5 elements. Because of the size, the hash table version is actually slower. But increase it to 50 elements, or 5000 elements, and the list version slows to a crawl, because it's O(N) vs. O(1) for the hashtable.
But change this query to be on the ID
column instead of Name
and you'll see a very different story. In that case, it does nested loops for both queries, but the INNER JOIN
version is able to replace one of the clustered index scans with a seek - meaning that this will literally be an order of magnitude faster with a large number of rows.
So the conclusion is more or less what I mentioned several paragraphs above; this is almost certainly an indexing or index coverage problem, possibly combined with one or more very small tables. Those are the only circumstances under which SQL Server might sometimes choose a worse execution plan for an INNER JOIN
than a LEFT JOIN
.
It happens because your maven plugin try to connect to an HTTPS remote repository (https://repo.maven.apache.org/maven2) or (https://repo1.maven.apache.org).
Some time ago, you could to change these URL's to use HTTP instead use HTTPS, but since January 15th 2020, these URL's doesn't work any more, only the HTTPS URL's.
As an easy way to fix this problem, you can use the insecure Maven URL in the settings.xml file. So, you need to change ALL of yours references above mencioned to: http://insecure.repo1.maven.org/maven2/
TIP: Your JAVA_HOME variable always needs to point to your JDK path, not to your JRE path, for example: "C:\Program Files\Java\jdk1.7.0_80".
having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...
public class global {
public static Activity globalContext = null;
and set it in the main activity create
@Override
public void onCreate(Bundle savedInstanceState) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
global.sdcardPath,
""));
super.onCreate(savedInstanceState);
//Start
//Debug.startMethodTracing("appname.Trace1");
global.globalContext = this;
also all preference keys should be language independent, I'm shocked nobody has mentioned that.
getText(R.string.yourPrefKeyName).toString()
now call it very simply like this in one line of code
global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);