The iterator_facade documentation from Boost.Iterator provides what looks like a nice tutorial on implementing iterators for a linked list. Could you use that as a starting point for building a random-access iterator over your container?
If nothing else, you can take a look at the member functions and typedefs provided by iterator_facade
and use it as a starting point for building your own.
I will give you a better idea
for(decltype(things.size()) i = 0; i < things.size(); i++){
//...
}
decltype
is
Inspects the declared type of an entity or the type and value category of an expression.
So, It deduces type of things.size()
and i
will be a type as same as things.size()
. So,
i < things.size()
will be executed without any warning
NOTE: git whatchanged
is deprecated, use git log
instead
New users are encouraged to use git-log[1] instead. The
whatchanged
command is essentially the same as git-log[1] but defaults to show the raw format diff output and to skip merges.The command is kept primarily for historical reasons; fingers of many people who learned Git long before
git log
was invented by reading Linux kernel mailing list are trained to type it.
You can use the command git whatchanged --stat
to get a list of files that changed in each commit (along with the commit message).
In angular 1, you can use ng-show
and ng-hide
.In your case, you would use ng-hide
. For example:
<li ng-hide="area"></li>
Here you go...
- (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
NSUInteger location = 0;
unichar charBuffer[[strtoremove length]];
[strtoremove getCharacters:charBuffer];
int i = 0;
for(i = [strtoremove length]; i >0; i--) {
NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
if(![charSet characterIsMember:charBuffer[i - 1]]) {
break;
}
}
return [strtoremove substringWithRange:NSMakeRange(location, i - location)];
}
So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:
NSString *oneTwoThree = @" TestString ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];
resultString
will then have no spaces at the end.
According to the official documentation, a click on any link in WebView launches an application that handles URLs, which by default is a browser. You need to override the default behavior like this
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
Handy way: Using Browser Printing/Preview
public function plainText($text)
{
$text = strip_tags($text, '<br><p><li>');
$text = preg_replace ('/<[^>]*>/', PHP_EOL, $text);
return $text;
}
$text = "string 1<br>string 2<br/><ul><li>string 3</li><li>string 4</li></ul><p>string 5</p>";
echo planText($text);
output
string 1
string 2
string 3
string 4
string 5
As my first object is a native javascript object (used like a list of objects), push
didn't work in my escenario, but I resolved it by adding new key as following:
MyObjList['newKey'] = obj;
In addition to this, may be usefull to know how to delete same object inserted before:
delete MyObjList['newKey'][id];
Hope it helps someone as it helped me;
As of HTML5 it is OK to wrap <a>
elements around a <div>
(or any other block elements):
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).
Just have to make sure you don't put an <a>
within your <a>
( or a <button>
).
I stumbled upon this example on https://css-tricks.com/snippets/jquery/smooth-scrolling/ explaining every line of code. I found this to be the best option.
https://css-tricks.com/snippets/jquery/smooth-scrolling/
You can go native:
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
window.scrollBy({
top: 100, // could be negative value
left: 0,
behavior: 'smooth'
});
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
or with jquery:
$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
}
});
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
set
When x in seen
is True
:
x
's sequence 511, 256, 129, 68, 41, 32, 31, 31;Hence, it suffices to stop as soon as the current x
is greater than or equal to the previous one:
def is_square(n):
assert n > 1
previous = n
x = n // 2
while x * x != n:
x = (x + (n // x)) // 2
if x >= previous:
return False
previous = x
return True
x = 12345678987654321234567 ** 2
assert not is_square(x-1)
assert is_square(x)
assert not is_square(x+1)
Equivalence with the original algorithm tested for 1 < n < 10**7. On the same interval, this slightly simpler variant is about 1.4 times faster.
In my company, we write software for the Avionics and Defense market, and we always include a default statement, because ALL cases in a switch statement must be explicitly handled (even if it is just a comment saying 'Do nothing'). We cannot afford the software just to misbehave or simply crash on unexpected (or even what we think impossible) values.
It can be discussed that a default case is not always necessary, but by always requiring it, it is easily checked by our code analyzers.
The x86 instruction set includes an unsigned multiply instruction that stores the result to two registers. To use that instruction from C, one can write the following code in a 64-bit program (GCC):
unsigned long checked_imul(unsigned long a, unsigned long b) {
unsigned __int128 res = (unsigned __int128)a * b;
if ((unsigned long)(res >> 64))
printf("overflow in integer multiply");
return (unsigned long)res;
}
For a 32-bit program, one needs to make the result 64 bit and parameters 32 bit.
An alternative is to use compiler-dependent intrinsic to check the flag register. GCC documentation for overflow intrinsic can be found from 6.56 Built-in Functions to Perform Arithmetic with Overflow Checking.
In this post Scrollview vertical and horizontal in android they talk about a possible solution, quoting:
Matt Clark has built a custom view based on the Android source, and it seems to work perfectly: http://blog.gorges.us/2010/06/android-two-dimensional-scrollview
Beware that the class in that page has a bug calculating the view's horizonal width. A fix by Manuel Hilty is in the comments:
Solution: Replace the statement on line 808 by the following:
final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
For those who are trying to get an X Window application working from Windows from Linux:
What worked for me was to setup xming server on my windows machine, set X11 forwarding option in putty when I connect to the linux host and put in my windows ip address with the display port and then the display variable with my windows IP address:0.0
Dont forget to add the linux hosts IP address to the X0.hosts file to ensure that the xming server accepts traffic from that host. Took me a while to figure that out.
you should try with jquery validate plugin :
$('form').validate({
rules:{
email:{
required:true,
email:true
}
},
messages:{
email:{
required:"Email is required",
email:"Please type a valid email"
}
}
})
If you are using string
datatype, below code works:
string str = str.Remove(str.Length - 1);
But when you have StringBuilder
, you have to specify second parameter length
as well.
That is,
string newStr = sb.Remove(sb.Length - 1, 1).ToString();
To avoid below error:
You can use:
button.titleLabel.font = [UIFont systemFontOfSize:14.0];
I guess you can use:
$con = new mysqli("localhost", "my_user", "my_password", "world");
$sql = "UPDATE `some_table` SET `txid`= '$txid', `data` = '$data' WHERE `wallet` = '$wallet'";
if ($mysqli->query($sql, $con)) {
print "wallet $wallet updated";
}else{
printf("Errormessage: %s\n", $con->error);
}
$con->close();
I believe the simplest solution would be to use find
. I do not like to have multiple .gitignore
hanging around in sub-directories and I prefer to manage a unique, top-level .gitignore
. To do so you could simply append the found files to your .gitignore
. Supposing that /public/static/
is your project/git home I would use something like:
find . -type f -name *.js | cut -c 3- >> .gitignore
I found that cutting out the ./
at the beginning is often necessary for git to understand which files to avoid. Therefore the cut -c 3-
.
I just created a project which explain what is the difference between all subjects:
https://github.com/piecioshka/rxjs-subject-vs-behavior-vs-replay-vs-async
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:
struct { 11
char a; 012345678901
short b; ------------
char c; axbbcxxxdddd
int d;
};
This structure will occupy 12 bytes of memory (x being pad bytes).
Python works similarly (see the struct documentation):
>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12
Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:
>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'
Beware of letting struct handle padding. In C, these structures:
struct A { struct B {
short a; int a;
char b; char b;
}; };
are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:
>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
i. Please check the InnerException
property of the TypeInitializationException
ii. Also, this may occur due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly
In the "Repeat Task every:" just type 2 minutes instead of choosing from the dropdown list.
Haven't tried it myself, but I think
has a lot of potential...
coming from php and classic asp, it's the first java web framework that sounds promising to me....
Edit by original question asker - 2011-06-09
Just wanted to provide an update.
I went with Play and it was exactly what I asked for. It requires very little configuration, and just works out of the box. It is unusual in that it eschews some common Java best-practices in favor of keeping things as simple as possible.
In particular, it makes heavy use of static methods, and even does some introspection on the names of variables passed to methods, something not supported by the Java reflection API.
Play's attitude is that its first goal is being a useful web framework, and sticking to common Java best-practices and idioms is secondary to that. This approach makes sense to me, but Java purists may not like it, and would be better-off with Apache Wicket.
In summary, if you want to build a web-app with convenience and simplicity comparable to a framework like Ruby on Rails, but in Java and with the benefit of Java's tooling (eg. Eclipse), then Play Framework is a great choice.
When you call document.write
after a page has loaded it will eliminate all content and replace it with the parameter you provide. Instead use DOM methods to add content, for example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
var text = document.createTextNode('hi');
OpenWindow.document.body.appendChild(text);
If you want to use jQuery you get some better APIs to deal with. For example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).append('<p>hi</p>');
If you need the code to run after the new window's DOM is ready try:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).ready(function() {
$(OpenWindow.document.body).append('<p>hi</p>');
});
A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare()
or equals()
implementation).
Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs
This could be done like this
var inputfile= $('#uploadCaptureInputFile')_x000D_
$('#reset').on('click',function(){_x000D_
inputfile.replaceWith(inputfile.val('').clone(true));_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />_x000D_
<a href="" id="reset">Reset</a>
_x000D_
You can also use batch functions for this:
@echo off
setlocal
goto MAIN
::-----------------------------------------------
:: "%~f2" get abs path of %~2.
::"%~fs2" get abs path with short names of %~2.
:setAbsPath
setlocal
set __absPath=%~f2
endlocal && set %1=%__absPath%
goto :eof
::-----------------------------------------------
:MAIN
call :setAbsPath ABS_PATH ..\
echo %ABS_PATH%
endlocal
export https_proxy=http://user:pswd@host:port
^^^^
Use http
for https_proxy instead of https
The GetHashCode
function is specifically designed to create a well distributed range of integers with a low probability of collision, so for this use case is likely to be the best you can do.
But, as I'm sure you're aware, hashing 128 bits of information into 32 bits of information throws away a lot of data, so there will almost certainly be collisions if you have a sufficiently large number of GUIDs.
finalize()
is called just before garbage collection. It is not called when an object goes out of scope. This means that you cannot know when or even if finalize()
will be executed.
Example:
If your program end before garbage collector occur, then finalize()
will not execute. Therefore, it should be used as backup procedure to ensure the proper handling of other resources, or for special use applications, not as the means that your program uses in its normal operation.
<input data-ng-model="userInf.username" class="span12 editEmail" type="text" placeholder="[email protected]" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required ng-disabled="true"/>
The best practice is to check the Identity.IsAuthenticated
Property first and then get the usr.UserName
like this:
string userName = string.Empty;
if (System.Web.HttpContext.Current != null &&
System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
System.Web.Security.MembershipUser usr = Membership.GetUser();
if (usr != null)
{
userName = usr.UserName;
}
}
This issue has been discussed in https://github.com/twbs/bootstrap/issues/10203 By now, there is no plan to change Grid because compatibility reasons.
You can get Bootstrap from this fork, branch hs
: https://github.com/antespi/bootstrap/tree/hs
This branch give you an extra breakpoint at 480px, so yo have to:
Design mobile first is the key to understand Bootstrap 3. This is the major change from BootStrap 2.x. As a rule template you can follow this (in LESS):
.template {
/* rules for mobile vertical (< 480) */
@media (min-width: @screen-hs-min) {
/* rules for mobile horizontal (480 > 768) */
}
@media (min-width: @screen-sm-min) {
/* rules for tablet (768 > 992) */
}
@media (min-width: @screen-md-min) {
/* rules for desktop (992 > 1200) */
}
@media (min-width: @screen-lg-min) {
/* rules for large (> 1200) */
}
}
If you want to initialize a vector with numeric values other than zero, use rep
n <- 10
v <- rep(0.05, n)
v
which will give you:
[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05
INSERT
syntax cannot have WHERE
clause. The only time you will find INSERT
has WHERE
clause is when you are using INSERT INTO...SELECT
statement.
The first syntax is already correct.
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
select * into newtable from oldtable
Unicode currently has 74605 CJK characters. CJK characters not only includes characters used by Chinese, but also Japanese Kanji, Korean Hanja, and Vietnamese Chu Nom. Some CJK characters are not Chinese characters.
Code points U+4E00 to U+9FCC.
Code points U+3400 to U+4DB5. Unicode 3.0 (1999).
Code points U+20000 to U+2A6D6. Unicode 3.1 (2001).
Code points U+2A700 to U+2B734. Unicode 5.2 (2009).
Code points U+2B740 to U+2B81D. Unicode 6.0 (2010).
If the above is not spaghetti enough, take a look at known issues. Have fun =)
Atom does not have a built-in command for formatting html. However, you can install the atom-beautify package to get this behavior.
I removed the bin and obj folders from old C# projects using git on windows. Be careful with
git filter-branch --tree-filter "rm -rf bin" --prune-empty HEAD
It destroys the integrity of the git installation by deleting the usr/bin folder in the git install folder.
You simply need to enclose your SELECT
statements in parentheses to indicate that they are subqueries:
SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);
Alternatively, you can use MySQL's SELECT ... INTO
syntax. One advantage of this approach is that both cityLat
and cityLng
can be assigned from a single table-access:
SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;
However, the entire procedure can be replaced with a single self-joined SELECT
statement:
SELECT b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM cities AS a, cities AS b
WHERE a.id = cityID
ORDER BY dist
LIMIT 10;
Protected internal best suites when you want a member or type to be used in a derived class from another assembly at the same time just want to consume the member or type in the parent assembly without deriving from the class where it is declared. Also if you want only to use a member or type with out deriving from another class, in the same assembly you can use internal only.
You can try wiht TIMESTAMP(curdate(), curtime()) for use the current time.
@zhutoulala -- FWIW your links worked for me with Hadoop 2.4.0 with one exception I had to tell maven not to build the javadocs. I also used the patch in the first link for 2.4.0 and it worked fine. Here's the maven command I had to issue
mvn package -Dmaven.javadoc.skip=true -Pdist,native -DskipTests -Dtar
After building this and moving the libraries, don't forget to update hadoop-env.sh :)
Thought this might help someone who ran into the same roadblocks as me
I recently discovered the rather useful sweep
function and add it here for the sake of completeness:
sweep
The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):
Let's say you have a matrix and want to standardize it column-wise:
dataPoints <- matrix(4:15, nrow = 4)
# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)
# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)
# Center the points
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")
# Return the result
dataPoints_Trans1
## [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,] 0.5 0.5 0.5
## [4,] 1.5 1.5 1.5
# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")
# Return the result
dataPoints_Trans2
## [,1] [,2] [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,] 0.3872983 0.3872983 0.3872983
## [4,] 1.1618950 1.1618950 1.1618950
NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)
Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))
It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf
style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite
).
Firstly,Object is created and then we assign it 's address to pointers.Constructors are called at the time of object creation and used to initializ the value of data members. Pointer to object comes into scenario after object creation. Thats why, C++ do not allows us to make constructors as virtual . .another reason is that, There is nothing like pointer to constructor , which can point to virtual constructor,because one of the property of virtual function is that it can be used by pointers only.
This works fine for me:
<style type="text/css">_x000D_
#table {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
</style>
_x000D_
For me, just changing Height and Width to 100% doesn’t do it for me, and neither do setting left, right, top and bottom to 0, but using them both together will do the trick.
you can use the below method to extract all numbers from a string.
def extract_numbers_from_string(string):
number = ''
for i in string:
try:
number += str(int(i))
except:
pass
return number
(OR) you could use i.isdigit()
or i.isnumeric
(in Python 3.6.5 or above)
def extract_numbers_from_string(string):
number = ''
for i in string:
if i.isnumeric():
number += str(int(i))
return number
a = '343fdfd3'
print (extract_numbers_from_string(a))
# 3433
Your Code is Fine just you need to place it inside the ready function.
$(document).ready( function() {
$("#cpa-form").submit(function(e){
e.preventDefault();
});
}
Try with bufferFileWriter.append, it works with me.
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
I'm answering only the part of the question about zbar
installation.
I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:
Install it with pip install zbar-0.10-cp27-none-win_amd64.whl
If Python reports an ImportError: DLL load failed: The specified module could not be found.
when doing import zbar
, then you will just need to install the Visual C++ Redistributable Packages for VS 2013 (I spent a lot of time here, trying to recompile unsuccessfully...)
Required too: libzbar64-0.dll must be in a folder which is in the PATH. In my case I copied it to "C:\Python27\libzbar64-0.dll" (which is in the PATH). If it still does not work, add this:
import os
os.environ['PATH'] += ';C:\\Python27'
import zbar
PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.
PS2: I just tested pyzbar with pip install pyzbar
and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.
My use case was to save range to variable and then select it later on
Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset
I agree with many here, but I also think it depends.
Recently I did this code:
private void animate(FlowLayoutPanel element, int start, int end)
{
bool asc = end > start;
element.Show();
while (start != end) {
start += asc ? 1 : -1;
element.Height = start;
Thread.Sleep(1);
}
if (!asc)
{
element.Hide();
}
element.Focus();
}
It was a simple animate-function, and I used Thread.Sleep
on it.
My conclusion, if it does the job, use it.
<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>
jquery part
$(".rg").change(function () {
if ($("#r1").attr("checked")) {
$('#r1edit:input').removeAttr('disabled');
}
else {
$('#r1edit:input').attr('disabled', 'disabled');
}
});
here is the DEMO
well the simplest answer i tried is just remove your code which makes the activity go full screen .I had a code like this which was responsible for making my activity go fullscreen :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
i just removed my code and it works completely fine although if you want to achieve this with your fullscreen on then you'll have to try some other methods
-w
is the GCC-wide option to disable warning messages.
To send the raw file only:
using(WebClient client = new WebClient()) {
client.UploadFile(address, filePath);
}
If you want to emulate a browser form with an <input type="file"/>
, then that is harder. See this answer for a multipart/form-data answer.
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
Swift 2 Version
As @Johan Karlsson pointed out... I was doing it wrong. Here's the proper way to send and receive information with NSNotificationCenter.
First, we look at the initializer for postNotificationName:
init(name name: String,
object object: AnyObject?,
userInfo userInfo: [NSObject : AnyObject]?)
We'll be passing our information using the userInfo
param. The [NSObject : AnyObject]
type is a hold-over from Objective-C. So, in Swift land, all we need to do is pass in a Swift dictionary that has keys that are derived from NSObject
and values which can be AnyObject
.
With that knowledge we create a dictionary which we'll pass into the object
parameter:
var userInfo = [String:String]()
userInfo["UserName"] = "Dan"
userInfo["Something"] = "Could be any object including a custom Type."
Then we pass the dictionary into our object parameter.
Sender
NSNotificationCenter.defaultCenter()
.postNotificationName("myCustomId", object: nil, userInfo: userInfo)
Receiver Class
First we need to make sure our class is observing for the notification
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("btnClicked:"), name: "myCustomId", object: nil)
}
Then we can receive our dictionary:
func btnClicked(notification: NSNotification) {
let userInfo : [String:String!] = notification.userInfo as! [String:String!]
let name = userInfo["UserName"]
print(name)
}
Is the Config/setup.php
file actually in /test/content/home/
or is in your document root? it is best to make all references relative to your document root.
include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";
Your current code assumes that the location of setup.php
is in /text/content/home/Config/setup.php
, is this correct?
$('div#someID').datepicker({
onSelect: function(dateText, inst) { alert(dateText); }
});
you must bind it to input element only
Now, simply using colorAccent
and colorPrimary
will work perfectly.
You can't do it with just CSS, but you can do it with Javascript, and (optionally) jQuery.
If you want to do it without jQuery:
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
</script>
And to do it without jQuery, and only on a specific class (ex: hohoho
):
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if(/\bhohoho\b/).match(anchor.className)) {
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
}
</script>
If you are okay with using jQuery, then you can do this for all anchors:
<script>
$(document).ready(function() {
$('a').click(function() {
alert('ho ho ho');
});
});
</script>
And this jQuery snippet to only apply it to anchors with a specific class:
<script>
$(document).ready(function() {
$('a.hohoho').click(function() {
alert('ho ho ho');
});
});
</script>
After creating Set just convert it to List and get by index from List:
Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");
List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";
right click on project -> go to maven -> update project
this fixed my problem when nothing else could
This worked for me but only after forcing the specific verbs to be handled by the default handler.
<system.web>
...
<httpHandlers>
...
<add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>
You still use the same configuration as you have above, but also force the verbs to be handled with the default handler and validated. Source: http://forums.asp.net/t/1311323.aspx
An easy way to test is just to deny GET and see if your site loads.
A simple Toast message works also as a quick check.
increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin
heap size can be changed based on Requirements.
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
This one-liner is pretty much the same as your original try with a couple of additions. It works with paths including spaces, and works in both XP and Windows 7 even if the key is not found (and hides the error). %fn%
will be empty if the key does not exist. This example gets the current desktop background filename:
for /f "tokens=2*" %%a in ('reg query "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper 2^>^&1^|find "REG_"') do @set fn=%%b
This command uses tokens=2*
with %%a
as the loop variable but consumes %%b
to correctly handle spaces. When using tokens=2*
, the loop variable %%a
is assigned the value in the second token (in this case, REG_SZ
) and %%b
is assigned the remainder of the line after the next group of delimiter characters, including all internal delimiter characters. This means that %%b
will correctly replicate delimiter characters—even if multiple delimiter characters are clustered together. For example, the value might be C:\A weird path\blah.png
. This technique of reading the value would correctly preserve the two spaces between C:\A
and weird
.
Here's a working example:
<div class="item item-text-wrap" ng-repeat="(key,value) in form_list">
<b>{{key}}</b> : {{value}}
</div>
edited
Bind in the icons from this site!
https://github.com/pointhi/leaflet-color-markers
Detailed how-to information included on the website.
Edit: Use the code below to add a marker icon and just replace the link to the one with the color of your choice. (i.e. marker-icon-2x-green.png
to some other image)
var greenIcon = new L.Icon({
iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);
CREATE FUNCTION dbo.UdfGetProductsScrapStatus
(
@ScrapComLevel INT
)
RETURNS @ResultTable TABLE
(
ProductName VARCHAR(50), ScrapQty FLOAT, ScrapReasonDef VARCHAR(100), ScrapStatus VARCHAR(50)
) AS BEGIN
INSERT INTO @ResultTable
SELECT PR.Name, SUM([ScrappedQty]), SC.Name, NULL
FROM [Production].[WorkOrder] AS WO
INNER JOIN
Production.Product AS PR
ON Pr.ProductID = WO.ProductID
INNER JOIN Production.ScrapReason AS SC
ON SC.ScrapReasonID = WO.ScrapReasonID
WHERE WO.ScrapReasonID IS NOT NULL
GROUP BY PR.Name, SC.Name
UPDATE @ResultTable
SET ScrapStatus =
CASE WHEN ScrapQty > @ScrapComLevel THEN 'Critical'
ELSE 'Normal'
END
RETURN
END
Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()
)
See Kotlin's documentation
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads
and then you can parse it with index.
Instead of using .read()
to intermediately save it to memory and then read it to json
, allow json
to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
I had this problem and I realized that I was assuming that Geocoding came with the JS maps API. However, it is a separate API which I hadn't enabled in the cloud console. Enabling it fixed it right away.
Here is how a UTF8 text file can be read from a zip archive into a string variable (.NET Framework 4.5 and up):
string zipFileFullPath = "{{TypeYourZipFileFullPathHere}}";
string targetFileName = "{{TypeYourTargetFileNameHere}}";
string text = new string(
(new System.IO.StreamReader(
System.IO.Compression.ZipFile.OpenRead(zipFileFullPath)
.Entries.Where(x => x.Name.Equals(targetFileName,
StringComparison.InvariantCulture))
.FirstOrDefault()
.Open(), Encoding.UTF8)
.ReadToEnd())
.ToArray());
stringify-object
is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-object
npm install stringify-object
then:
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
Obviously it's interesting only if you have circular object that would fail with JSON.stringify();
Declare @dob datetime
Declare @today datetime
Set @dob = '05/20/2000'
set @today = getdate()
select CASE
WHEN dateadd(year, datediff (year, @dob, @today), @dob) > @today
THEN datediff (year, @dob, @today) - 1
ELSE datediff (year, @dob, @today)
END as Age
Just got a solution to get height and width of a custom view:
@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
super.onSizeChanged(xNew, yNew, xOld, yOld);
viewWidth = xNew;
viewHeight = yNew;
}
Its working in my case.
npm install rxjs@6 rxjs-compat@6 --save
If you have >100 images that you want to have drop shadows for, I would suggest using the command-line program ImageMagick. With this, you can apply shaped drop shadows to 100 images just by typing one command! For example:
for i in "*.png"; do convert $i '(' +clone -background black -shadow 80x3+3+3 ')' +swap -background none -layers merge +repage "shadow/$i"; done
The above (shell) command takes each .png file in the current directory, applies a drop shadow, and saves the result in the shadow/ directory. If you don't like the drop shadows generated, you can tweak the parameters a lot; start by looking at the documentation for shadows, and the general usage instructions have a lot of cool examples of things that can be done to images.
If you change your mind in the future about the look of the drop shadows - it's just one command to generate new images with different parameters :-)
First of all, you should look gradle.properties and these values have to be true. If you cannot see them you have to write.
android.useAndroidX=true
android.enableJetifier=true
After that you can use AndroidX dependencies in your build.gradle (Module: app). Also, you have to check compileSDKVersion and targetVersion. They should be minimum 28. For example I am using 29.
So, an androidx dependency example:
implementation 'androidx.cardview:cardview:1.0.0'
However be careful because everything is not start with androidx like cardview dependency. For example, old design dependency is:
implementation 'com.android.support:design:27.1.1'
But new design dependency is:
implementation 'com.google.android.material:material:1.3.0'
RecyclerView is:
implementation 'androidx.recyclerview:recyclerview:1.1.0'
So, you have to search and read carefully. Happy code.
@canerkaseler
No answer seems to deal with the OverflowException/UnderflowException that comes from trying to convert a decimal that is outside the range of int.
int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));
This solution will return the maximum or minimum int value possible if the decimal value is outside the int range. You might want to add some rounding with Math.Round, Math.Ceiling or Math.Floor for when the value is inside the int range.
Private Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
Maybe you should just write the ImageView first and the TextView second. That can help sometimes. That's simple but I hope it helps somebody. :)
Position absolute fixes it for me. I suggest also adding a semi-colon if you haven't already.
.container {
width: 22.5%;
size: 22.5% 22.5%;
margin-top: 0%;
border-radius: 10px;
background-color: floralwhite;
display:inline-block;
min-height: 20%;
position: absolute;
height: 50%;
}
You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
You can also download the correct chromedriver version from:
https://chromedriver.chromium.org/downloads https://chromedriver.storage.googleapis.com/index.html?path=81.0.4044.138/
Adding to slebetman's answer for more clarity on what happens while executing the code.
The internal thread pool in nodeJs just has 4 threads by default. and its not like the whole request is attached to a new thread from the thread pool the whole execution of request happens just like any normal request (without any blocking task) , just that whenever a request has any long running or a heavy operation like db call ,a file operation or a http request the task is queued to the internal thread pool which is provided by libuv. And as nodeJs provides 4 threads in internal thread pool by default every 5th or next concurrent request waits until a thread is free and once these operations are over the callback is pushed to the callback queue. and is picked up by event loop and sends back the response.
Now here comes another information that its not once single callback queue, there are many queues.
Whenever a request comes the code gets executing in this order of callbacks queued.
It is not like when there is a blocking request it is attached to a new thread. There are only 4 threads by default. So there is another queueing happening there.
Whenever in a code a blocking process like file read occurs , then calls a function which utilises thread from thread pool and then once the operation is done , the callback is passed to the respective queue and then executed in the order.
Everything gets queued based on the the type of callback and processed in the order mentioned above.
It seems that in RxJS 5.2.0 the .first()
operator has a bug,
Because of that bug .take(1)
and .first()
can behave quite different if you are using them with switchMap
:
With take(1)
you will get behavior as expected:
var x = Rx.Observable.interval(1000)
.do( x=> console.log("One"))
.take(1)
.switchMap(x => Rx.Observable.interval(1000))
.do( x=> console.log("Two"))
.subscribe((x) => {})
// In the console you will see:
// One
// Two
// Two
// Two
// Two
// etc...
But with .first()
you will get wrong behavior:
var x = Rx.Observable.interval(1000)
.do( x=> console.log("One"))
.first()
.switchMap(x => Rx.Observable.interval(1000))
.do( x=> console.log("Two"))
.subscribe((x) => {})
// In console you will see:
// One
// One
// Two
// One
// Two
// One
// etc...
Here's a link to codepen
Maven is not installed any more by default on Mac OS X 10.9. You need to install it yourself, for example using Homebrew.
The command to install Maven using Homebrew is
brew install maven
You can #include <cstdint>
. It's part of C++-standard since 2011.
Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.
First, some definitions:
Bar
is a TypeName in Public Class Bar
, or in Dim Foo as Bar
. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.System.Type
objects which contain a value. This value indicates a type; just like a String
would take some text or an Int
would take a number, except we are storing types instead of text or numbers. Type
objects contain the type definitions, as well as its corresponding TypeName.Second, the theory:
Foo.GetType()
returns a Type
object which contains the type for the variable Foo
. In other words, it tells you what Foo
is an instance of.GetType(Bar)
returns a Type
object which contains the type for the TypeName Bar
.In some instances, the type an object has been Cast
to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer
cast into an Object
:
Dim MyVal As Integer = 42
Dim MyObj As Object = CType(MyVal, Object)
So, is MyObj
of type Object
or of type Integer
? MyObj.GetType()
will tell you it is an Integer
.
Type Of Foo Is Bar
feature, which allows you to ascertain a variable Foo
is compatible with a TypeName Bar
. Type Of MyObj Is Integer
and Type Of MyObj Is Object
will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it.
More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarksThe test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.
Public Sub TestMethod1()
Dim MyValInt As Integer = 42
Dim MyValDble As Double = CType(MyValInt, Double)
Dim MyObj As Object = CType(MyValDble, Object)
Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
Debug.Print(MyObj.GetType.ToString) 'Returns System.Double
Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False
Debug.Print(TypeOf MyObj Is Integer) 'Returns False
Debug.Print(TypeOf MyObj Is Double) '# Returns True
Debug.Print(TypeOf MyObj Is Object) '# Returns True
End Sub
EDIT
You can also use Information.TypeName(Object)
to get the TypeName of a given object. For example,
Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"
Here's an updated example that is using NSURLConnection +sendAsynchronousRequest: (10.7+, iOS 5+), The "Post" request remains the same as with the accepted answer and is omitted here for the sake of clarity:
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:@"http://www.myserver.com/api/api.php?request=%@", @"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(@"%@", responseString);
}
}
}];
I feel that one of the mentioned cons for "Handlebars" isnt' really valid anymore.
Handlebars.java now allows us to share the same template languages for both client and server which is a big win for large projects with 1000+ components that require serverside rendering for SEO
Take a look at https://github.com/jknack/handlebars.java
You can also write a custom query using @Query
@Query(value = "from EntityClassTable t where yourDate BETWEEN :startDate AND :endDate")
public List<EntityClassTable> getAllBetweenDates(@Param("startDate")Date startDate,@Param("endDate")Date endDate);
So I have put together a very rough modal in jsfiddle for you to take hints from.
$("#pop").on("click", function(e) {
// e.preventDefault() this is stopping the redirect to the image its self
e.preventDefault();
// #the-modal is the img tag that I use as the modal.
$('#the-modal').modal('toggle');
});
The part that you are missing is the hidden modal that you want to display when the link is clicked. In the example I used a second image as the modal and added the Bootstap classes.
One thing to note, if you are using a freestyle job, you won't be able to access build parameters or the Jenkins JVM's environment UNLESS you are using System Groovy Script build steps. I spent hours googling and researching before gathering enough clues to figure that out.
Everytime I install node.js it needs a reboot and then the path is recognized.
Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:
-Xmx512m -ea -Djava.awt.headless=true
I want to add 2 points that I learned:
Refs:
Try this out:
$url = 'http://techcrunch.com/startups/'; $url = str_replace(array('http://', 'https://'), '', $url);
EDIT:
Or, a simple way to always remove the protocol:
$url = 'https://www.google.com/'; $url = preg_replace('@^.+?\:\/\/@', '', $url);
A TCP/IP connection is always made to an IP address (you can think of an IP-address as the address of a certain computer, even if that is not always the case) and a specific (logical, not physical) port on that address.
Usually one port is coupled to a specific process or "service" on the target computer. Some port numbers are standardized, like 80 for http, 25 for smtp and so on. Because of that standardization you usually don't need to put port numbers into your web adresses.
So if you say something like http://www.stackoverflow.com, the part "stackoverflow.com" resolves to an IP address (in my case 64.34.119.12) and because my browser knows the standard it tries to connect to port 80 on that address. Thus this is the same as http://www.stackoverflow.com:80.
But there is nothing that stops a process to listen for http requests on another port, like 12434, 4711 or 8080. Usually (as in your case) this is used for debugging purposes to not intermingle with another process (like IIS) already listening to port 80 on the same machine.
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
Here's a succinct and generic solution to use a seaborn color palette.
First find a color palette you like and optionally visualize it:
sns.palplot(sns.color_palette("Set2", 8))
Then you can use it with matplotlib
doing this:
# Unique category labels: 'D', 'F', 'G', ...
color_labels = df['color'].unique()
# List of RGB triplets
rgb_values = sns.color_palette("Set2", 8)
# Map label to RGB
color_map = dict(zip(color_labels, rgb_values))
# Finally use the mapped values
plt.scatter(df['carat'], df['price'], c=df['color'].map(color_map))
Have a look at GitHub - gspread.
I found it to be very easy to use and since you can retrieve a whole column by
first_col = worksheet.col_values(1)
and a whole row by
second_row = worksheet.row_values(2)
you can more or less build some basic select ...
where ... = ...
easily.
I don't recall the exact syntax, but you may set the table column to be case insensitive. But be careful because then you won't be able to match based on case anymore and if you WANT 'cool' to not match 'CoOl' it will no longer be possible.
You might be able to resize the image with canvas
and export it using dataURI. Not sure about compression, though.
Take a look at this: Resizing an image in an HTML5 canvas
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
You can use video js library for easily play HLS video's. It allows to directly play videos
<!-- CSS -->
<link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">
<!-- HTML -->
<video id='hls-example' class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>
<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>
<script>
var player = videojs('hls-example');
player.play();
</script>
http://developer.android.com/google/play-services/setup.html
Quoting docs
If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.
Needs Emulator of Google API"S
See the target in the snap
Snap
I prefer testing on a real device which has google play services installed
You can just check the variable directly. If not defined it will return a falsy value.
var string = "?z=z";
if (page_name) { string += "&page_name=" + page_name; }
if (table_name) { string += "&table_name=" + table_name; }
if (optionResult) { string += "&optionResult=" + optionResult; }
I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.
I think that some pretty common limitations for subject lines in general (not just e-mail) are:
Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.
Hope this helps!
srand
doesn't return anything so you can't initialize a
with its return value because, well, because it doesn't return a value. Did you mean to call rand
as well?
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
If you want move placeholder text right and leave the cursor on the blank space you need to add space(s) at the start of the placeholder attribute:
<input type="email" placeholder=" Your email" />
There are multiple problems here
Ex
$(document).ready(function(){
$("#addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click', '#remCF', function(){
$(this).parent().parent().remove();
});
});
Demo: Fiddle
See this demo where id properties are removed.
$(document).ready(function(){
$("#addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click', '.remCF', function(){
$(this).parent().parent().remove();
});
});
One has to ask what the point of using short tags is.
Quicker to type
MDCore said:
<?=
is far more convenient than typing<?php echo
Yes, it is. You save having to type 7 characters * X times throughout your scripts.
However, when a script takes an hour, or 10 hours, or more, to design, develop, and write, how relevant is the few seconds of time not typing those 7 chars here and there for the duration of the script?
Compared to the potential for some core, or all, of you scripts not working if short tags are not turned on, or are on but an update or someone changing the ini file/server config stops them working, other potentials.
The small benefit you gain doesn't comes close to outweighing the severity of the potential problems, that is your site not working, or worse, only parts of it not working and thus a headache to resolve.
Easier to read
This depends on familiarity.
I've always seen and used <?php echo
. So while <?=
is not hard to read, it's not familiar to me and thus not easier to read.
And with front end/back end developer split (as with most companies) would a front end developer working on those templates be more familiar knowing <?=
is equal to "PHP open tag and echo"?
I would say most would be more comfortable with the more logical one. That is, a clear PHP open tag and then what is happening "echo" - <?php echo
.
Risk assessment
Issue = entire site or core scripts fail to work;
The potential of issue is very low + severity of outcome is very high = high risk
Conclusion
You save a few seconds here and there not having to type a few chars, but risk a lot for it, and also likely lose readability as a result.
Front or back end coders familiar with <?=
are more likely to understand <?php echo
, as they're standard PHP things - standard <?php
open tag and very well known "echo".
(Even front end coders should know "echo" or they simply wont be working on any code served by a framework).
Whereas the reverse is not as likely, someone is not likely to logically deduce that the equals sign on a PHP short tag is "echo".
What, hang on?! ... Okay ya, maybe this makes more sense to someones else too.
[nodejs 7 mind you]
fs = import('fs');
let dirCont = fs.readdirSync( dir );
let files = dirCont.filter( function( elm ) {return elm.match(/.*\.(htm?html)/ig);});
Do whatever with regex make it an argument you set in the function with a default etc.
Use Predefined Character Ranges
echo $words= preg_replace('/[[:digit:]]/','', $words);
After using pngcheck and resave all my image files to *.png, the problem still.
Finally, I found the issue is about *.9.png files. Open and check all your 9-Patch files, make sure that all files have black lines as below, if don't have, just click the white place and add it, then save it.
CHAR takes up less storage space than VARCHAR if all your data values in that field are the same length. Now perhaps in 2009 a 800GB database is the same for all intents and purposes as a 810GB if you converted the VARCHARs to CHARs, but for short strings (1 or 2 characters), CHAR is still a industry "best practice" I would say.
Now if you look at the wide variety of data types most databases provide even for integers alone (bit, tiny, int, bigint), there ARE reasons to choose one over the other. Simply choosing bigint every time is actually being a bit ignorant of the purposes and uses of the field. If a field simply represents a persons age in years, a bigint is overkill. Now it's not necessarily "wrong", but it's not efficient.
But its an interesting argument, and as databases improve over time, it could be argued CHAR vs VARCHAR does get less relevant.
Here's the calling order:
app.config()
app.run()
app.controller()
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
From Angular's module docs:
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One situation where run blocks are used is during authentications.
You should use Java's built in serialization mechanism. To use it, you need to do the following:
Declare the Club
class as implementing Serializable
:
public class Club implements Serializable {
...
}
This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.
To write your list to a file do the following:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(clubs);
oos.close();
To read the list from a file, do the following:
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
List<Club> clubs = (List<Club>) ois.readObject();
ois.close();
Your second DELETE
query was nearly correct. Just be sure to put the table name (or an alias) between DELETE
and FROM
to specify which table you are deleting from. This is simpler than using a nested SELECT
statement like in the other answers.
DELETE tableA
FROM tableA
INNER JOIN tableB u on (u.qlabel = tableA.entityrole AND u.fieldnum = tableA.fieldnum)
WHERE (LENGTH(tableA.memotext) NOT IN (8,9,10)
OR tableA.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
DELETE q
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
More examples here:
How to Delete using INNER JOIN with SQL Server?
Constructors are not inherited. They are called implicitly or explicitly by the child constructor.
The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
public:
explicit B(int x) : A(x) { }
};
UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.
Plese try this:
var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;
if (sizeInKB >= sizeLimit) {
alert("Max file size 30KB");
return false;
}
FileUtils
is class from apache org.apache.commons.io
package, you need to download org.apache.commons.io.jar
and then configure that jar
file in your class path.
I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.
That means:
then link the two together:
public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException
{
FileReader fr = null;
try {
fr = new FileReader(source);
XMLReader reader = new NamespaceFilterXMLReader();
InputSource is = new InputSource(fr);
SAXSource ss = new SAXSource(reader, is);
return unmarshaller.unmarshal(ss);
} catch (SAXException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} catch (ParserConfigurationException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} finally {
FileUtil.close(fr); //replace with this some safe close method you have
}
}
C++ has a builtin regex library since TR1. AFAIK Boost's regex library is very compatible with it and can be used as a replacement, if your standard library doesn't provide TR1.
If you don't mind the slashes being switched, you could [ab]use Uri
:
Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
Uri folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}
How about using readlink
?
# if symlink, readlink returns not empty string (the symlink target)
# if string is not empty, test exits w/ 0 (normal)
#
# if non symlink, readlink returns empty string
# if string is empty, test exits w/ 1 (error)
simlink? () {
test "$(readlink "${1}")";
}
FILE=/usr/mda
if simlink? "${FILE}"; then
echo $FILE is a symlink
else
echo $FILE is not a symlink
fi
Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson()
method.
For example:
class Response {
Map<String, App> descriptor;
// standard getters & setters...
}
class App {
String name;
int age;
String[] messages;
// standard getters & setters...
}
Then just use:
Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);
Where yourJson
can be a String
, any Reader
, a JsonReader
or a JsonElement
.
Finally, if you want to access any particular field, you just have to do:
String name = response.getDescriptor().get("app3").getName();
You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.
Here's a macro that allows you to shuffle selected cells in a column:
Option Explicit
Sub ShuffleSelectedCells()
'Do nothing if selecting only one cell
If Selection.Cells.Count = 1 Then Exit Sub
'Save selected cells to array
Dim CellData() As Variant
CellData = Selection.Value
'Shuffle the array
ShuffleArrayInPlace CellData
'Output array to spreadsheet
Selection.Value = CellData
End Sub
Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim J As Long, _
N As Long, _
Temp As Variant
'Randomize
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
If J <> N Then
Temp = InArray(N, 1)
InArray(N, 1) = InArray(J, 1)
InArray(J, 1) = Temp
End If
Next N
End Sub
You can read the comments to see what the macro is doing. Here's how to install the macro:
Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).
Not portable, Zsh only, but pretty concise.
First, make sure zmv
is loaded.
autoload -U zmv
Also, make sure extendedglob
is on:
setopt extendedglob
Then use:
zmv '(**/)(*)~CVS~**/CVS' '${1}${(L)2}'
To recursively lowercase files and directories where the name is not CVS.
$ svn log | head -10
on whatever directory that has a .svn
folder
You have two syntax options:
Option 1
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
CREATE TABLE Table2 (
id int identity(1, 1) not null,
LongIntColumn2 int,
CurrencyColumn2 money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
Option 2
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1
Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).
USE LIMIT 1 - so It will return only 1 row. Example
customerId- (select id from enumeration where enumerations.name = 'Ready To Invoice' limit 1)
$percentage = 50;
$totalWidth = 350;
$new_width = ($percentage / 100) * $totalWidth;
You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
A slightly shorter version using reduce
:
things.stream()
.map(this::resolve)
.reduce(Optional.empty(), (a, b) -> a.isPresent() ? a : b );
You could also move the reduce function to a static utility method and then it becomes:
.reduce(Optional.empty(), Util::firstPresent );
In Python you may use the in
operator. You can do stuff like this:
>>> "c" in "abc"
True
Taking this further, you can check for complex structures, like tuples:
>>> (2, 4, 8) in ((1, 2, 3), (2, 4, 8))
True
Here is an alternate approach. It is more intuitive.
One key aspect I feel some of the answers did not take into account, which I point out for posterity, is apply() lets you do row calculations easily, but only for matrix (all numeric) data
operations on columns are possible still for dataframes:
as.data.frame(lapply(df, myFunctionForColumn()))
To operate on rows, we make the transpose first.
tdf<-as.data.frame(t(df))
as.data.frame(lapply(tdf, myFunctionForRow()))
The downside is that I believe R will make a copy of your data table. Which could be a memory issue. (This is truly sad, because it is programmatically simple for tdf to just be an iterator to the original df, thus saving memory, but R does not allow pointer or iterator referencing.)
Also, a related question, is how to operate on each individual cell in a dataframe.
newdf <- as.data.frame(lapply(df, function(x) {sapply(x, myFunctionForEachCell()}))
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci.certificateStatus = "TRUE";
break;
default:
dataToSend.naci.certificateStatus = "";
}
}
And because dataToSend.naci
cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci!.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci!.certificateStatus = "TRUE";
break;
default:
dataToSend.naci!.certificateStatus = "";
}
}
you have to do like this...
if not "A%1" == "A"
if the input argument %1 is null, your code will have problem.
Looking for the possibility to put a powershell script into a batch file, I found this thread. The idea of walid2mi did not worked 100% for my script. But via a temporary file, containing the script it worked out. Here is the skeleton of the batch file:
;@echo off
;setlocal ENABLEEXTENSIONS
;rem make from X.bat a X.ps1 by removing all lines starting with ';'
;Findstr -rbv "^[;]" %0 > %~dpn0.ps1
;powershell -ExecutionPolicy Unrestricted -File %~dpn0.ps1 %*
;del %~dpn0.ps1
;endlocal
;goto :EOF
;rem Here start your power shell script.
param(
,[switch]$help
)
If need swap first and last elements only:
array.unshift( array.pop() );
This comes a little close.
.box
{
-webkit-box-shadow: inset -1px 10px 5px -3px #000000;
box-shadow: inset -1px 10px 5px -3px #000000;
}
preg_match_all(/<pre>([^>]*?)<\/pre>/,$content,$matches)
this regex will select everyting between tag. no matter is it in new line(work with multiline.
In case it helps someone else, I was able to convert to an array by doing something like this,
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...or you should be able to get the length
((JSONArray) myJsonArray).toArray().length
In fact to stopping the service we must use the method stopService()
and you are doing in right way:
Start service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);
Stop service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);
if you call stopService()
, then the method onDestroy()
in the service is called (NOT the stopService()
method):
@Override
public void onDestroy() {
timer.cancel();
task.cancel();
Log.i(TAG, "onCreate() , service stopped...");
}
you must implement the onDestroy()
method!.
Here is a complete example including how to start/stop the service.
This worked for me to return an array of strings from my config:
var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
.Get<string[]>();
My configuration section looks like this:
"AppSettings": {
"CORS-Settings": {
"Allow-Origins": [ "http://localhost:8000" ],
"Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
}
}
If you are using Windows.Data.Xml.Dom.XmlDocument
version of XmlDocument
(used in UWP apps for example), you can use yourXmlDocument.GetXml()
to get the XML as a string.
Screenshot:
Using BoxShadow
(more customizations):
Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Colors.teal,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.red,
blurRadius: 4,
offset: Offset(4, 8), // Shadow position
),
],
),
)
Using PhysicalModel
:
PhysicalModel(
color: Colors.teal,
elevation: 8,
shadowColor: Colors.red,
borderRadius: BorderRadius.circular(20),
child: SizedBox(width: 100, height: 100),
)
This Worked For me => adding agent and 'rejectUnauthorized' set to false
const https = require('https'); //Add This_x000D_
const bindingGridData = async () => {_x000D_
const url = `your URL-Here`;_x000D_
const request = new Request(url, {_x000D_
method: 'GET',_x000D_
headers: new Headers({_x000D_
Authorization: `Your Token If Any`,_x000D_
'Content-Type': 'application/json',_x000D_
}),_x000D_
//Add The Below_x000D_
agent: new https.Agent({_x000D_
rejectUnauthorized: false,_x000D_
}),_x000D_
});_x000D_
return await fetch(request)_x000D_
.then((response: any) => {_x000D_
return response.json();_x000D_
})_x000D_
.then((response: any) => {_x000D_
console.log('response is', response);_x000D_
return response;_x000D_
})_x000D_
.catch((err: any) => {_x000D_
console.log('This is Error', err);_x000D_
return;_x000D_
});_x000D_
};
_x000D_
In my case I had not enabled the site 'default-ssl'. Only '000-default' was listed in the /etc/apache2/sites-enabled
folder.
Enable SSL site on Ubuntu 14 LTS, Apache 2.4.7:
a2ensite default-ssl
service apache2 reload
Do not use list as variable name. You can take a look at the following code too:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
Or in-place editing:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
From iOS 6 and later UITextAlignment
is deprecated. use NSTextAlignment
myLabel.textAlignment = NSTextAlignmentCenter;
Swift Version from iOS 6 and later
myLabel.textAlignment = .center
If you are using MinGW, the problem is that by default, MinGW uses the I/O resp. formatting functions from the Microsoft C runtime, which doesn't support 80 bit floating point numbers (long double
== double
in Microsoft land).
However, MinGW also comes with a set of alternative implementations that do properly support long doubles. To use them, prefix the function names with __mingw_
(e.g. __mingw_printf
). Depending on the nature of your project, you might also want to globally #define printf __mingw_printf
or use -D__USE_MINGW_ANSI_STDIO
(which enables the MinGW versions of all the printf
-family functions).
In the Terminal, type:
$ curl -V
That's a capital V
for the version
Set style= "display:none;"
. By setting visible=false
, it will not render button in the browser. Thus,client side script wont execute.
<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />
html markup should be
<button id="btnsave" onclick="fncsave()">Save</button>
Change javascript to
<script type="text/javascript">
function fncsave()
{
document.getElementById('<%= savebtn.ClientID %>').click();
}
</script>
You have to check if the argument is undefined:
function func(a, b) {
if (a === undefined) a = "default value";
if (b === undefined) b = "default value";
}
Problem comes from the fact that line breaks (\n\r
?) are not the same as HTML <br/>
tags
var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '<br />');
UPDATE
Since many of the comments and my own experience have show me that this <br>
solution is not working as expected here is an example of how to append a new line to a textarea
using '\r\n'
function log(text) {
var txtArea ;
txtArea = document.getElementById("txtDebug") ;
txtArea.value += text + '\r\n';
}
I decided to do this an edit, and not as a new question because this a far too popular answer to be wrong or incomplete.
open a terminal and run this command xhost +
. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands
Also make sure in your /etc/environment file there is a line
export DISPLAY=:0.0
And then, run your tests to see if your issue is resolved.
All please note the comment from sardathrion below before using this.
This is another simpler solution to your question
pd.read_json(data)
where data is the str output from the following code
response = urlopen("https://data.nasa.gov/resource/y77d-th95.json")
json_data = response.read().decode('utf-8', 'replace')
The most important thing here is consistency. That said, I follow the GTK+ coding convention, which can be summarized as follows:
MAX_BUFFER_SIZE
, TRACKING_ID_PREFIX
.GtkWidget
, TrackingOrder
.gtk_widget_show()
, tracking_order_process()
.GtkWidget *foo
, TrackingOrder *bar
._refrobnicate_data_tables()
, _destroy_cache()
.I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
As long as you don't need to support versions of Internet Explorer earlier than IE8, you can use display: table-cell
to accomplish this:
HTML:
<div class="outer">
<div class="inner">
<p>Menu or Whatever</p>
</div>
<div class="inner">
<p>Page contents...</p>
</div>
</div>
CSS:
.inner {
display: table-cell;
}
This will force each element with the .inner
class to occupy the full height of its parent element.
here is my custom function
function reverse_substring(str,from,to){
var temp="";
var i=0;
var pos = 0;
var append;
for(i=str.length-1;i>=0;i--){
//alert("inside loop " + str[i]);
if(pos == from){
append=true;
}
if(pos == to){
append=false;
break;
}
if(append){
temp = str[i] + temp;
}
pos++;
}
alert("bottom loop " + temp);
}
var str = "bala_123";
reverse_substring(str,0,3);
This function works for reverse index.
As already said by Jordão, just negate it:
if (!(id in tutorTimes)) { ... }
Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes
returns true because it is defined in Object.prototype.
If you want to test if a property doesn't exist in the current object, use hasOwnProperty:
if (!tutorTimes.hasOwnProperty(id)) { ... }
Or if you might have a key that is hasOwnPropery you can use this:
if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }
From here:
One way to conserve system resources is to configure idle time-out settings for the worker processes in an application pool. When these settings are configured, a worker process will shut down after a specified period of inactivity. The default value for idle time-out is 20 minutes.
Also check Why is the IIS default app pool recycle set to 1740 minutes?
If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.
When you write the following line of code in TypeScript:
var SUCSS = {};
The type of SUCSS
is inferred from the assignment (i.e. it is an empty object type).
You then go on to add a property to this type a few lines later:
SUCSS.fadeDiv = //...
And the compiler warns you that there is no property named fadeDiv
on the SUCSS
object (this kind of warning often helps you to catch a typo).
You can either... fix it by specifying the type of SUCSS
(although this will prevent you from assigning {}
, which doesn't satisfy the type you want):
var SUCSS : {fadeDiv: () => void;};
Or by assigning the full value in the first place and let TypeScript infer the types:
var SUCSS = {
fadeDiv: function () {
// Simplified version
alert('Called my func');
}
};
You can use operator Contains
,
private void ContainColumn(string columnName, DataTable table)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
....
}
}
Be Careful: If your app is targeting iPhone device only, iPad running with iphone compatible mode will return false for below statement:
#define IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
The right way to detect physical iPad device is:
#define IS_IPAD_DEVICE ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"])
Use the pandas.DataFrame.astype(<type>)
function to manipulate column dtypes.
>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
A B C D
0 0.542447 0.949988 0.669239 0.879887
1 0.068542 0.757775 0.891903 0.384542
2 0.021274 0.587504 0.180426 0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
A B C D
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
EDIT:
To handle missing values:
>>> df
A B C D
0 0.475103 0.355453 0.66 0.869336
1 0.260395 0.200287 NaN 0.617024
2 0.517692 0.735613 0.18 0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
A B C D
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
There isn't any need to write this much. Just put your desired field separator with the -F
option in the AWK command and the column number you want to print segregated as per your mentioned field separator.
echo "1: " | awk -F: '{print $1}'
1
echo "1#2" | awk -F# '{print $1}'
1
Use this CSS (jsFiddle example):
input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
color: green
}
You have to write the most outer element on the left and the most inner element on the right.
.btn:hover input:disabled
would select any disabled input elements contained in an element with a class btn
which is currently hovered by the user.
I would prefer :disabled
over [disabled]
, see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?
By the way, Laravel (PHP) generates the HTML - not the browser.
You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.
Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html
simply try this 'listBox' is your list and 'yu' is a veriable to which the value on index 0 will be assigned
string yu = listBox1.Items[0].ToString();
MessageBox.Show(yu);
If you don't want to change your default settings, and you only want to change the width of the current notebook you're working on, you can enter the following into a cell:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError as e:
return False
return True
Which prints:
print is_json("{}") #prints True
print is_json("{asdf}") #prints False
print is_json('{ "age":100}') #prints True
print is_json("{'age':100 }") #prints False
print is_json("{\"age\":100 }") #prints True
print is_json('{"age":100 }') #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
Convert a JSON string to a Python dictionary:
import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo']) #prints bar
mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]
Convert a python object to JSON string:
foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo)) #prints {"gummy": "bear"}
If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/
Great tutorial on python JSON module: https://pymotw.com/2/json/
sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json
Prints:
, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.
json_xs
is capable of syntax checking, parsing, prittifying, encoding, decoding and more:
You can get the ID, or any other attribute, using jQuery's attrib function.
$('ul.art-vmenu li').attrib('id');
To get the menu text, which is in the t span, you can do this:
$('ul.art-vmenu li').children('span.t').html();
To change the HTML is just as easy:
$('ul.art-vmenu li').children('span.t').html("I'm different");
Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:
$('ul.art-vemnu li span.t').html();
But I'm assuming you've already got the li's, and want to use child() to find something within that element.
Microsoft's answer to backing up all user databases on SQL Express is here:
The process is: copy, paste, and execute their code (see below. I've commented some oddly non-commented lines at the top) as a query on your database server. That means you should first install the SQL Server Management Studio (or otherwise connect to your database server with SSMS). This code execution will create a stored procedure on your database server.
Create a batch file to execute the stored procedure, then use Task Scheduler to schedule a periodic (e.g. nightly) run of this batch file. My code (that works) is a slightly modified version of their first example:
sqlcmd -S .\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='E:\SQLBackups\', @backupType='F'"
This worked for me, and I like it. Each time you run it, new backup files are created. You'll need to devise a method of deleting old backup files on a routine basis. I already have a routine that does that sort of thing, so I'll keep a couple of days' worth of backups on disk (long enough for them to get backed up by my normal backup routine), then I'll delete them. In other words, I'll always have a few days' worth of backups on hand without having to restore from my backup system.
I'll paste Microsoft's stored procedure creation script below:
--// Copyright © Microsoft Corporation. All Rights Reserved.
--// This code released under the terms of the
--// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Microsoft
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================
CREATE PROCEDURE [dbo].[sp_BackupDatabases]
@databaseName sysname = null,
@backupType CHAR(1),
@backupLocation nvarchar(200)
AS
SET NOCOUNT ON;
DECLARE @DBs TABLE
(
ID int IDENTITY PRIMARY KEY,
DBNAME nvarchar(500)
)
-- Pick out only databases which are online in case ALL databases are chosen to be backed up
-- If specific database is chosen to be backed up only pick that out from @DBs
INSERT INTO @DBs (DBNAME)
SELECT Name FROM master.sys.databases
where state=0
AND name=@DatabaseName
OR @DatabaseName IS NULL
ORDER BY Name
-- Filter out databases which do not need to backed up
IF @backupType='F'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
END
ELSE IF @backupType='D'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE IF @backupType='L'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE
BEGIN
RETURN
END
-- Declare variables
DECLARE @BackupName varchar(100)
DECLARE @BackupFile varchar(100)
DECLARE @DBNAME varchar(300)
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @dateTime NVARCHAR(20)
DECLARE @Loop int
-- Loop through the databases one by one
SELECT @Loop = min(ID) FROM @DBs
WHILE @Loop IS NOT NULL
BEGIN
-- Database Names have to be in [dbname] format since some have - or _ in their name
SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'
-- Set the current date and time n yyyyhhmmss format
SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- Create backup filename in path\filename.extension format for full,diff and log backups
IF @backupType = 'F'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'D'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'L'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'
-- Provide the backup a name for storing in the media
IF @backupType = 'F'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
IF @backupType = 'D'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
IF @backupType = 'L'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime
-- Generate the dynamic SQL command to be executed
IF @backupType = 'F'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'D'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'L'
BEGIN
SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
-- Execute the generated SQL command
EXEC(@sqlCommand)
-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop
END?
In some cases, such as routing with a component that's wrapped with redux-form
, replacing the Route
component argument on this JSX element:
<Route path="speaker" component={Speaker}/>
With the Route
render argument like the following, will fix issue:
<Route path="speaker" render={props => <Speaker {...props} />} />
Call c_str()
to get a const char *
(LPCSTR
) from a std::string
.
It's all in the name:
LPSTR
- (long) pointer to string - char *
LPCSTR
- (long) pointer to constant string - const char *
LPWSTR
- (long) pointer to Unicode (wide) string - wchar_t *
LPCWSTR
- (long) pointer to constant Unicode (wide) string - const wchar_t *
LPTSTR
- (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPCTSTR
- (long) pointer to constant TCHAR string - const TCHAR *
You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.
You can also set up a mime type for application/JavaScript to run as PHP, .NET, Java, or whatever language you're using. I've done this for dynamic CSS files in the past.