128 characters. This is the max length of the sysname
datatype (nvarchar(128)
).
You can use below code for h2 and MySQl
@Query(value = "SELECT req.CREATED_AT createdAt, req.CREATED_BY createdBy,req.APP_ID appId,req.NOTE_ID noteId,req.MODEL model FROM SUMBITED_REQUESTS req inner join NOTE note where req.NOTE_ID=note.ID and note.CREATED_BY= :userId "
,
countQuery = "SELECT count(*) FROM SUMBITED_REQUESTS req inner join NOTE note WHERE req.NOTE_ID=note.ID and note.CREATED_BY=:userId",
nativeQuery = true)
Page<UserRequestsDataMapper> getAllRequestForCreator(@Param("userId") String userId,Pageable pageable);
while(choice!=99)
{
cin>>choice;
if (choice==99)
exit(0);
cin>>gNum;
}
Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...
Press Shift-zz. Saves changes and Quits. Escape didn't work for me.
I am using Git Bash in windows. And couldn't get past this either. My commit messages are simple so I dont want to add another editor atm.
Easily extracting multiple properties from array of objects:
let arrayOfObjects = [
{id:1, name:'one', desc:'something'},
{id:2, name:'two', desc:'something else'}
];
//below will extract just the id and name
let result = arrayOfObjects.map(({id, name}) => ({id, name}));
result
will be [{id:1, name:'one'},{id:2, name:'two'}]
Add or remove properties as needed in the map function
You've misunderstood how character classes are used:
$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
does the same as your regex (assuming you didn't mean to remove '
characters from your strings).
Edit: The +
allows several of those "special characters" to match at once, so it should also be faster.
open the CMD and use this command :
**
pip uninstall django
**
it will easy uninstalled .
When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id
) and search for it specific.
$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+
$('#autocomplete_input').val() +'"]').data('value'));
})
Try this way of formation, it is rather fancy ...
Have a look at this jsfiddle
The idea is to choose a the radio as a button instead of the normal circle image.
The typical way to send binary in json is to base64 encode it.
Java provides different ways to Base64 encode and decode a byte[]
. One of these is DatatypeConverter
.
Very simply
byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5};
String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes);
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);
You'll have to make this conversion depending on the json parser/generator library you use.
I have nice solution that i would like to share. First you need to detect if user is on mobile like this:
var touchDevice = /ipad|iphone|android|windows phone|blackberry/i.test(navigator.userAgent.toLowerCase());
Then just add:
if (!touchDevice) {
$(".navbar-ul").addClass("hoverable");
}
And in CSS:
.navbar-ul.hoverable li a:hover {
color: #fff;
}
I have one strange problem. In fact when i plug my phone to my mac the time of the device change but not use the actual hour. For example on my computer I have this hour : 05:17 pm but on my phone when is unlocked time is frozen to 09:41 am so when i try to build my app on phone from xCode i have the next error message :
Please verify that your device’s clock is properly set
The strange thing is that when my phone is still pluged to the mac the time on lockScreen is good (05:17 pm)... And if i check on Date & Time on general settings I have this strange thing too (time of statusbar is wrong but time below is good) :
After few minutes i understood that it was because of QuickTime Player which was running on my mac with view of my iPhone (i was going to save a video demo of my app).
To resolve the problem I had to quit all applications and restart computer.
In plus at the end if problem persists do these steps :
Hope this can help.
Thank you,
Look at http://github.com/mono/mono/tree/master/mcs/class/Mono.Options/
Dowlnoad sqlite manager and install it from Here.Open the sqlite file using that browser.
It doesn't work because name
is a reserved word in JavaScript. Change the function name to something else.
See http://www.quackit.com/javascript/javascript_reserved_words.cfm
<form id="form" onsubmit="return false;">
<input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
<input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>
function othername() {
var input = document.getElementById("userInput").value;
alert(input);
}
Interesting blog post here:
http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx
It mentions subscribing to Dispatcher.ShutdownStarted to dispose of your resources.
does the later approach save computation time and memory?
There is no big difference between those two examples that you provided. The first example cuts the video sequentially, in 2 steps, while the second example does it at the same time (using threads). No particular speed-up will be noticeable. You can read more about creating multiple outputs with FFmpeg
Further more, what you can use (in recent FFmpeg) is the stream segmenter muxer which can:
output streams to a number of separate files of nearly fixed duration. Output filename pattern can be set in a fashion similar to image2.
TCP has "open" and a "close" procedures in the protocol. Once "opened", a connection is held until "closed". But there are lots of things that can stop the data flow abnormally. That being said, the techniques to determine if it is possible to use a link are highly dependent on the layers of software between the protocol and the application program. The ones mentioned above focus on a programmer attempting to use a socket in a non-invasive way (read or write 0 bytes) are perhaps the most common. Some layers in libraries will supply the "polling" for a programmer. For example Win32 asych (delayed) calls can Start a read that will return with no errors and 0 bytes to signal a socket that cannot be read any more (presumably a TCP FIN procedure). Other environments might use "events" as defined in their wrapping layers. There is no single answer to this question. The mechanism to detect when a socket cannot be used and should be closed depends on the wrappers supplied in the libraries. It is also worthy to note that sockets themselves can be reused by layers below an application library so it is wise to figure out how your environment deals with the Berkley Sockets interface.
You should be aware of a few key factors...
First, there are two types of compression: Lossless and Lossy.
There are also different colour depths (palettes): Indexed color and Direct color.
BMP - Lossless / Indexed and Direct
This is an old format. It is Lossless (no image data is lost on save) but there's also little to no compression at all, meaning saving as BMP results in VERY large file sizes. It can have palettes of both Indexed and Direct, but that's a small consolation. The file sizes are so unnecessarily large that nobody ever really uses this format.
Good for: Nothing really. There isn't anything BMP excels at, or isn't done better by other formats.
GIF - Lossless / Indexed only
GIF uses lossless compression, meaning that you can save the image over and over and never lose any data. The file sizes are much smaller than BMP, because good compression is actually used, but it can only store an Indexed palette. This means that for most use cases, there can only be a maximum of 256 different colours in the file. That sounds like quite a small amount, and it is.
GIF images can also be animated and have transparency.
Good for: Logos, line drawings, and other simple images that need to be small. Only really used for websites.
JPEG - Lossy / Direct
JPEGs images were designed to make detailed photographic images as small as possible by removing information that the human eye won't notice. As a result it's a Lossy format, and saving the same file over and over will result in more data being lost over time. It has a palette of thousands of colours and so is great for photographs, but the lossy compression means it's bad for logos and line drawings: Not only will they look fuzzy, but such images will also have a larger file-size compared to GIFs!
Good for: Photographs. Also, gradients.
PNG-8 - Lossless / Indexed
PNG is a newer format, and PNG-8 (the indexed version of PNG) is really a good replacement for GIFs. Sadly, however, it has a few drawbacks: Firstly it cannot support animation like GIF can (well it can, but only Firefox seems to support it, unlike GIF animation which is supported by every browser). Secondly it has some support issues with older browsers like IE6. Thirdly, important software like Photoshop have very poor implementation of the format. (Damn you, Adobe!) PNG-8 can only store 256 colours, like GIFs.
Good for: The main thing that PNG-8 does better than GIFs is having support for Alpha Transparency.
PNG-24 - Lossless / Direct
PNG-24 is a great format that combines Lossless encoding with Direct color (thousands of colours, just like JPEG). It's very much like BMP in that regard, except that PNG actually compresses images, so it results in much smaller files. Unfortunately PNG-24 files will still be bigger than JPEGs (for photos), and GIFs/PNG-8s (for logos and graphics), so you still need to consider if you really want to use one.
Even though PNG-24s allow thousands of colours while having compression, they are not intended to replace JPEG images. A photograph saved as a PNG-24 will likely be at least 5 times larger than a equivalent JPEG image, with very little improvement in visible quality. (Of course, this may be a desirable outcome if you're not concerned about filesize, and want to get the best quality image you can.)
Just like PNG-8, PNG-24 supports alpha-transparency, too.
SVG - Lossless / Vector
A filetype that is currently growing in popularity is SVG, which is different than all the above in that it's a vector file format (the above are all raster). This means that it's actually comprised of lines and curves instead of pixels. When you zoom in on a vector image, you still see a curve or a line. When you zoom in on a raster image, you will see pixels.
For example:
This means SVG is perfect for logos and icons you wish to retain sharpness on Retina screens or at different sizes. It also means a small SVG logo can be used at a much larger (bigger) size without degradation in image quality -- something that would require a separate larger (in terms of filesize) file with raster formats.
SVG file sizes are often tiny, even if they're visually very large, which is great. It's worth bearing in mind, however, that it does depend on the complexity of the shapes used. SVGs require more computing power than raster images because mathematical calculations are involved in drawing the curves and lines. If your logo is especially complicated it could slow down a user's computer, and even have a very large file size. It's important that you simplify your vector shapes as much as possible.
Additionally, SVG files are written in XML, and so can be opened and edited in a text editor(!). This means its values can be manipulated on the fly. For example, you could use JavaScript to change the colour of an SVG icon on a website, much like you would some text (ie. no need for a second image), or even animate them.
In all, they are best for simple flat shapes like logos or graphs.
I hope that helps!
Update 17/07/27: As this is the most-voted answer, I should update this to include current information locally (with links to the references).
From the spec [1]:
The aside element represents a section of a page that consists of content that is tangentially related to the content of the parenting sectioning content, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography.
Great! Exactly what we're looking for. In addition, it is best to check on <section>
as well.
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content. Each section should be identified, typically by including a heading (h1-h6 element) as a child of the section element.
...
A general rule is that the section element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.
Excellent. Just what we're looking for. As opposed to <article>
[2] which is for "self-contained" content, <section>
allows for related content that isn't stand-alone, or generic enough for a <div>
element.
As such, the spec seems to suggest that using Option 1, <aside>
with <section>
children is best practice.
References
If you just want to round the number for output purposes, then the "%.2f"
format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:
#include <math.h>
float val = 37.777779;
float rounded_down = floorf(val * 100) / 100; /* Result: 37.77 */
float nearest = roundf(val * 100) / 100; /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100; /* Result: 37.78 */
Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.
As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.
For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.
All procedure at once. Based on @Till Schäfer answer.
In KB...
jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10]); printf("%.2f KB\n",sum)}'
In MB...
jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10])/1024; printf("%.2f MB\n",sum)}'
"Awk sum" reference:
a[1] - S0C
a[2] - S1C
a[3] - S0U
a[4] - S1U
a[5] - EC
a[6] - EU
a[7] - OC
a[8] - OU
a[9] - PC
a[10] - PU
a[11] - YGC
a[12] - YGCT
a[13] - FGC
a[14] - FGCT
a[15] - GCT
Used for "Awk sum":
a[3] -- (S0U) Survivor space 0 utilization (KB).
a[4] -- (S1U) Survivor space 1 utilization (KB).
a[6] -- (EU) Eden space utilization (KB).
a[8] -- (OU) Old space utilization (KB).
a[10] - (PU) Permanent space utilization (KB).
[Ref.: https://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html ]
Thanks!
NOTE: Works to OpenJDK!
FURTHER QUESTION: Wrong information?
If you check memory usage with the ps
command, you will see that the java process consumes much more...
ps -eo size,pid,user,command --sort -size | egrep -i "*/bin/java *" | egrep -v grep | awk '{ hr=$1/1024 ; printf("%.2f MB ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | cut -d "" -f2 | cut -d "-" -f1
UPDATE (2021-02-16):
According to the reference below (and @Till Schäfer comment) "ps can show total reserved memory from OS" (adapted) and "jstat can show used space of heap and stack" (adapted). So, we see a difference between what is pointed out by the ps
command and the jstat
command.
According to our understanding, the most "realistic" information would be the ps
output since we will have an effective response of how much of the system's memory is compromised. The command jstat
serves for a more detailed analysis regarding the java performance in the consumption of reserved memory from OS.
[Ref.: http://www.openkb.info/2014/06/how-to-check-java-memory-usage.html ]
There is a way to cleanup workspace in Jenkins. You can clean up the workspace before build or after build.
First, install Workspace Cleanup Plugin.
To clean up the workspace before build: Under Build Environment, check the box that says Delete workspace before build starts.
To clean up the workspace after the build: Under the heading Post-build Actions select Delete workspace when build is done from the Add Post-build Actions drop down menu.
I know this is old but I didn't see anyone mention extending the String prototype
.
String.prototype.replaceAll = function(search, replace){
if(!search || !replace){return this;} //if search entry or replace entry empty return the string
return this.replace(new RegExp('[' + search + ']', 'g'), replace); //global RegEx search for all instances ("g") of your search entry and replace them all.
};
Not all browsers cache files with '?' in it. What I did to make sure it was cached as much as possible, I included the version in the filename.
So instead of stuff.js?123
, I did stuff_123.js
I used mod_redirect
(I think) in apache to to have stuff_*.js
to go stuff.js
Acepted solution implemented in PyQt5
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
self.pb.clicked.connect(self.button_click)
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print (shost)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
same as Igor but should work without line 2:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
One cause of this is having Fiddler2 configured to decrypt HTTPS traffic. Close Fiddler2 and it should work fine.
It seems that Facebook Page Plugin doesn't change at all in past 5-7 years :) It wasn't responsive from the begining and still not now, even new param Adapt to plugin container width
doesn't work or I don't understand how it works.
I'm searching for the most posible simple way to do PLUGIN SIZE 100% WIDTH
, and it seems it is not posible. Nonsense at it's best. How designers solve this problem?
I found the best decision for this time 2017 Oct:
.fb-page, .fb-page iframe[style], .fb-page span {
width: 100% !important;
}
.fb-comments, .fb-comments iframe[style], .fb-comments span {
width: 100% !important;
}
This lets do not broke screen size width for responsive screens, but still looks ugly, because cuted in some time and doesn't stretch... Facebook doesn't care about plugins design at all. That's the truth.
HTML4/XHTML1 requires
<script type="...">...</script>
HTML5 faces the fact that there is only one scripting language on the web, and allows
<script>...</script>
The latter works in any browser that supports scripting (NN2+).
Refining Günter Zöchbauer answer:
This appears to be different now. I was trying to do this to conditionally apply an href attribute to an anchor tag. You must use undefined for the 'do not apply' case. As an example, I'll demonstrate with a link conditionally having an href attribute applied.
--EDIT--
It looks like angular has changed some things, so null
will now work as expected. I've update the example to use null
rather than undefined
.
An anchor tag without an href attribute becomes plain text, indicating a placeholder for a link, per the hyperlink spec.
For my navigation, I have a list of links, but one of those links represents the current page. I didn't want the current page link to be a link, but still want it to appear in the list (it has some custom styles, but this example is simplified).
<a [attr.href]="currentUrl !== link.url ? link.url : null">
This is cleaner than using two *ngIf's on a span and anchor tag, I think. It's also perfect for adding a disabled attribute to a button.
package lecture3;
import java.util.Scanner;
public class divisibleBy2and5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter an integer number:");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
if (x % 2==0){
System.out.println("The integer number you entered is divisible by 2");
}
else{
System.out.println("The integer number you entered is not divisible by 2");
if(x % 5==0){
System.out.println("The integer number you entered is divisible by 5");
}
else{
System.out.println("The interger number you entered is not divisible by 5");
}
}
}
}
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
$personCount=1;
while ($personCount < 10) {
$result=0;
$result.= $personCount . "person ";
$personCount++;
echo $result;
}
If your vector look like this std::vector<MyClass*> vecType_pt
you have to explicitly release memory ,Or if your vector look like : std::vector<MyClass> vecType_obj
, constructor will be called by vector.Please execute example given below , and understand the difference :
class MyClass
{
public:
MyClass()
{
cout<<"MyClass"<<endl;
}
~MyClass()
{
cout<<"~MyClass"<<endl;
}
};
int main()
{
typedef std::vector<MyClass*> vecType_ptr;
typedef std::vector<MyClass> vecType_obj;
vecType_ptr myVec_ptr;
vecType_obj myVec_obj;
MyClass obj;
for(int i=0;i<5;i++)
{
MyClass *ptr=new MyClass();
myVec_ptr.push_back(ptr);
myVec_obj.push_back(obj);
}
cout<<"\n\n---------------------If pointer stored---------------------"<<endl;
myVec_ptr.erase (myVec_ptr.begin(),myVec_ptr.end());
cout<<"\n\n---------------------If object stored---------------------"<<endl;
myVec_obj.erase (myVec_obj.begin(),myVec_obj.end());
return 0;
}
I used these code Hope it could help
dataGridView2.Rows[n].Cells[3].Value = item[2].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d");
overflow: hidden
should give you the correct behavior. My guess is that RTL
is messed up because you have float: left
on the encapsulated div
s.
Beside that bug, you got the right behavior.
[2017-07-25] since this continues to be the accepted answer, despite being a very hacky solution, I'm incorporating Gabi's code into it, leaving my own to serve as a bad example.
// my hacky approach:
function get_content() {
var html = document.getElementById("txt").innerHTML;
document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
}
// Gabi's elegant approach, but eliminating one unnecessary line of code:
function gabi_content() {
var element = document.getElementById('txt');
element.innerHTML = element.innerText || element.textContent;
}
// and exploiting the fact that IDs pollute the window namespace:
function txt_content() {
txt.innerHTML = txt.innerText || txt.textContent;
}
_x000D_
.A {
background: blue;
}
.B {
font-style: italic;
}
.C {
font-weight: bold;
}
_x000D_
<input type="button" onclick="get_content()" value="Get Content (bad)" />
<input type="button" onclick="gabi_content()" value="Get Content (good)" />
<input type="button" onclick="txt_content()" value="Get Content (shortest)" />
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>
_x000D_
If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:
Add an 'Application Server' role:
Then, add a 'Web Server' role:
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
Here too I can reproduce this problem with scrapy
and psycopg2
(both require C++ compiling), even though I have Microsoft Visual C++ Compiler for Python 2.7 installed.
It has to be noted that I use virtualenv
. From your post I'm not sure whether you do the same.
Anyway I tried to skip the activation of the virtual environment. Then both scrapy
and psycopg2
installed fine.
My hypothesis: there is a conflict between this 2014 C++ compiler for Python and virtualenv. I do not know why nor how to solve it (and I'd be glad if someone can suggest a workaround).
Modules go in site-packages
and executables go in your system's executable path. For your environment, this path is /usr/local/bin/
.
To avoid having to deal with this, simply use easy_install
, distribute
or pip
. These tools know which files need to go where.
I got this after adding Episerver Find to our site and installing the corresponding NuGet package for Episerver Find.
The fix was easy: update all Episerver related add-ons as well (even if they seem unrelated: CMS, CMS.TinyMCE, CMS.UI, etc.)
After updating all possible Episerver add-ons and recompiling, the error went away.
Instead of String.IndexOf, use String.Equals to ensure you don't have partial matches. Also don't use FindAll as that goes through every element, use FindIndex (it stops on the first one it hits).
if(testList.FindIndex(x => x.Equals(keyword,
StringComparison.OrdinalIgnoreCase) ) != -1)
Console.WriteLine("Found in list");
Alternately use some LINQ methods (which also stops on the first one it hits)
if( testList.Any( s => s.Equals(keyword, StringComparison.OrdinalIgnoreCase) ) )
Console.WriteLine("found in list");
Beginning with Java 7, you can use the following idiom:
String someString = "...";
InputStream is = new ByteArrayInputStream( someString.getBytes(StandardCharsets.UTF_8) );
You can use assertException extension to assert more than one exception during one test execution.
Insert method into your TestCase and use:
public function testSomething()
{
$test = function() {
// some code that has to throw an exception
};
$this->assertException( $test, 'InvalidArgumentException', 100, 'expected message' );
}
I also made a trait for lovers of nice code..
xcode is now available for free from the app store. Just "buy it" (for free) and it will download. To get the command line tools go into preferences/downloads and "install command line compiler tools".
Instead of gcc you are using clang, but it works the same.
also, look for a comment // that breaks the closing curly brace
if (1==1) { //echo "it is true"; }
the closing curly brace will not properly close the conditional section and php won't properly process the remainder of code.
You can try this in your Action:
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
And this in your Ajax success:
success: function (resultDateString) {
var date = new Date(resultDateString);
}
Or this in your View: (Javascript plus C#)
var date = new Date('@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');
If you want downloads number for each customer, use:
select ssn
, sum(time)
from downloads
group by ssn
If you want just one record -- for a customer with highest number of downloads -- use:
select *
from (
select ssn
, sum(time)
from downloads
group by ssn
order by sum(time) desc
)
where rownum = 1
However if you want to see all customers with the same number of downloads, which share the highest position, use:
select *
from (
select ssn
, sum(time)
, dense_rank() over (order by sum(time) desc) r
from downloads
group by ssn
)
where r = 1
@
suppresses the error message thrown by the function. fopen
throws an error when the file doesn't exit. @
symbol makes the execution to move to the next line even the file doesn't exists. My suggestion would be not using this in your local environment when you develop a PHP code.
I am running tests for my Angular app and encountered error Can't bind to 'routerLink' since it isn't a known property of 'a'
as well.
I thought it might be useful to show my Angular dependencies:
"@angular/animations": "^8.2.14",
"@angular/common": "^8.2.14",
"@angular/compiler": "^8.2.14",
"@angular/core": "^8.2.14",
"@angular/forms": "^8.2.14",
"@angular/router": "^8.2.14",
The issue was in my spec
file. I compared to another similar component spec
file and found that I was missing RouterTestingModule
in imports
, e.g.
TestBed.configureTestingModule({
declarations: [
...
],
imports: [ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule],
providers: [...]
});
});
Assuming you will compare the substring against the end of another string and use the result as a boolean you may extend the String class to accomplish this:
String.prototype.endsWith = function (substring) {
if(substring.length > this.length) return false;
return this.substr(this.length - substring.length) === substring;
};
Allowing you to do the following:
var aSentenceToPonder = "This sentence ends with toad";
var frogString = "frog";
var toadString = "toad";
aSentenceToPonder.endsWith(frogString) // false
aSentenceToPonder.endsWith(toadString) // true
Check this basic code to setup html server. its work for me.
var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(8000); });
A callable piece of code (routine) can be a Sub (called for a side effect/what it does) or a Function (called for its return value) or a mixture of both. As the docs for MsgBox
Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])
indicate, this routine is of the third kind.
The syntactical rules of VBScript are simple:
Use parameter list () when calling a (routine as a) Function
If you want to display a message to the user and need to know the user's reponse:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.
Don't use parameter list () when calling a (routine as a) Sub
If you want to display a message to the user and are not interested in the response:
MsgBox "Hello World!", 65, "MsgBox Example"
This beautiful simplicity is messed up by:
The design flaw of using () for parameter lists and to force call-by-value semantics
>> Sub S(n) : n = n + 1 : End Sub
>> n = 1
>> S n
>> WScript.Echo n
>> S (n)
>> WScript.Echo n
>>
2
2
S (n) does not mean "call S with n", but "call S with a copy of n's value". Programmers seeing that
>> s = "value"
>> MsgBox(s)
'works' are in for a suprise when they try:
>> MsgBox(s, 65, "MsgBox Example")
>>
Error Number: 1044
Error Description: Cannot use parentheses when calling a Sub
The compiler's leniency with regard to empty () in a Sub call. The 'pure' Sub Randomize (called for the side effect of setting the random seed) can be called by
Randomize()
although the () can neither mean "give me your return value) nor "pass something by value". A bit more strictness here would force prgrammers to be aware of the difference in
Randomize n
and
Randomize (n)
The Call statement that allows parameter list () in Sub calls:
s = "value" Call MsgBox(s, 65, "MsgBox Example")
which further encourage programmers to use () without thinking.
(Based on What do you mean "cannot use parentheses?")
Here's my example in which I work
If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:
public class Foo {
private static final int widgets;
static {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
widgets = first + second;
}
}
If first
and second
weren't in a block, they'd look like fields. If they were in a block without static
in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.
Now in this particular case, you could use a static method instead:
public class Foo {
private static final int widgets = getWidgets();
static int getWidgets() {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
return first + second;
}
}
... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
How to end the request?
Try other solution, just:
return StatusCode(418);
You could use StatusCode(???)
to return any HTTP status code.
Also, you can use dedicated results:
Success:
return Ok()
? Http status code 200return Created()
? Http status code 201return NoContent();
? Http status code 204Client Error:
return BadRequest();
? Http status code 400return Unauthorized();
? Http status code 401return NotFound();
? Http status code 404
More details:
You can download a library from http://json.org (Json-lib or org.json) and use it to parse/generate the JSON
Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..
In current release
Assuming you have handled the verification of the request to reset the forgotten password, use following code as a sample code steps.
ApplicationDbContext =new ApplicationDbContext()
String userId = "<YourLogicAssignsRequestedUserId>";
String newPassword = "<PasswordAsTypedByUser>";
ApplicationUser cUser = UserManager.FindById(userId);
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>();
store.SetPasswordHashAsync(cUser, hashedNewPassword);
In AspNet Nightly Build
The framework is updated to work with Token for handling requests like ForgetPassword. Once in release, simple code guidance is expected.
Update:
This update is just to provide more clear steps.
ApplicationDbContext context = new ApplicationDbContext();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
String userId = User.Identity.GetUserId();//"<YourLogicAssignsRequestedUserId>";
String newPassword = "test@123"; //"<PasswordAsTypedByUser>";
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
ApplicationUser cUser = await store.FindByIdAsync(userId);
await store.SetPasswordHashAsync(cUser, hashedNewPassword);
await store.UpdateAsync(cUser);
sed -n "1 x;1 !H
$ {x;s/\n*$//p;}
" YourFile
Should remove any last occurence of \n in file. Not working on huge file (due to sed buffer limitation)
I did it like this
CSS
html {
-webkit-transition: background-color 1s;
transition: background-color 1s;
}
html, body {
/* For the loading indicator to be vertically centered ensure */
/* the html and body elements take up the full viewport */
min-height: 100%;
}
html.loading {
/* Replace #333 with the background-color of your choice */
/* Replace loading.gif with the loading image of your choice */
background: #333 url('/Images/loading.gif') no-repeat 50% 50%;
/* Ensures that the transition only runs in one direction */
-webkit-transition: background-color 0;
transition: background-color 0;
}
body {
-webkit-transition: opacity 1s ease-in;
transition: opacity 1s ease-in;
}
html.loading body {
/* Make the contents of the body opaque during loading */
opacity: 0;
/* Ensures that the transition only runs in one direction */
-webkit-transition: opacity 0;
transition: opacity 0;
}
JS
$(document).ready(function () {
$(document).ajaxStart(function () {
$("html").addClass("loading");
});
$(document).ajaxStop(function () {
$("html").removeClass("loading");
});
$(document).ajaxError(function () {
$("html").removeClass("loading");
});
});
try this:
textarea {
border-style: none;
border-color: Transparent;
overflow: auto;
outline: none;
}
jsbin: http://jsbin.com/orozon/2/
In Windows
..\AndroidStudio2.0Beta6\android-studio\gradle\gradle-2.10
Edit: Use printf("val = 0x%" PRIx64 "\n", val);
instead.
Try printf("val = 0x%llx\n", val);
. See the printf manpage:
ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.
Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t
is not always a unsigned long long
: PRIx64
see also this stackoverflow answer
The first constructor in the header should not end with a semicolon. #include <string>
is missing in the header. string
is not qualified with std::
in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream
is broken. I suggest learning C++ before trying to use it.
Let's fix this up:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
#include <iostream>
#include <string>
class Polygone {
public:
// declarations have to end with a semicolon, definitions do not
Polygone(){} // why would we needs this?
Polygone(const std::string& fichier);
};
# endif
and
//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>
Polygone::Polygone(const std::string& nom)
{
std::ifstream fichier (nom, ios::in);
if (fichier.is_open())
{
// keep the scope as tiny as possible
std::string line;
// getline returns the stream and streams convert to booleans
while ( std::getline(fichier, line) )
{
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
You can use regular expressions with the caret symbol (^
) which anchors the match to the beginning of the string:
$str = preg_replace('/^bla_/', '', $str);
To spool from a BEGIN
END
block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop
. Sample code is given below.
BEGIN
FOR x IN
(
SELECT COLUMN1,COLUMN2 FROM TABLE1
UNION ALL
SELECT COLUMN1,COLUMN2 FROM TABLEB
)
LOOP
dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;
END;
/
I think it's the join sequence effect. In the upper left join case, SQL do Left join first and then do where filter. In the downer case, find Orders.ID=12345 first, and then do join.
We had the same problem while working on an Android application for a customer and I managed to "hack" around this restriction.
I took a look at the Android Source code for the WebView class and spotted a updateZoomButtonsEnabled()
-method which was working with an ZoomButtonsController
-object to enable and disable the zoom controls depending on the current scale of the browser.
I searched for a method to return the ZoomButtonsController
-instance and found the getZoomButtonsController()
-method, that returned this very instance.
Although the method is declared public
, it is not documented in the WebView
-documentation and Eclipse couldn't find it either. So, I tried some reflection on that and created my own WebView
-subclass to override the onTouchEvent()
-method, which triggered the controls.
public class NoZoomControllWebView extends WebView {
private ZoomButtonsController zoom_controll = null;
public NoZoomControllWebView(Context context) {
super(context);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs) {
super(context, attrs);
disableControls();
}
/**
* Disable the controls
*/
private void disableControls(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// Use the API 11+ calls to disable the controls
this.getSettings().setBuiltInZoomControls(true);
this.getSettings().setDisplayZoomControls(false);
} else {
// Use the reflection magic to make it work on earlier APIs
getControlls();
}
}
/**
* This is where the magic happens :D
*/
private void getControlls() {
try {
Class webview = Class.forName("android.webkit.WebView");
Method method = webview.getMethod("getZoomButtonsController");
zoom_controll = (ZoomButtonsController) method.invoke(this, null);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
super.onTouchEvent(ev);
if (zoom_controll != null){
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.setVisible(false);
}
return true;
}
}
You might want to remove the unnecessary constructors and react on probably on the exceptions.
Although this looks hacky and unreliable, it works back to API Level 4 (Android 1.6).
As @jayellos pointed out in the comments, the private getZoomButtonsController()
-method is no longer existing on Android 4.0.4 and later.
However, it doesn't need to. Using conditional execution, we can check if we're on a device with API Level 11+ and use the exposed functionality (see @Yuttadhammo answer) to hide the controls.
I updated the example code above to do exactly that.
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data
argument as yadda
, but miss one of the places it is used in the function's body... Now data
refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError
if you didn't have a global name data
.
Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo
at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo
.
Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.
None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.
One place that SET NOCOUNT ON
can really help is where you are doing queries in a loop or a cursor. This can add up to a lot of network traffic.
CREATE PROCEDURE NoCountOn
AS
set nocount on
DECLARE @num INT = 10000
while @num > 0
begin
update MyTable SET SomeColumn=SomeColumn
set @num = @num - 1
end
GO
CREATE PROCEDURE NoCountOff
AS
set nocount off
DECLARE @num INT = 10000
while @num > 0
begin
update MyTable SET SomeColumn=SomeColumn
set @num = @num - 1
end
GO
Turning on client statistics in SSMS, a run of EXEC NoCountOn
and EXEC NoCountOff
shows that there was an extra 390KB traffic on the NoCountOff one:
Probably not ideal to be doing queries in a loop or cursor, but we don't live in in ideal world either :)
Port: In simple language, "Port" is a number used by a particular software to identify its data coming from internet.
Each software, like Skype, Chrome, Youtube has its own port number and that's how they know which internet data is for itself.
Socket: "IP address and Port " together is called "Socket". It is used by another computer to send data to one particular computer's particular software.
IP address is used to identify the computer and Port is to identify the software such as IE, Chrome, Skype etc.
In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.
Here is some LESS for you, in case you customize the navbar:
.navbar .divider-vertical {
height: floor(@navbar-height - @navbar-margin-bottom);
margin: floor(@navbar-margin-bottom / 2) 9px;
border-left: 1px solid #f2f2f2;
border-right: 1px solid #ffffff;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
CGSize constraintSize = {245.0, 20000}
CGSize neededSize = [ yourText sizeWithFont:[UIfont systemFontOfSize:14.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap]
if ( neededSize.height <= 18)
return 45
else return neededSize.height + 45
//18 is the size of your text with the requested font (systemFontOfSize 14). if you change fonts you have a different number to use
// 45 is what is required to have a nice cell as the neededSize.height is the "text"'s height only
//not the cell.
}
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
void showfile() throws java.io.IOException <-----
Your showfile()
method throws IOException
, so whenever you use it you have to either catch that exception or again thorw it. Something like:
try {
showfile();
}
catch(IOException e) {
e.printStackTrace();
}
You should learn about exceptions in Java.
Our example project has two build targets: HelloWorld.app and Helper.app. We make a component package for each and combine them into a product archive.
A component package contains payload to be installed by the OS X Installer. Although a component package can be installed on its own, it is typically incorporated into a product archive.
After a successful "Build and Archive" open $BUILT_PRODUCTS_DIR in the Terminal.
$ cd ~/Library/Developer/Xcode/DerivedData/.../InstallationBuildProductsLocation
$ pkgbuild --analyze --root ./HelloWorld.app HelloWorldAppComponents.plist
$ pkgbuild --analyze --root ./Helper.app HelperAppComponents.plist
This give us the component-plist, you find the value description in the "Component Property List" section. pkgbuild -root generates the component packages, if you don't need to change any of the default properties you can omit the --component-plist parameter in the following command.
productbuild --synthesize results in a Distribution Definition.
$ pkgbuild --root ./HelloWorld.app \
--component-plist HelloWorldAppComponents.plist \
HelloWorld.pkg
$ pkgbuild --root ./Helper.app \
--component-plist HelperAppComponents.plist \
Helper.pkg
$ productbuild --synthesize \
--package HelloWorld.pkg --package Helper.pkg \
Distribution.xml
In the Distribution.xml you can change things like title, background, welcome, readme, license, and so on. You turn your component packages and distribution definition with this command into a product archive:
$ productbuild --distribution ./Distribution.xml \
--package-path . \
./Installer.pkg
I recommend to take a look at iTunes Installers Distribution.xml to see what is possible. You can extract "Install iTunes.pkg" with:
$ pkgutil --expand "Install iTunes.pkg" "Install iTunes"
I usually have a folder named Package in my project which includes things like Distribution.xml, component-plists, resources and scripts.
Add a Run Script Build Phase named "Generate Package", which is set to Run script only when installing:
VERSION=$(defaults read "${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}/Contents/Info" CFBundleVersion)
PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
TMP1_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp1.pkg"
TMP2_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp2"
TMP3_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp3.pkg"
ARCHIVE_FILENAME="${BUILT_PRODUCTS_DIR}/${PACKAGE_NAME}.pkg"
pkgbuild --root "${INSTALL_ROOT}" \
--component-plist "./Package/HelloWorldAppComponents.plist" \
--scripts "./Package/Scripts" \
--identifier "com.test.pkg.HelloWorld" \
--version "$VERSION" \
--install-location "/" \
"${BUILT_PRODUCTS_DIR}/HelloWorld.pkg"
pkgbuild --root "${BUILT_PRODUCTS_DIR}/Helper.app" \
--component-plist "./Package/HelperAppComponents.plist" \
--identifier "com.test.pkg.Helper" \
--version "$VERSION" \
--install-location "/" \
"${BUILT_PRODUCTS_DIR}/Helper.pkg"
productbuild --distribution "./Package/Distribution.xml" \
--package-path "${BUILT_PRODUCTS_DIR}" \
--resources "./Package/Resources" \
"${TMP1_ARCHIVE}"
pkgutil --expand "${TMP1_ARCHIVE}" "${TMP2_ARCHIVE}"
# Patches and Workarounds
pkgutil --flatten "${TMP2_ARCHIVE}" "${TMP3_ARCHIVE}"
productsign --sign "Developer ID Installer: John Doe" \
"${TMP3_ARCHIVE}" "${ARCHIVE_FILENAME}"
If you don't have to change the package after it's generated with productbuild you could get rid of the pkgutil --expand
and pkgutil --flatten
steps. Also you could use the --sign paramenter on productbuild instead of running productsign.
Packages are signed with the Developer ID Installer certificate which you can download from Developer Certificate Utility.
They signing is done with the --sign "Developer ID Installer: John Doe"
parameter of pkgbuild, productbuild or productsign.
Note that if you are going to create a signed product archive using productbuild, there is no reason to sign the component packages.
To copy something into the Xcode Archive we can't use the Run Script Build Phase. For this we need to use a Scheme Action.
Edit Scheme and expand Archive. Then click post-actions and add a New Run Script Action:
In Xcode 6:
#!/bin/bash
PACKAGES="${ARCHIVE_PATH}/Packages"
PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
ARCHIVE_FILENAME="$PACKAGE_NAME.pkg"
PKG="${OBJROOT}/../BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"
if [ -f "${PKG}" ]; then
mkdir "${PACKAGES}"
cp -r "${PKG}" "${PACKAGES}"
fi
In Xcode 5, use this value for PKG
instead:
PKG="${OBJROOT}/ArchiveIntermediates/${TARGET_NAME}/BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"
In case your version control doesn't store Xcode Scheme information I suggest to add this as shell script to your project so you can simple restore the action by dragging the script from the workspace into the post-action.
There are two different kinds of scripting: JavaScript in Distribution Definition Files and Shell Scripts.
The best documentation about Shell Scripts I found in WhiteBox - PackageMaker How-to, but read this with caution because it refers to the old package format.
In order for the package to run as arm64, the Distribution file has to specify in its hostArchitectures
section that it supports arm64
in addition to x86_64
:
<options hostArchitectures="arm64,x86_64" />
Destination Select Pane
The user is presented with the destination select option with only a single choice - "Install for all users of this computer". The option appears visually selected, but the user needs to click on it in order to proceed with the installation, causing some confusion.
Apples Documentation recommends to use <domains enable_anywhere ... />
but this triggers the new more buggy Destination Select Pane which Apple doesn't use in any of their Packages.
Using the deprecate <options rootVolumeOnly="true" />
give you the old Destination Select Pane.
You want to install items into the current user’s home folder.
Short answer: DO NOT TRY IT!
Long answer: REALLY; DO NOT TRY IT! Read Installer Problems and Solutions. You know what I did even after reading this? I was stupid enough to try it. Telling myself I'm sure that they fixed the issues in 10.7 or 10.8.
First of all I saw from time to time the above mentioned Destination Select Pane Bug. That should have stopped me, but I ignored it. If you don't want to spend the week after you released your software answering support e-mails that they have to click once the nice blue selection DO NOT use this.
You are now thinking that your users are smart enough to figure the panel out, aren't you? Well here is another thing about home folder installation, THEY DON'T WORK!
I tested it for two weeks on around 10 different machines with different OS versions and what not, and it never failed. So I shipped it. Within an hour of the release I heart back from users who just couldn't install it. The logs hinted to permission issues you are not gonna be able to fix.
So let's repeat it one more time: We do not use the Installer for home folder installations!
RTFD for Welcome, Read-me, License and Conclusion is not accepted by productbuild
.
Installer supported since the beginning RTFD files to make pretty Welcome screens with images, but productbuild doesn't accept them.
Workarounds:
Use a dummy rtf file and replace it in the package by after productbuild
is done.
Note: You can also have Retina images inside the RTFD file. Use multi-image tiff files for this: tiffutil -cat Welcome.tif Welcome_2x.tif -out FinalWelcome.tif
. More details.
Starting an application when the installation is done with a BundlePostInstallScriptPath script:
#!/bin/bash
LOGGED_IN_USER_ID=`id -u "${USER}"`
if [ "${COMMAND_LINE_INSTALL}" = "" ]
then
/bin/launchctl asuser "${LOGGED_IN_USER_ID}" /usr/bin/open -g PATH_OR_BUNDLE_ID
fi
exit 0
It is important to run the app as logged in user, not as the installer user. This is done with launchctl asuser uid path. Also we only run it when it is not a command line installation, done with installer tool or Apple Remote Desktop.
Just access the element and append it to the value.
<input
type="button"
onclick="document.getElementById('myTextArea').value += '•'"
value="Add •">
See a live demo.
For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.
Also it needs to be a UTF8 character.
Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
TL;DR:
The ActionListener
s (there can be multiple) execute in the order they were registered BEFORE the action
Long Answer:
A business action
typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view
if that is not what you are doing an actionListener
is more appropriate i.e. for when the user interacts with the components, such as h:commandButton
or h:link
they can be handled by passing the name of the managed bean method in actionListener
attribute of a UI Component or to implement an ActionListener
interface and pass the implementation class name to actionListener
attribute of a UI Component.
The issue is in your registration app. It seems django-registration calls get_user_module()
in models.py
at a module level (when models are still being loaded by the application registration process). This will no longer work:
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
I'd change this models file to only call get_user_model()
inside methods (and not at module level) and in FKs use something like:
user = ForeignKey(settings.AUTH_USER_MODEL)
BTW, the call to django.setup()
shouldn't be required in your manage.py
file, it's called for you in execute_from_command_line
. (source)
I think the best ranking is
1.node-schedule
2.later
3.crontab
and the sample of node-schedule is below:
var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
//rule.minute = 40;
rule.second = 10;
var jj = schedule.scheduleJob(rule, function(){
console.log("execute jj");
});
Maybe you can find the answer from node modules.
I'm assuming what you want to do is run a command without an interface (possibly automatically?). On windows there are a number of options for what you are looking for:
Best: write your program as a windows service. These will start when no one logs into the server. They let you select the user account (which can be different than your own) and they will restart if they fail. These run all the time so you can automate tasks at specific times or on a regular schedule from within them. For more information on how to write a windows service you can read a tutorial online such as (http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx).
Better: Start the command and hide the window. Assuming the command is a DOS command you can use a VB or C# script for this. See here for more information. An example is:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("C:\yourbatch.bat"), 0, True
You are still going to have to start the command manually or write a task to start the command. This is one of the biggest down falls of this strategy.
Hope that helps some!
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
For Swift 3
func stringToDate(_ str: String)->Date{
let formatter = DateFormatter()
formatter.dateFormat="yyyy-MM-dd hh:mm:ss Z"
return formatter.date(from: str)!
}
func dateToString(_ str: Date)->String{
var dateFormatter = DateFormatter()
dateFormatter.timeStyle=DateFormatter.Style.short
return dateFormatter.string(from: str)
}
The most simple way I found was to create a stored procedure. Enter the 'JobName' and hit go.
/*-----------------------------------------------------------------------------------------------------------
Document Title: usp_getJobStatus
Purpose: Finds a Current Jobs Run Status
Input Example: EXECUTE usp_getJobStatus 'MyJobName'
-------------------------------------------------------------------------------------------------------------*/
IF OBJECT_ID ( 'usp_getJobStatus','P' ) IS NOT NULL
DROP PROCEDURE usp_getJobStatus;
GO
CREATE PROCEDURE usp_getJobStatus
@JobName NVARCHAR (1000)
AS
IF OBJECT_ID('TempDB..#JobResults','U') IS NOT NULL DROP TABLE #JobResults
CREATE TABLE #JobResults ( Job_ID UNIQUEIDENTIFIER NOT NULL,
Last_Run_Date INT NOT NULL,
Last_Run_Time INT NOT NULL,
Next_Run_date INT NOT NULL,
Next_Run_Time INT NOT NULL,
Next_Run_Schedule_ID INT NOT NULL,
Requested_to_Run INT NOT NULL,
Request_Source INT NOT NULL,
Request_Source_id SYSNAME
COLLATE Database_Default NULL,
Running INT NOT NULL,
Current_Step INT NOT NULL,
Current_Retry_Attempt INT NOT NULL,
Job_State INT NOT NULL )
INSERT #JobResults
EXECUTE master.dbo.xp_sqlagent_enum_jobs 1, '';
SELECT job.name AS [Job_Name],
( SELECT MAX(CAST( STUFF(STUFF(CAST(jh.run_date AS VARCHAR),7,0,'-'),5,0,'-') + ' ' +
STUFF(STUFF(REPLACE(STR(jh.run_time,6,0),' ','0'),5,0,':'),3,0,':') AS DATETIME))
FROM msdb.dbo.sysjobs AS j
INNER JOIN msdb.dbo.sysjobhistory AS jh
ON jh.job_id = j.job_id AND jh.step_id = 0
WHERE j.[name] LIKE '%' + @JobName + '%'
GROUP BY j.[name] ) AS [Last_Completed_DateTime],
( SELECT TOP 1 start_execution_date
FROM msdb.dbo.sysjobactivity
WHERE job_id = r.job_id
ORDER BY start_execution_date DESC ) AS [Job_Start_DateTime],
CASE
WHEN r.running = 0 THEN
CASE
WHEN jobInfo.lASt_run_outcome = 0 THEN 'Failed'
WHEN jobInfo.lASt_run_outcome = 1 THEN 'Success'
WHEN jobInfo.lASt_run_outcome = 3 THEN 'Canceled'
ELSE 'Unknown'
END
WHEN r.job_state = 0 THEN 'Success'
WHEN r.job_state = 4 THEN 'Success'
WHEN r.job_state = 5 THEN 'Success'
WHEN r.job_state = 1 THEN 'In Progress'
WHEN r.job_state = 2 THEN 'In Progress'
WHEN r.job_state = 3 THEN 'In Progress'
WHEN r.job_state = 7 THEN 'In Progress'
ELSE 'Unknown' END AS [Run_Status_Description]
FROM #JobResults AS r
LEFT OUTER JOIN msdb.dbo.sysjobservers AS jobInfo
ON r.job_id = jobInfo.job_id
INNER JOIN msdb.dbo.sysjobs AS job
ON r.job_id = job.job_id
WHERE job.[enabled] = 1
AND job.name LIKE '%' + @JobName + '%'
~/.bashrc
sudo su
vim ~/.bashrc
Common default install folders:
Example .bashrc
export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools
source ~/.bashrc
When
ionic build android
still fails it could be because of wrong sdk version. To install correct versions and images runandroid
from command line. Since it is now in your PATH you should be able to run it from anywhere.
What you really want to do is bind the event handler for the capture phase of the event. However, that isn't supported in IE as far as I know, so that might not be all that useful.
http://www.quirksmode.org/js/events_order.html
Related questions:
DELETE FROM table_name
WHERE id BETWEEN 79 AND 296;
Actually whatever the third parameter is, 0 or 1 or 2, it will not round your value.
CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))
For sending the output to another file (I'm leaving out error checking to focus on the important details):
if (fork() == 0)
{
// child
int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
dup2(fd, 2); // make stderr go to file - you may choose to not do this
// or perhaps send stderr to another file
close(fd); // fd no longer needed - the dup'ed handles are sufficient
exec(...);
}
For sending the output to a pipe so you can then read the output into a buffer:
int pipefd[2];
pipe(pipefd);
if (fork() == 0)
{
close(pipefd[0]); // close reading end in the child
dup2(pipefd[1], 1); // send stdout to the pipe
dup2(pipefd[1], 2); // send stderr to the pipe
close(pipefd[1]); // this descriptor is no longer needed
exec(...);
}
else
{
// parent
char buffer[1024];
close(pipefd[1]); // close the write end of the pipe in the parent
while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}
}
getting a char from a string may depend on the enconding (string default is UTF-16)
https://stackoverflow.com/a/32141891
string str = new String(new char[] { '\uD800', '\uDC00', 'z' });
string first = str.Substring(0, char.IsHighSurrogate(str[0]) ? 2 : 1);
pipenv want combine all, in addition to previous it installs "requirements" (into the active virtual environment or create its own if none is active)
So maybe you will be happy with pipenv only.
But I use: pyenv + pyenv-virtualenvwrapper, + pipenv (pipenv for installing requirements only).
In Debian:
apt install libffi-dev
install pyenv based on https://www.tecmint.com/pyenv-install-and-manage-multiple-python-versions-in-linux/, but..
.. but instead of pyenv-virtualenv install pyenv-virtualenvwrapper (which can be standalone library or pyenv plugin, here the 2nd option):
pyenv install 3.9.0
git clone https://github.com/pyenv/pyenv-virtualenvwrapper.git $(pyenv root)/plugins/pyenv-virtualenvwrapper
into ~/.bashrc add: export $VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"
source ~/.bashrc
pyenv virtualenvwrapper
Then create virtual environments for your projects (workingdir must exist):
pyenv local 3.9.0 # to prevent 'interpreter not found' in mkvirtualenv
python -m pip install --upgrade pip setuptools wheel
mkvirtualenv <venvname> -p python3.9 -a <workingdir>
and switch between projects:
workon <venvname>
python -m pip install --upgrade pip setuptools wheel pipenv
Inside a project I have the file requirements.txt, without fixing the versions inside (if some version limitation is not neccessary). You have 2 possible tools to install them into the current virtual environment: pip-tools or pipenv. Lets say you will use pipenv:
pipenv install -r requirements.txt
this will create Pipfile and Pipfile.lock files, fixed versions are in the 2nd one. If you want reinstall somewhere exactly same versions then (Pipfile.lock must be present):
pipenv install
Remember that Pipfile.lock is related to some Python version and need to be recreated if you use a different one.
As you see I write requirements.txt. This has some problems: You must remove a removed package from Pipfile too. So writing Pipfile directly is probably better.
So you can see I use pipenv very poorly. Maybe if you will use it well, it can replace everything?
EDIT 2021.01: I have changed my stack to: pyenv + pyenv-virtualenvwrapper + poetry
. Ie. I use no apt or pip installation of virtualenv or virtualenvwrapper, and instead I install pyenv
's plugin pyenv-virtualenvwrapper
. This is easier way.
Poetry
is great for me:
poetry add <package> # install single package
poetry remove <package>
poetry install # if you remove poetry.lock poetry will re-calculate versions
If you check the info on python.org, you can see this summary:
Version Time (seconds)
Basic loop 3.47
Eliminate dots 2.45
Local variable & no dots 1.79
Using map function 0.54
But you really should read the above article in details to understand the cause of the performance difference.
I also strongly suggest you should time your code by using timeit. At the end of the day, there can be a situation where, for example, you may need to break out of for
loop when a condition is met. It could potentially be faster than finding out the result by calling map
.
Try using git log -n 1
after doing a git checkout branchname
. This shows the commit hash, author, date and commit message for the latest commit.
Perform a git pull origin/branchname
first, to make sure your local repo matches upstream.
If perhaps you would only like to see a list of the commits your local branch is behind on the remote branch do this:
git fetch origin
git cherry localbranch remotebranch
This will list all the hashes of the commits that you have not yet merged into your local branch.
you can use default ng-submitted is set if the form was submitted.
https://docs.angularjs.org/api/ng/directive/form
example: http://jsbin.com/cowufugusu/1/
In the past, I have used a bridge using the Linux Netem (Network Emulation) functionality. It is highly configurable -- allowing the introduction of delays (the first example is for a WAN), packet loss, corruption, etc.
I'm noting that Netem worked very well for my applications, but I also ended up using WANem several times. The provided bootable ISO (and virtual appliance images) made it quite handy.
Use outline: transparent;
in order to make the outline appear like it isn't there but still provide accessibility to your forms. outline: none;
will negatively impact accessibility.
Source: http://outlinenone.com/
From the Notes of Fred Swartz (fredosaurus) :
There are two types of methods.
Instance methods are associated with an object and use the instance variables of that object. This is the default.
Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math
class.
From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");
A static method is called by prefixing it with a class name, eg, Math.max(i,j);
. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.
Here is a typical static method:
class MyUtils {
. . .
//================================================= mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
. . .
}
The only data this method uses or changes is from parameters (or local variables of course).
static
The above mean()
method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.
There are two cases.
Called from within the same class
Just write the static method name. Eg:
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg:
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of the object will be used.
Altho a static
method can't access instance variables, it can access static
variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI
or Color.RED
. They are qualified with the class name, so you know they are static
. Any method, static
or not, can access static
variables. Instance variables can be accessed only by instance methods.
What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.
You need the oracle client driver installed for those classes to work.
There might be 3rd party connection frameworks out there that can handle Oracle, perhaps someone else might know of some specific ones.
On Ubuntu until python-distribute is something newer than 0.7 I'd recommend:
$ wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | sudo python
See http://reinout.vanrees.org/weblog/2013/07/08/new-setuptools-buildout.html
Their are two methods you can use to pass an integer. One is as shown below.
A.class
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
B.class
Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);
The other method converts the integer to a string and uses the following code.
A.class
Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);
The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.
B.class
Bundle extras = getIntent().getExtras();
String stringVariableName = extras.getString("StringVariableName");
int intVariableName = Integer.parseInt(stringVariableName);
Is it possible that you are using GCC 5?
If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace or the tag [abi:cxx11] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly happens when linking to a third-party library that was compiled with an older version of GCC. If the third-party library cannot be rebuilt with the new ABI then you will need to recompile your code with the old ABI.
Source: GCC 5 Release Notes/Dual ABI
Defining the following macro before including any standard library headers should fix your problem: #define _GLIBCXX_USE_CXX11_ABI 0
This is the right way to do it with Twitter Bootstrap and the new navbar-fixed-bottom class: (you have no idea how long I spent looking for this)
CSS:
html {
position: relative;
min-height: 100%;
}
#content {
padding-bottom: 50px;
}
#footer .navbar{
position: absolute;
}
HTML:
<html>
<body>
<div id="content">...</div>
<div id="footer">
<div class="navbar navbar-fixed-bottom">
<div class="navbar-inner">
<div class="container">
<ul class="nav">
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
AspNetCoreModuleV2 cannot handle OPTIONS causing a preflight issue
I discovered that .net core module does not handle OPTIONS well which makes a big CORS problem:
Solution: remove the star *
In web.config, exclude OPTIONS verb from the module because this verb is already handled by the IIS OPTIONSVerbHandler:
<add name="aspNetCore" path="*" verb="* modules="AspNetCoreModuleV2" resourceType="Unspecified" />
with this one
<add name="aspNetCore" path="*" verb="GET,POST,PUT,DELETE" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
Array values = Enum.GetValues(typeof(Bar));
Random random = new Random();
Bar randomBar = (Bar)values.GetValue(random.Next(values.Length));
As you've already noticed, you can control most of these settings in .csproj.
If you'd rather keep these in AssemblyInfo.cs, you can turn off auto-generated assembly attributes.
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
If you want to see what's going on under the hood, checkout Microsoft.NET.GenerateAssemblyInfo.targets inside of Microsoft.NET.Sdk.
On your system there is a file named /proc/self/statm
. The proc filesystem is a pseudo-filesystem which provides an interface to kernel data structures. This file contains the information you need in columns with only integers that are space separated.
Column no.:
= total program size (VmSize in /proc/[pid]/status)
= resident set size (VmRSS in /proc/[pid]/status)
For more info see the LINK.
My favourite rule in regards to authentication systems: use passphrases, not passwords. Easy to remember, hard to crack. More info: Coding Horror: Passwords vs. Pass Phrases
In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS")
out to make it even faster):
var _getAllFilesFromFolder = function(dir) {
var filesystem = require("fs");
var results = [];
filesystem.readdirSync(dir).forEach(function(file) {
file = dir+'/'+file;
var stat = filesystem.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(_getAllFilesFromFolder(file))
} else results.push(file);
});
return results;
};
usage is clear:
_getAllFilesFromFolder(__dirname + "folder");
The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):
Greedy quantifiers
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}? X, exactly n times
X{n,}? X, at least n times
X{n,m}? X, at least n but not more than m times
Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+ X, exactly n times
X{n,}+ X, at least n times
X{n,m}+ X, at least n but not more than m times
I simplification for Science_Fiction's answer I think is to use the exclusive or function so you can just have:
if(checkbox1.checked ^ checkbox2.checked)
{
//do stuff
}
That is assuming you want to do the same thing for both situations.
I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).
This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.
Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null
out the reference to class B to allow it to be collected.
A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.
If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?
You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.
Would that take more space than just plugging '5' into the println method?
The JIT is smart enough to turn fields which don't change into constants.
Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory
Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.
The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.
TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
private String txt;
@Override
public void run() {
searchResultTextView.setText(txt);
}
public void setText(String txt){
this.txt = txt;
}
}
It can be used from anywhere like this:
textViewUpdater.setText("Hello");
textViewUpdaterHandler.post(textViewUpdater);
str1 = "test123.00";
str2 = "yes50.00";
intStr1 = str1.replace(/[A-Za-z$-]/g, "");
intStr2 = str2.replace(/[A-Za-z$-]/g, "");
total = parseInt(intStr1)+parseInt(intStr2);
alert(total);
working Jsfiddle
git diff --name-only SHA1 SHA2
where you only need to include enough of the SHA to identify the commits. You can also do, for example
git diff --name-only HEAD~10 HEAD~5
to see the differences between the tenth latest commit and the fifth latest (or so).
Nice and simple, from Pinal Dave's site:
http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/
DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT
SET @Lower = 3 ---- The lowest random number
SET @Upper = 7 ---- One more than the highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random
(I did make a slight change to the @Upper- to include the upper number, added 1.)
You have to do this:
class Bar : public Foo
{
// ...
}
The default inheritance type of a class
in C++ is private
, so any public
and protected
members from the base class are limited to private
. struct
inheritance on the other hand is public
by default.
In python the with
keyword is used when working with unmanaged resources (like file streams). It is similar to the using
statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally
blocks.
From Python Docs:
The
with
statement clarifies code that previously would usetry...finally
blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.The
with
statement is a control-flow structure whose basic structure is:with expression [as variable]: with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has
__enter__()
and__exit__()
methods).
Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with
with using
.
You didn't specify which environment. Assuming you are using IDLE.
From IDLE documentation: Command history:
Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
(These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.
HAVING is like WHERE with aggregate functions, or you could use a subquery.
select EmployeeId, sum(amount)
from Sales
group by Employee
having sum(amount) > 20000
Or
select EmployeeId, sum(amount)
from Sales
group by Employee
where EmployeeId in (
select max(EmployeeId) from Employees)
use the HorizontalContentAlignment property.
Sample
<Label HorizontalContentAlignment="Center"/>
I had almost precisely the same error, and was able to completely fix it simply by running:
gem install bundler
It's possible your bundler installation is corrupt or missing - that's what happened in my case. Note that if the above fails you can try:
sudo gem install bundler
...but generally you can do it without sudo.
Use the FirstOrDefault selector.
var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var firstEven = list.FirstOrDefault(n => n % 2 == 0);
if (firstEven == 0)
Console.WriteLine("no even number");
else
Console.WriteLine("first even number is {0}", firstEven);
Just pass in a predicate to the First or FirstOrDefault method and it'll happily go round' the list and picks the first match for you.
If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.
Hope this helps :-)
You can do it with document.getElementByID Here is how.
function dostuff (var here) {
if(add statment here) {
document.getElementById('First ID'));
document.getElementById('Second ID'));
}
}
There you go! xD
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateClient {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
You can remove the application's persistent domain like this:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
In Swift 3 and later:
if let bundleID = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundleID)
}
This is similar to the answer by @samvermette but is a little bit cleaner IMO.
I came to this page with the same question in mind, but it worked for me!, Just thought to update here , may be helpful for someone later!!
MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------+------+-----+---------+----------------+
| inv_id | int(4) | NO | PRI | NULL | auto_increment |
| cust_id | int(4) | NO | MUL | NULL | |
| inv_dt | date | NO | | NULL | |
| smen_id | int(4) | NO | MUL | NULL | |
+---------+--------+------+-----+---------+----------------+
4 rows in set (0.003 sec)
MariaDB [niffdb]> ALTER TABLE invoice MODIFY inv_dt DATE NOT NULL DEFAULT (CURRENT_DATE);
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+-----------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------+------+-----+-----------+----------------+
| inv_id | int(4) | NO | PRI | NULL | auto_increment |
| cust_id | int(4) | NO | MUL | NULL | |
| inv_dt | date | NO | | curdate() | |
| smen_id | int(4) | NO | MUL | NULL | |
+---------+--------+------+-----+-----------+----------------+
4 rows in set (0.002 sec)
MariaDB [niffdb]> SELECT VERSION();
+---------------------------+
| VERSION() |
+---------------------------+
| 10.3.18-MariaDB-0+deb10u1 |
+---------------------------+
1 row in set (0.010 sec)
MariaDB [niffdb]>
I had the same problem. Adding the gems 'execjs' and 'therubyracer' not work for me. apt-get install nodejs - also dosn't works. I'm using 64bit ubuntu 10.04.
But it helped me the following: 1. I created empty folder (for example "java"). 2. From the terminal in folder that I created I do:
$ git clone git://github.com/ry/node.git
$ cd node
$ ./configure
$ make
$ sudo make install
After that I run "bundle install" as usual (from folder with ruby&rails project). And the problem was resolved. Ruby did not have to reinstall.
create function [Sistema].[fParseDecimal]
(
@Valor nvarchar(4000)
)
returns decimal(18, 4) as begin
declare @Valores table (Valor varchar(50));
insert into @Valores values (@Valor);
declare @Resultado decimal(18, 4) = (select top 1
cast('' as xml).value('sql:column("Valor") cast as xs:decimal ?', 'decimal(18, 4)')
from @Valores);
return @Resultado;
END
To use Google Maps/Places APIs now, you're required to use an API Key. So the API URL will change from
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
to
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
The ideal datatype for storing Lat Long values is decimal(9,6)
This is at approximately 10cm precision, whilst only using 5 bytes of storage.
e.g. CAST(123.456789 as decimal(9,6))
Try this: use "%40" in place of the "@"
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:
The Code below checks if the key 'A' is down.
if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
// Do stuff
}
In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx
if(GetKeyState(VK_SHIFT) & 0x8000)
{
// Shift down
}
The low-order bit indicates if key is toggled.
SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;
Oh and also don't forget to
#include <Windows.h>
If you want to pretty print the data frames, then you can use tabulate package.
import pandas as pd
import numpy as np
from tabulate import tabulate
def pprint_df(dframe):
print tabulate(dframe, headers='keys', tablefmt='psql', showindex=False)
df = pd.DataFrame({'col1': np.random.randint(0, 100, 10),
'col2': np.random.randint(50, 100, 10),
'col3': np.random.randint(10, 10000, 10)})
pprint_df(df)
Specifically, the showindex=False
, as the name says, allows you to not show index. The output would look as follows:
+--------+--------+--------+
| col1 | col2 | col3 |
|--------+--------+--------|
| 15 | 76 | 5175 |
| 30 | 97 | 3331 |
| 34 | 56 | 3513 |
| 50 | 65 | 203 |
| 84 | 75 | 7559 |
| 41 | 82 | 939 |
| 78 | 59 | 4971 |
| 98 | 99 | 167 |
| 81 | 99 | 6527 |
| 17 | 94 | 4267 |
+--------+--------+--------+
tl;dr
cp -R "/src/project 1/App" "/src/project 2"
Explanation:
Using quotes will cater for spaces in the directory names
cp -R "/src/project 1/App" "/src/project 2"
If the App directory is specified in the destination directory:
cp -R "/src/project 1/App" "/src/project 2/App"
and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"
Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.
Inside a bash script:
cp -R "${1}/App" "${2}"
For Single Index :
df.index.rename('new_name')
For Multi Index :
df.index.rename(['new_name','new_name2'])
WE can also use this in latest pandas :
i always use connection.relase(); after pool.getconnetion like
pool.getConnection(function (err, connection) {
connection.release();
if (!err)
{
console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
//CHECKING USERNAME EXISTENCE
email = receivedValues.email
connection.query('SELECT * FROM users WHERE email = ?', [email],
function (err, rows) {
if (!err)
{
if (rows.length == 1)
{
if (bcrypt.compareSync(req.body.password, rows[0].password))
{
var alldata = rows;
var userid = rows[0].id;
var tokendata = (receivedValues, userid);
var token = jwt.sign(receivedValues, config.secret, {
expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
});
console.log("*** Authorised User");
res.json({
"code": 200,
"status": "Success",
"token": token,
"userData": alldata,
"message": "Authorised User!"
});
logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
return;
}
else
{
console.log("*** Redirecting: Unauthorised User");
res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
logger.error('*** Redirecting: Unauthorised User');
return;
}
}
else
{
console.error("*** Redirecting: No User found with provided name");
res.json({
"code": 200,
"status": "Error",
"message": "No User found with provided name"
});
logger.error('url=', URL.url, 'No User found with provided name');
return;
}
}
else
{
console.log("*** Redirecting: Error for selecting user");
res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
return;
}
});
connection.on('error', function (err) {
console.log('*** Redirecting: Error Creating User...');
res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
return;
});
}
else
{
Errors.Connection_Error(res);
}
});
You can also use Date.now() function.
None of the advanced answers to this question resolved the problem for me.
I managed to solve the problem by adding a dependencie to lombok in the pom.xml file, i.e. :
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.12</version>
</dependency>
I am using IntelliJ 2016.3.14 with maven-3.3.9
Hope my answer will be helpful for you
Just use cd /d %root%
to switch driver letters and change directories.
Alternatively, use pushd %root%
to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd
to switch back.
Note that pushd
will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd
for that directory.
I think if you want to add content directly to the body, the best way is:
document.body.innerHTML = document.body.innerHTML + "bla bla";
To replace it, use:
document.body.innerHTML = "bla bla";
Proceed like that :
Make a dump of your database first
Remove the primary key like that
ALTER TABLE yourtable DROP PRIMARY KEY
Add the new column like that
ALTER TABLE yourtable add column Id INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(Id)
The table will be looked and the AutoInc updated.
This answer is correct for old versions of iOS, but is now obsolete. You should use Micky Duncan's answer, which covers custom containers.
Don't do this! The intent of the UIViewController
is to drive the entire screen. It just isn't appropriate for this, and it doesn't really add anything you need.
All you need is an object that owns your custom view. Just use a subclass of UIView
itself, so it can be added to your window hierarchy and the memory management is fully automatic.
Point the subview NIB's owner a custom subclass of UIView
. Add a contentView
outlet to this custom subclass, and point it at the view within the nib. In the custom subclass do something like this:
- (id)initWithFrame: (CGRect)inFrame;
{
if ( (self = [super initWithFrame: inFrame]) ) {
[[NSBundle mainBundle] loadNibNamed: @"NibNameHere"
owner: self
options: nil];
contentView.size = inFrame.size;
// do extra loading here
[self addSubview: contentView];
}
return self;
}
- (void)dealloc;
{
self.contentView = nil;
// additional release here
[super dealloc];
}
(I'm assuming here you're using initWithFrame:
to construct the subview.)
Because it's the same component. You can either listen to route change by injecting the ActivatedRoute
and reacting to changes of params and query params, or you can change the default RouteReuseStrategy
, so that a component will be destroyed and re-rendered when the URL changes instead of re-used.
From the Java JDBC tutorial:
In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method
Class.forName
. Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the methodClass.forName
.)
So, if you're using the Oracle 11g (11.1) driver with Java 1.6, you don't need to call Class.forName
. Otherwise, you need to call it to initialise the driver.
The file .so is not a UNIX file extension for shared library.
It just happens to be a common one.
Check line 3b at ArnaudRecipes sharedlib page
Basically .dylib is the mac file extension used to indicate a shared lib.
David Walsh has a nice solution for this. Here is my take on this, combining his solution with what has been discovered on this thread as well.
https://davidwalsh.name/global-variables-javascript
x = {};
var iframe = document.createElement('iframe');
iframe.onload = function() {
var standardGlobals = Object.keys(iframe.contentWindow);
for(var b in window) {
const prop = window[b];
if(window.hasOwnProperty(b) && prop && !prop.toString().includes('native code') && !standardGlobals.includes(b)) {
x[b] = prop;
}
}
console.log(x)
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);
x
now has only the globals.
For emacs there is also gitsum
apt-get update apt-get upgrade
by far the easiest way to upgrade on linux, works like a charm everytime.
<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone required name='strMobileNo' ng-model="formModel.strMobileNo" type="text" placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>
the following code will help for phone number validation and the respected directive is
app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
return {
link: function(scope, elm) {
elm.on("keyup",function(){
var isMatchRegex = PHONE_REGEXP.test(elm.val());
if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
elm.removeClass('warning');
}else if(isMatchRegex == false && !elm.hasClass('warning')){
elm.addClass('warning');
}
});
}
}
});
In Eclipse Kepler,
JST Server Adapters
and JST Server Adapters Extensions
and install itAfter Eclipse restart, go to Window / Preferences / Server / Runtime Environments
I recommend you should clarify port that postgres. In my case I didn't know which port postgres was running on.
lsof -i | grep 'post'
then you can know which port is listening.
psql -U postgres -p "port_in_use"
with port option, might be answer. you can use psql.
Is it possible to have spring to inject the JPA entityManager object into my DAO class whitout extending JpaDaoSupport? if yes, does spring manage the transaction in this case?
This is documented black on white in 12.6.3. Implementing DAOs based on plain JPA:
It is possible to write code against the plain JPA without using any Spring dependencies, using an injected
EntityManagerFactory
orEntityManager
. Note that Spring can understand@PersistenceUnit
and@PersistenceContext
annotations both at field and method level if aPersistenceAnnotationBeanPostProcessor
is enabled. A corresponding DAO implementation might look like this (...)
And regarding transaction management, have a look at 12.7. Transaction Management:
Spring JPA allows a configured
JpaTransactionManager
to expose a JPA transaction to JDBC access code that accesses the same JDBC DataSource, provided that the registeredJpaDialect
supports retrieval of the underlying JDBC Connection. Out of the box, Spring provides dialects for the Toplink, Hibernate and OpenJPA JPA implementations. See the next section for details on theJpaDialect
mechanism.
Postgrseql 9.1 provides for a new command CREATE EXTENSION
. You should use it to install modules.
Modules provided in 9.1 can be found here.. The include,
adminpack , auth_delay , auto_explain , btree_gin , btree_gist
, chkpass , citext , cube , dblink , dict_int
, dict_xsyn , dummy_seclabel , earthdistance , file_fdw , fuzzystrmatch
, hstore , intagg , intarray , isn , lo
, ltree , oid2name , pageinspect , passwordcheck , pg_archivecleanup
, pgbench , pg_buffercache , pgcrypto , pg_freespacemap , pgrowlocks
, pg_standby , pg_stat_statements , pgstattuple , pg_test_fsync , pg_trgm
, pg_upgrade , seg , sepgsql , spi , sslinfo , tablefunc
, test_parser , tsearch2 , unaccent , uuid-ossp , vacuumlo
, xml2
If for instance you wanted to install earthdistance
, simply use this command:
CREATE EXTENSION earthdistance;
If you wanted to install an extension with a hyphen in its name, like uuid-ossp
, you need to enclose the extension name in double quotes:
CREATE EXTENSION "uuid-ossp";
DROP EXTENSION
. You can also get an extension list, and there is basic support for version numbers.The "call" solution has some problems.
It fails with many different contents, as the parameters of a CALL
are parsed twice by the parser.
These lines will produce more or less strange problems
one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty
the end
Therefore you shouldn't use the value of %%a
with a call, better move it to a variable and then call a function with only the name of the variable.
@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
set "myVar=%%a"
call :processLine myVar
)
goto :eof
:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof
Use TAB & TAB+SHIFT in a Specified container or element
we will handle TAB & TAB+SHIFT key listeners first
$(document).ready(function() {
lastIndex = 0;
$(document).keydown(function(e) {
if (e.keyCode == 9) var thisTab = $(":focus").attr("tabindex");
if (e.keyCode == 9) {
if (e.shiftKey) {
//Focus previous input
if (thisTab == startIndex) {
$("." + tabLimitInID).find('[tabindex=' + lastIndex + ']').focus();
return false;
}
} else {
if (thisTab == lastIndex) {
$("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
return false;
}
}
}
});
var setTabindexLimit = function(x, fancyID) {
console.log(x);
startIndex = 1;
lastIndex = x;
tabLimitInID = fancyID;
$("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
}
/*Taking last tabindex=10 */
setTabindexLimit(10, "limitTablJolly");
});
In HTML define tabindex
<div class="limitTablJolly">
<a tabindex=1>link</a>
<a tabindex=2>link</a>
<a tabindex=3>link</a>
<a tabindex=4>link</a>
<a tabindex=5>link</a>
<a tabindex=6>link</a>
<a tabindex=7>link</a>
<a tabindex=8>link</a>
<a tabindex=9>link</a>
<a tabindex=10>link</a>
</div>
git log --pretty=oneline tagA...tagB
(i.e. three dots)
If you just wanted commits reachable from tagB but not tagA:
git log --pretty=oneline tagA..tagB
(i.e. two dots)
or
git log --pretty=oneline ^tagA tagB
The simplest technique:
If your form action attribute is omitted, you can send a form to the same HTML file without actually using a GET HTTP access, just by using onClick on the button used for submitting the form. Then the form fields are in the elements array document.FormName.elements . Each element in that array has a value attribute containing the string the user provided (For INPUT elements). It also has id and name attributes, containing the id and/or name provided in the form child elements.
If you are using the grid or alike component: In XAML, make sure that the elements in the grid have Grid.Row and Grid.Column defined, and ensure tha they don't have margins. If you used designer mode, or Expression Blend, it could have assigned margins relative to the whole grid instead of to particular cells. As for cell sizing, I add an extra cell that fills up the rest of the space:
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
the only coding guidelines I've seen suggested for this is to put fields at the top of the class definition.
i tend to put constructors next.
my general comment would be that you should stick to one class per file and if the class is big enough that the organization of properties versus methods is a big concern, how big is the class and should you be refactoring it anyway? does it represent multiple concerns?
For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.
public static string[] GetStringInBetween(string strBegin,
string strEnd, string strSource,
bool includeBegin, bool includeEnd)
{
string[] result ={ "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin);
if (iIndexOfBegin != -1)
{
// include the Begin string if desired
if (includeBegin)
iIndexOfBegin -= strBegin.Length;
strSource = strSource.Substring(iIndexOfBegin
+ strBegin.Length);
int iEnd = strSource.IndexOf(strEnd);
if (iEnd != -1)
{
// include the End string if desired
if (includeEnd)
iEnd += strEnd.Length;
result[0] = strSource.Substring(0, iEnd);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd
+ strEnd.Length);
}
}
else
// stay where we are
result[1] = strSource;
return result;
}
let myobject= {}
let isempty = !!Object.values(myobject);
console.log(isempty);
_x000D_
For fixing such an issue I have used below code
a.divide(b, 2, RoundingMode.HALF_EVEN)
2 is precision. Now problem was resolved.
Register the EventEmitter
in your child component as the @Output
:
@Output() onDatePicked = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
Listen for the events in your parent component's template:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
and in the parent component:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
It's also well explained in the official docs: Component interaction.
You just need to get the value of the texbox and see if it has anything in it:
if (!$(`#textareaid`).val().length)
{
//do stuff
}
Following leppie's answer, why not make MetaData
an interface:
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
If Duff's device doesn't need a goto, then neither should you! ;)
void dsend(int count) {
int n;
if (!count) return;
n = (count + 7) / 8;
switch (count % 8) {
case 0: do { puts("case 0");
case 7: puts("case 7");
case 6: puts("case 6");
case 5: puts("case 5");
case 4: puts("case 4");
case 3: puts("case 3");
case 2: puts("case 2");
case 1: puts("case 1");
} while (--n > 0);
}
}
code above from Wikipedia entry.
Three options here.
Standard JavaScript answer: Use a framework! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST.
Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. (More information in Using POST method in XMLHTTPRequest (Ajax).)
Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.
Try the simplest one. Maybe Your app is crashing because your image size (in MB) is too large so it is not allocating space for that. So before pasting your image in drawable just reduce the size by any viewer software or if you are taking image from gallery at the run time than before saving it compress your bitmap. It worked for me. definitely for u will be.
I think this is what you want:
document.getElementById('tag-id').innerHTML = '<ol><li>html data</li></ol>';
Keep in mind that innerHTML is not accessible for all types of tags when using IE. (table elements for example)
ArrayList<String>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add("test");
I usually do:
grep install_targets Makefile
It would come back with something like:
install_targets = install-xxx1 install-xxx2 ... etc
I hope this helps
Yes do it.
It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.
A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.
I wrote an article on how to set a hyperlink or a mailto on a jLabel.
So just try it :
I think that's exactly what you're searching for.
Here's the complete code example :
/**
* Example of a jLabel Hyperlink and a jLabel Mailto
*/
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author ibrabelware
*/
public class JLabelLink extends JFrame {
private JPanel pan;
private JLabel contact;
private JLabel website;
/**
* Creates new form JLabelLink
*/
public JLabelLink() {
this.setTitle("jLabelLinkExample");
this.setSize(300, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
pan = new JPanel();
contact = new JLabel();
website = new JLabel();
contact.setText("<html> contact : <a href=\"\">[email protected]</a></html>");
contact.setCursor(new Cursor(Cursor.HAND_CURSOR));
website.setText("<html> Website : <a href=\"\">http://www.google.com/</a></html>");
website.setCursor(new Cursor(Cursor.HAND_CURSOR));
pan.add(contact);
pan.add(website);
this.setContentPane(pan);
this.setVisible(true);
sendMail(contact);
goWebsite(website);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Create and display the form
*/
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new JLabelLink().setVisible(true);
}
});
}
private void goWebsite(JLabel website) {
website.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
});
}
private void sendMail(JLabel contact) {
contact.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().mail(new URI("mailto:[email protected]?subject=TEST"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
});
}
}
$.inArray
returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is
if(jQuery.inArray("test", myarray) != -1) {
console.log("is in array");
} else {
console.log("is NOT in array");
}
Yes, it's possible, from @Fábio Zangirolami answer
audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
background-color: red;
}
No, but it's been requested many times.
That error means your node's publish is low than the need. carefully to update the node of your computer.
Unlike SOAP, REST isn't a standardized protocol so it's a bit difficult to have a "REST Client". However, since most RESTful services use HTTP as their underlying protocol, you should be able to use any HTTP library. In addition to cURL, PHP has these via PEAR:
which replaced
A sample of how they do HTTP Basic Auth
// This will set credentials for basic auth
$request = new HTTP_Request2('http://user:[email protected]/secret/');
The also support Digest Auth
// This will set credentials for Digest auth
$request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);
I found this to work very well!
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
Use:
<?php
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
include(findRoot() . 'Post.php');
$posts = getPosts(findRoot() . 'posts_content');
include(findRoot() . 'includes/head.php');
for ($i=(sizeof($posts)-1); 0 <= $i; $i--) {
$posts[$i]->displayArticle();
}
include(findRoot() . 'includes/footer.php');
?>
michal.kreuzman nice one I will have to say. It was useful.
However, the above works only for single digits: if you are going to use more than one digit, the structure is going to get misplaced since you are using spaces and not tabs.
As for my later codes I needed more digits than only 2, so I made a program myself.
It has some bugs now, again right now I am feeling lazy to correct them but it prints very beautifully and the nodes can take a larger number of digits.
The tree is not going to be as the question mentions but it is 270 degrees rotated :)
public static void printBinaryTree(TreeNode root, int level){
if(root==null)
return;
printBinaryTree(root.right, level+1);
if(level!=0){
for(int i=0;i<level-1;i++)
System.out.print("|\t");
System.out.println("|-------"+root.val);
}
else
System.out.println(root.val);
printBinaryTree(root.left, level+1);
}
Place this function with your own specified TreeNode and keep the level initially 0, and enjoy!
Here are some of the sample outputs:
| | |-------11
| |-------10
| | |-------9
|-------8
| | |-------7
| |-------6
| | |-------5
4
| |-------3
|-------2
| |-------1
| | | |-------10
| | |-------9
| |-------8
| | |-------7
|-------6
| |-------5
4
| |-------3
|-------2
| |-------1
Only problem is with the extending branches; I will try to solve the problem as soon as possible but till then you can use it too.
This one is correct:
ALTER TABLE `users`
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;
Look in JavaScript split() Method
Usage:
"something -- something_else".split(" -- ")
In order to search for a specific method in a whole module
for method in dir(module) :
if "keyword_of_methode" in method :
print(method, end="\n")
You can do
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();
or (using Method reference)
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();
[HttpPost]
public async Task<ActionResult> Capture(string imageData)
{
if (imageData.Length > 0)
{
var imageBytes = Convert.FromBase64String(imageData);
using (var stream = new MemoryStream(imageBytes))
{
var result = (JsonResult)await IdentifyFace(stream);
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));
if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });
}
}
return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);
}
// GET: Auth
[HttpGet]
public ActionResult Index(string param)
{
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(param);
return View(faceRecon);
}
It is a Bootstrap defined HTML5 data attribute. It binds a button to an event.
The second one creates a new array of Integers (first pass), and then adds all the elements of this new array to the list (second pass). It will thus be less efficient than the first one, which makes a single pass and doesn't create an unnecessary array of Integers.
A better way to use streams would be
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
Which should have roughly the same performance as the first one.
Note that for such a small array, there won't be any significant difference. You should try to write correct, readable, maintainable code instead of focusing on performance.
I think this solution uses less code and is easy to understand even for newbie.
For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.
Define definition of struct:
typedef struct {
int number;
char *name;
char *address;
char *birthdate;
char gender;
} Patient;
Initialize variable with type of that struct:
Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";
It is that simple. Hope this answer helps many developers.
As a matter of fact, specifying parameters explicitly as ?date='fulldatetime' worked like a charm. So this will be a solution for now: don't use commas, but use old GET approach.