I Get the same message, when using Intel XHAM emulator (instead of ARM) and have "Use Host GPU" option enabled. I belive when you disable it, it goes away.
" In computer networking, a network host, Internet host, host, or Internet node is a computer connected to the Internet - or more generically - to any type of data network. A network host can host information resources as well as application software for providing network services. "-Wikipedia
Local host is a special name given to the local machine or that you are working on, ussually its IP Address is 127.0.0.1. However you can define it to be anything.
There are multiple Network services running on each host for example Apache/IIS( Http Web Server),Mail Clients, FTP clients etc. Each service has a specific port associated with it. You can think of it as this.
In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
Warning!
This is a list of random books of diverse quality. In the view of some people (with some justification), it is no longer a list of recommended books. Some of the listed books contain blatantly incorrect statements or teach wrong/harmful practices. People who are aware of such books can edit this answer to help improve it. See The C book list has gone haywire. What to do with it?, and also Deleted question audit 2018.
The C Programming Language (2nd Edition) - Brian W. Kernighan and Dennis M. Ritchie (1988). Still a good, short but complete introduction to C (C90, not C99 or later versions), written by the inventor of C. However, the language has changed and good C style has developed in the last 25 years, and there are parts of the book that show its age.
C: A Reference Manual (5th Edition) - Samuel P. Harbison and Guy R. Steele (2002). An excellent reference book on C, up to and including C99. It is not a tutorial, and probably unfit for beginners. It's great if you need to write a compiler for C, as the authors had to do when they started.
C Pocket Reference (O'Reilly) - Peter Prinz and Ulla Kirch-Prinz (2002).
The comp.lang.c FAQ - Steve Summit. Web site with answers to many questions about C.
Various versions of the C language standards can be found here. There is an online version of the draft C11 standard.
The new C standard - an annotated reference (Free PDF) - Derek M. Jones (2009). The "new standard" referred to is the old C99 standard rather than C11.
C Programming: A Modern Approach (2nd Edition) - K. N. King (2008). A good book for learning C.
Programming in C (4th Edition) - Stephen Kochan (2014). A good general introduction and tutorial.
C Primer Plus (5th Edition) - Stephen Prata (2004)
A Book on C - Al Kelley/Ira Pohl (1998).
The C Book (Free Online) - Mike Banahan, Declan Brady, and Mark Doran (1991).
C: How to Program (8th Edition) - Paul Deitel and Harvey M. Deitel (2015). Lots of good tips and best practices for beginners. The index is very good and serves as a decent reference (just not fully comprehensive, and very shallow).
Head First C - David Griffiths and Dawn Griffiths (2012).
Beginning C (5th Edition) - Ivor Horton (2013). Very good explanation of pointers, using lots of small but complete programs.
Sams Teach Yourself C in 21 Days - Bradley L. Jones and Peter Aitken (2002). Very good introductory stuff.
C In Easy Steps (5th Edition) - Mike McGrath (2018). It is a good book for learning and referencing C.
Effective C - Robert C Seacord (2020). A good introduction to modern C, including chapters on dynamic memory allocation, on program structure, and on debugging, testing and analysis. It has some pointers toward probable C2x features.
Modern C — Jens Gustedt (2017 1st Edn; 2020 2nd Edn). Covers C in 5 levels (encounter, acquaintance, cognition, experience, ambition) from beginning C to advanced C. It covers C11 and C17, including threads and atomic access, which few other books do. Not all compilers recognize these features in all environments.
C Interfaces and Implementations - David R. Hanson (1997). Provides information on how to define a boundary between an interface and implementation in C in a generic and reusable fashion. It also demonstrates this principle by applying it to the implementation of common mechanisms and data structures in C, such as lists, sets, exceptions, string manipulation, memory allocators, and more. Basically, Hanson took all the code he'd written as part of building Icon and lcc and pulled out the best bits in a form that other people could reuse for their own projects. It's a model of good C programming using modern design techniques (including Liskov's data abstraction), showing how to organize a big C project as a bunch of useful libraries.
The C Puzzle Book - Alan R. Feuer (1998)
The Standard C Library - P.J. Plauger (1992). It contains the complete source code to an implementation of the C89 standard library, along with extensive discussions about the design and why the code is designed as shown.
21st Century C: C Tips from the New School - Ben Klemens (2012). In addition to the C language, the book explains gdb, valgrind, autotools, and git. The comments on style are found in the last part (Chapter 6 and beyond).
Algorithms in C - Robert Sedgewick (1997). Gives you a real grasp of implementing algorithms in C. Very lucid and clear; will probably make you want to throw away all of your other algorithms books and keep this one.
Problem Solving and Program Design in C (6th Edition) - Jeri R. Hanly and Elliot B. Koffman (2009).
Data Structures - An Advanced Approach Using C - Jeffrey Esakov and Tom Weiss (1989).
C Unleashed - Richard Heathfield, Lawrence Kirby, et al. (2000). Not ideal, but it is worth intermediate programmers practicing problems written in this book. This is a good cookbook-like approach suggested by comp.lang.c contributors.
Expert C Programming: Deep C Secrets - Peter van der Linden (1994). Lots of interesting information and war stories from the Sun compiler team, but a little dated in places.
Advanced C Programming by Example - John W. Perry (1998).
Advanced Programming in the UNIX Environment - Richard W. Stevens and Stephen A. Rago (2013). Comprehensive description of how to use the Unix APIs from C code, but not so much about the mechanics of C coding.
Essential C (Free PDF) - Nick Parlante (2003). Note that this describes the C90 language at several points (e.g., in discussing //
comments and placement of variable declarations at arbitrary points in the code), so it should be treated with some caution.
C Programming FAQs: Frequently Asked Questions - Steve Summit (1995). This is the book of the web site listed earlier. It doesn't cover C99 or the later standards.
C in a Nutshell - Peter Prinz and Tony Crawford (2005). Excellent book if you need a reference for C99.
Functional C - Pieter Hartel and Henk Muller (1997). Teaches modern practices that are invaluable for low-level programming, with concurrency and modularity in mind.
The Practice of Programming - Brian W. Kernighan and Rob Pike (1999). A very good book to accompany K&R. It uses C++ and Java too.
C Traps and Pitfalls by A. Koenig (1989). Very good, but the C style pre-dates standard C, which makes it less recommendable these days.
Some have argued for the removal of 'Traps and Pitfalls' from this list because it has trapped some people into making mistakes; others continue to argue for its inclusion. Perhaps it should be regarded as an 'expert' book because it requires a moderately extensive knowledge of C to understand what's changed since it was published.
MISRA-C - industry standard published and maintained by the Motor Industry Software Reliability Association. Covers C89 and C99.
Although this isn't a book as such, many programmers recommend reading and implementing as much of it as possible. MISRA-C was originally intended as guidelines for safety-critical applications in particular, but it applies to any area of application where stable, bug-free C code is desired (who doesn't want fewer bugs?). MISRA-C is becoming the de facto standard in the whole embedded industry and is getting increasingly popular even in other programming branches. There are (at least) three publications of the standard (1998, 2004, and the current version from 2012). There is also a MISRA Compliance Guidelines document from 2016, and MISRA C:2012 Amendment 1 — Additional Security Guidelines for MISRA C:2012 (published in April 2016).
Note that some of the strictures in the MISRA rules are not appropriate to every context. For example, directive 4.12 states "Dynamic memory allocation shall not be used". This is appropriate in the embedded systems for which the MISRA rules are designed; it is not appropriate everywhere. (Compilers, for instance, generally use dynamic memory allocation for things like symbol tables, and to do without dynamic memory allocation would be difficult, if not preposterous.)
Archived lists of ACCU-reviewed books on Beginner's C (116 titles) from 2007 and Advanced C (76 titles) from 2008. Most of these don't look to be on the main site anymore, and you can't browse that by subject anyway.
There is a list of books and tutorials to be cautious about at the ISO 9899 Wiki, which is not itself formally associated with ISO or the C standard, but contains information about the C standard (though it hails the release of ISO 9899:2011 and does not mention the release of ISO 9899:2018).
Be wary of books written by Herbert Schildt. In particular, you should stay away from C: The Complete Reference (4th Edition, 2000), known in some circles as C: The Complete Nonsense.
Also do not use the book Let Us C (16th Edition, 2017) by Yashwant Kanetkar. Many people view it as an outdated book that teaches Turbo C and has lots of obsolete, misleading and incorrect material. For example, page 137 discusses the expected output from printf("%d %d %d\n", a, ++a, a++)
and does not categorize it as undefined behaviour as it should. It also consistently promotes unportable and buggy coding practices, such as using gets
, %[\n]s
in scanf
, storing return value of getchar
in a variable of type char
or using fflush
on stdin
.
Learn C The Hard Way (2015) by Zed Shaw. A book with mixed reviews. A critique of this book by Tim Hentenaar:
To summarize my views, which are laid out below, the author presents the material in a greatly oversimplified and misleading way, the whole corpus is a bundled mess, and some of the opinions and analyses he offers are just plain wrong. I've tried to view this book through the eyes of a novice, but unfortunately I am biased by years of experience writing code in C. It's obvious to me that either the author has a flawed understanding of C, or he's deliberately oversimplifying to the point where he's actually misleading the reader (intentionally or otherwise).
"Learn C The Hard Way" is not a book that I could recommend to someone who is both learning to program and learning C. If you're already a competent programmer in some other related language, then it represents an interesting and unusual exposition on C, though I have reservations about parts of the book. Jonathan Leffler
Other contributors, not necessarily credited in the revision history, include:
Alex Lockwood,
Ben Jackson,
Bubbles,
claws,
coledot,
Dana Robinson,
Daniel Holden,
desbest,
Dervin Thunk,
dwc,
Erci Hou,
Garen,
haziz,
Johan Bezem,
Jonathan Leffler,
Joshua Partogi,
Lucas,
Lundin,
Matt K.,
mossplix,
Matthieu M.,
midor,
Nietzche-jou,
Norman Ramsey,
r3st0r3,
ridthyself,
Robert S. Barnes,
Steve Summit,
Tim Ring,
Tony Bai,
VMAtm
For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.
Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4
columns_to_overwrite = ["column_1", "column_3"]
First delete the columns that you intend to replace...
original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)
... then re-insert the columns, but using the values that you intended to overwrite
original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]
http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
You need to find the bin folder and then open a command prompt on that folder Then just type mongo.exe and press enter to start the shell
Or you can supply the full path to mongo.exe from any folder to start the shell:
c:\MongoDB\bin\mongo.exe
Then if you have multiple databases, you can do enter command >use <database_name>
to use that db
Let me know if it helps or have issues
I think you're using the wrong approach. You should set the value
attribute of your input elements. Check the docs for .val() for examples of setting and returning the .val() of input elements.
ie.
<input type="radio" runat="server" name="testGroup" value="test2" />
return $('input:radio[name=testGroup]:checked').val() == 'test2';
Maybe a better solution would be to add an extra column that is automatically set to 1 on each row. As soon as there is an element that is not null change it to a 0.
then
If(drEntitity.rows[i].coulmn[8] = 1)
{
dtEntity.Rows.Add(drEntity);
}
else
{
//don't add, will create a new one (drEntity = dtEntity.NewRow();)
}
A bit late but don't matter...
the question is "How do you use...?" short answer is you are doing it correct
&&
instead of AND
and ||
instead of OR
.
$a = 1
$b = 3
Now,
if ($a == 1 && $b == 1) { TRUE } else { FALSE }
in this case the result is "FALSE" because B is not 1, now what if
if ($a == 1 || $b == 1) { TRUE } else { FALSE }
This will return "TRUE" even if B still not the value we asking for, there is another way to return TRUE without the use of OR / || and that would be XOR
if ($a == 1 xor $b == 1) { TRUE } else { FALSE }
in this case we need only one of our variables to be true BUT NOT BOTH if both are TRUE the result would be FALSE.
I hope this helps...
more in:
http://www.php.net/manual/en/language.operators.logical.php
Hope this help
private bool isDate(Range cell)
{
if (cell.NumberFormat.ToString().Contains("/yy"))
{
return true;
}
return false;
}
isDate(worksheet.Cells[irow, icol])
If you're interested in the reasons for these rules, it's because the time it takes the earth to make exactly one orbit around the sun is a long imprecise decimal value. It's not exactly 365.25. It's slightly less than 365.25, so every 100 years, one leap day must be eliminated (365.25 - 0.01 = 365.24). But that's not exactly correct either. The value is slightly larger than 365.24. So only 3 out of 4 times will the 100 year rule apply (or in other words, add back in 1 day every 400 years; 365.25 - 0.01 + 0.0025 = 365.2425).
It can happen because of native method calling in your application. For example, in Qtjambi if you use QApplication.quit()
instead of QApplication.closeAllWindows()
for closing a Java application it generates an error log.
In this case, you can get a stack trace right to your method that called the native code and caused the crash. Just look in the log file it tells you about:
# An error report file with more information is saved as hs_err_pid24139.log.
The stack trace looks quite unusual, since it has native code mixed with VM code and your code, but each line is prefixed so you can tell which lines are your own code. There's a key at the top of the stack trace to explain the prefixes:
Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)
I faced the same problem but I successfully solved the problem by changing the version of compileSdkVersion to the latest which is 29 and change the version of targetSdkVersion to the latest which is 29.
Go to the gradile.build file and change the compilesdkversion and targetsdkversion.
I resolved this issue by excluding byte-buddy dependency from springfox
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
Simple and Easy. Remove all columns after the 22th.
df.drop(columns=df.columns[22:]) # love it
Configure the maven-compiler-plugin to use the same character encoding that your source files are encoded in (e.g):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
Many maven plugins will by default use the "project.build.sourceEncoding" property so setting this in your pom will cover most plugins.
<project>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
...
However, I prefer setting the encoding in each plugin's configuration that supports it as I like to be explicit.
When your source code is compiled by the maven-compiler-plugin your source code files are read in by the compiler plugin using whatever encoding the compiler plugin is configured with. If your source files have a different encoding than the compiler plugin is using then it is possible that some characters may not exist in both encodings.
Many people prefer to set the encoding on their source files to UTF-8 so as to avoid this problem. To do this in Eclipse you can right click on a project and select Properties->Resource->Text File Encoding and change it to UTF-8. This will encode all your source files in UTF-8. (You should also explicitly configure the maven-compiler-plugin as mentioned above to use UTF-8 encoding.) With your source files and the compiler plugin both using the same encoding you shouldn't have any more unmappable characters during compilation.
Note, You can also set the file encoding globally in eclipse through Window->Preferences->General->Workspace->Text File Encoding. You can also set the encoding per file type through Window->Preferences->General->Content Types.
You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.
Try to remove that tag:
<form id="formID" runat="server">
and of course closing tag:
</form>
This should do the job, no?
<Button Content="Test">
<Button.Background>
<ImageBrush ImageSource="folder/file.PNG"/>
</Button.Background>
</Button>
For example,
package main
import (
"flag"
"fmt"
"os"
"strconv"
)
func main() {
flag.Parse()
s := flag.Arg(0)
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
}
fmt.Println(s, i)
}
#region even and odd numbers
for (int x = 0; x <= 50; x = x + 2)
{
int y = 1;
y = y + x;
if (y < 50)
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
Console.ReadKey();
}
else
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
Console.ReadKey();
}
}
//order by desc
for (int z = 50; z >= 0; z = z - 2)
{
int w = z;
w = w - 1;
if (w > 0)
{
Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
Console.ReadKey();
}
else
{
Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
Console.ReadKey();
}
}
Use the following lines of codes and you will find the solution...
pictureBox1.ImageLocation = @"C:\Users\Desktop\mypicture.jpg";
pictureBox1.SizeMode =PictureBoxSizeMode.StretchImage;
Regexes are beatable, but if you have a string version of HTML that you don't want to inject into a DOM, they may be the best approach. You may want to put it in a loop to handle something like:
<scr<script>Ha!</script>ipt> alert(document.cookie);</script>
Here's what I did, using the jquery regex from above:
var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
while (SCRIPT_REGEX.test(text)) {
text = text.replace(SCRIPT_REGEX, "");
}
~/.gradle/gradle.properties:
mavenUser=admin
mavenPassword=admin123
build.gradle:
...
authentication(userName: mavenUser, password: mavenPassword)
$(<img />).attr('src','http://somedomain.com/image.jpg');
Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.
Let's dissect it. There are three parts:
cd
-- This is change directory command./d
-- This switch makes cd
change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0
. (%~d0
Changs active drive, cd %~p0
change the directory).%~dp0
-- This can be dissected further into three parts:
%0
-- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.%~0
-- The ~
there strips double quotes ("
) around the expanded argument.%dp0
-- The d
and p
there are modifiers of the expansion. The d
forces addition of a drive letter and the p
adds full path.If your input file is in.txt, you can use freopen to set stdin file as in.txt
freopen("in.txt","r",stdin);
if you want to do the same with your output:
freopen("out.txt","w",stdout);
this will work for std::cin (if using c++), printf, etc...
This will also help you in debugging your code in clion, vscode
Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.
String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
Facebook uses the LAMP stack, so if you want to get a career with them you're going to want to focus on that. In addition they often have C++ and/or Java listed in their requirements as well.
One of the postings includes the following requirements:
Another:
Another:
http://www.facebook.com/careers/#!/careers/department.php?dept=engineering
Also, do any other social networking sites use the same language?
Some other companys that use PHP/LAMP Stack:
Use font
property of UILabel
:
label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
or use default system font
to bold text:
label.font = UIFont.boldSystemFont(ofSize: 16.0)
You can do it programmatically:
grid0.Columns[0].Visible = true;
grid0.DataSource = dt;
grid0.DataBind();
grid0.Columns[0].Visible = false;
In this way you set the column to visible before databinding, so the column is generated. The you set the column to not visible, so it is not displayed.
This worked for me...
double num = 10025000;
new DecimalFormat("#,###.##");
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
System.out.println(df.format(num));
I've had this problem myself and I've found the great wikipedia page on the subject (in "Common rotations" paragraph:
https://en.wikipedia.org/wiki/Rotation_matrix#Ambiguities
Then I wrote the following code, super verbose in order to have a clear understanding of what is going on.
I hope that you'll find it useful to dig more in the very beautiful and clever one-liner you've posted.
To quickly test it you can copy / paste it here:
http://www.codeskulptor.org/
triangle = [[0,0],[5,0],[5,2]]
coordinates_a = triangle[0]
coordinates_b = triangle[1]
coordinates_c = triangle[2]
def rotate90ccw(coordinates):
print "Start coordinates:"
print coordinates
old_x = coordinates[0]
old_y = coordinates[1]
# Here we apply the matrix coming from Wikipedia
# for 90 ccw it looks like:
# 0,-1
# 1,0
# What does this mean?
#
# Basically this is how the calculation of the new_x and new_y is happening:
# new_x = (0)(old_x)+(-1)(old_y)
# new_y = (1)(old_x)+(0)(old_y)
#
# If you check the lonely numbers between parenthesis the Wikipedia matrix's numbers
# finally start making sense.
# All the rest is standard formula, the same behaviour will apply to other rotations, just
# remember to use the other rotation matrix values available on Wiki for 180ccw and 170ccw
new_x = -old_y
new_y = old_x
print "End coordinates:"
print [new_x, new_y]
def rotate180ccw(coordinates):
print "Start coordinates:"
print coordinates
old_x = coordinates[0]
old_y = coordinates[1]
new_x = -old_x
new_y = -old_y
print "End coordinates:"
print [new_x, new_y]
def rotate270ccw(coordinates):
print "Start coordinates:"
print coordinates
old_x = coordinates[0]
old_y = coordinates[1]
new_x = -old_x
new_y = -old_y
print "End coordinates:"
print [new_x, new_y]
print "Let's rotate point A 90 degrees ccw:"
rotate90ccw(coordinates_a)
print "Let's rotate point B 90 degrees ccw:"
rotate90ccw(coordinates_b)
print "Let's rotate point C 90 degrees ccw:"
rotate90ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 180 degrees ccw:"
rotate180ccw(coordinates_a)
print "Let's rotate point B 180 degrees ccw:"
rotate180ccw(coordinates_b)
print "Let's rotate point C 180 degrees ccw:"
rotate180ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 270 degrees ccw:"
rotate270ccw(coordinates_a)
print "Let's rotate point B 270 degrees ccw:"
rotate270ccw(coordinates_b)
print "Let's rotate point C 270 degrees ccw:"
rotate270ccw(coordinates_c)
print "=== === === === === === === === === "
I used
<p align='right'>Farhan Khan</p>
and it worked for me on Google Colaboratory. Funnily enough it does not work anywhere else?
java [ options ] -jar file.jar [ argument ... ]
and
... Non-option arguments after the class name or JAR file name are passed to the main function...
Maybe you have to put the arguments in single quotes.
The below code will replace repeating space with a single %20 character.
Example:
Input is:
Code by Hitesh Jain
Output:
Code%20by%20Hitesh%20Jain
static void Main(string[] args)
{
Console.WriteLine("Enter a string");
string str = Console.ReadLine();
string replacedStr = null;
// This loop will repalce all repeat black space in single space
for (int i = 0; i < str.Length - 1; i++)
{
if (!(Convert.ToString(str[i]) == " " &&
Convert.ToString(str[i + 1]) == " "))
{
replacedStr = replacedStr + str[i];
}
}
replacedStr = replacedStr + str[str.Length-1]; // Append last character
replacedStr = replacedStr.Replace(" ", "%20");
Console.WriteLine(replacedStr);
Console.ReadLine();
}
The RecyclerView
takes care of adding, removing, and re-ordering animations!
This simple AndroidStudio project features a RecyclerView
. take a look at the commits:
For me / had to be in a new line.
For example
create type emp_t;/
didn't work
but
create type emp_t;
/
worked.
def search(myDict, lookup):
a=[]
for key, value in myDict.items():
for v in value:
if lookup in v:
a.append(key)
a=list(set(a))
return a
if the research involves more keys maybe you should create a list with all the keys
Just use mysql's DATE function:
mysql> select DATE(mytimestamp) from foo;
Just select table and press Alt+F1,
it will show all the information about table like Column name, datatype, keys etc.
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
I'm not sure if you can turn it off, but you can change the colors of it :)
myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
background:#000;
color:#fff;
}
Then just match the colors to your "darky" design and see what happens :)
The serial communication manager library has many API and features targeted for the task you want. If the device is a USB-UART its VID/PID can be used. If the device is BT-SPP than platform specific APIs can be used. Take a look at this project for serial port programming: https://github.com/RishiGupta12/serial-communication-manager
Really the ideal way to do this is to not use pull
at all, but instead fetch
and reset
:
git fetch origin master
git reset --hard FETCH_HEAD
git clean -df
(Altering master
to whatever branch you want to be following.)
pull
is designed around merging changes together in some way, whereas reset
is designed around simply making your local copy match a specific commit.
You may want to consider slightly different options to clean
depending on your system's needs.
And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:
http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php
I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:
df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)
i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.
/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */
_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }
That works great!
// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass
{
border: 1px solid brown;
}
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
Before Mongo 3.6:
You may start mongodb with
mongod --httpinterface
And access it on
http://localhost:28017
Since version 2.6: MongoDB disables the HTTP interface by default.
Update
HTTP Interface and REST API
MongoDB 3.6 removes the deprecated HTTP interface and REST API to MongoDB.
javamonkey79 is right. But don't forget what you might want to do (e.g. try something else or notify someone) if object is not an instance of String.
String myString;
if (object instanceof String) {
myString = (String) object;
} else {
// do something else
}
BTW: If you use ClassCastException instead of Exception in your code above, you can be sure that you will catch the exception caused by casting object to String. And not any other exceptions caused by other code (e.g. NullPointerExceptions).
if you need decimals can use this
DECLARE @Num NUMERIC(18, 7) = 19.1471985
SELECT FLOOR(@Num * 10000) / 10000
Output: 19.147100 Clear: 985 Add: 00
OR use this:
SELECT SUBSTRING(CONVERT(VARCHAR, @Num), 1, CHARINDEX('.', @Num) + 4)
Output: 19.1471 Clear: 985
I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:
UPDATE FUNCTIONS A
INNER JOIN (
SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
FROM TAX BB, FUNCTIONS AA
WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
GROUP BY AA.Func_ID
) B
ON B.Func_ID = A.Func_ID
SET A.Func_TaxRef = B.MinOfTax_Code
Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:
UPDATE FUNCTIONS
INNER JOIN FUNCTIONS_TAX
ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code
However, this still doesn't work.
I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:
UPDATE FUNCTIONS
SET Func_TaxRef = DLookup(
"MinOfTax_Code",
"FUNCTIONS_TAX",
"Func_ID = '" & Func_ID & "'"
)
Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).
Good luck!
Update 1/5/2018 - over the last 9 years, my thinking has evolved considerably on this topic. I tend to live a little closer to the bleeding edge in our industry than the majority (though certainly not pushing the boundaries nearly as much as a lot of really smart people out there). I've been an architect at varying levels from application, to solution, to enterprise, at multiple companies large and small. I've come to the conclusion that the future in our technology industry is one mostly without architects. If this sounds crazy to you, wait a few years and your company will probably catch up, or your competitors who figure it out will catch up with (and pass) you. The fundamental problem is that "architecture" is nothing more or less than the sum of all the decisions that have been made about your application/solution/portfolio. So the title "architect" really means "decider". That says a lot, also by what it doesn't say. It doesn't say "builder". Creating a career path / hierarchy that implicitly tells people "building" is lower than "deciding", and "deciders" are not directly responsible (by the difference in title) for "building". People who are still hanging on to their architect title will chafe at this and protest "but I am hands-on!" Great, if you're just a builder then give up your meaningless title and stop setting yourself apart from the other builders. Companies that emphasize "all builders are deciders, and all deciders are builders" will move faster than their competitors. We use the title "engineer" for everyone, and "engineer" means deciding and building.
Original answer:
For people who have never worked in a very large organization (or have, but it was a dysfunctional one), "architect" may have left a bad taste in their mouth. However, it is not only a legitimate role, but a highly strategic one for smart companies.
When an application becomes so vast and complex that dealing with the overall technical vision and planning, and translating business needs into technical strategy becomes a full-time job, that is an application architect. Application architects also often mentor and/or lead developers, and know the code of their responsible application(s) well.
When an organization has so many applications and infrastructure inter-dependencies that it is a full-time job to ensure their alignment and strategy without being involved in the code of any of them, that is a solution architect. Solution architect can sometimes be similar to an application architect, but over a suite of especially large applications that comprise a logical solution for a business.
When an organization becomes so large that it becomes a full-time job to coordinate the high-level planning for the solution architects, and frame the terms of the business technology strategy, that role is an enterprise architect. Enterprise architects typically work at an executive level, advising the CxO office and its support functions as well as the business as a whole.
There are also infrastructure architects, information architects, and a few others, but in terms of total numbers these comprise a smaller percentage than the "big three".
Note: numerous other answers have said there is "no standard" for these titles. That is not true. Go to any Fortune 1000 company's IT department and you will find these titles used consistently.
The two most common misconceptions about "architect" are:
These misconceptions come from a lot of architects doing a pretty bad job, and organizations doing a terrible job at understanding what an architect is for. It is common to promote the top programmer into an architect role, but that is not right. They have some overlapping but not identical skillsets. The best programmer may often be, but is not always, an ideal architect. A good architect has a good understanding of many technical aspects of the IT industry; a better understanding of business needs and strategies than a developer needs to have; excellent communication skills and often some project management and business analysis skills. It is essential for architects to keep their hands dirty with code and to stay sharp technically. Good ones do.
I'm writing slider ui control to provide drag feature, this is my way to prevent content from selecting when user is dragging:
function disableSelect(event) {
event.preventDefault();
}
function startDrag(event) {
window.addEventListener('mouseup', onDragEnd);
window.addEventListener('selectstart', disableSelect);
// ... my other code
}
function onDragEnd() {
window.removeEventListener('mouseup', onDragEnd);
window.removeEventListener('selectstart', disableSelect);
// ... my other code
}
bind startDrag
on your dom:
<button onmousedown="startDrag">...</button>
If you want to statically disable text select on all element, execute the code when elements are loaded:
window.addEventListener('selectstart', function(e){ e.preventDefault(); });
For those who are still trying, this link helped me out, too; it just puts it all together:
http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx
private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);
//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;
//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}
As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:
<script type="text/javascript" language="javascript">
function post_link(data){
$('#post_form').find('#form_input').val(data);
$('#post_form').submit();
};
</script>
<form id="post_form" action="anywhere/you/want/" method="POST">
{% csrf_token %}
<input id="form_input" type="hidden" value="" name="form_input">
</form>
<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>
You can use the REST-API's "Item last modified". From the docs, it retuns something like this:
GET /api/storage/libs-release-local/org/acme?lastModified
{
"uri": "http://localhost:8081/artifactory/api/storage/libs-release-local/org/acme/foo/1.0-SNAPSHOT/foo-1.0-SNAPSHOT.pom",
"lastModified": ISO8601
}
Example:
# Figure out the URL of the last item modified in a given folder/repo combination
url=$(curl \
-H 'X-JFrog-Art-Api: XXXXXXXXXXXXXXXXXXXX' \
'http://<artifactory-base-url>/api/storage/<repo>/<folder>?lastModified' | jq -r '.uri')
# Figure out the name of the downloaded file
downloaded_filename=$(echo "${url}" | sed -e 's|[^/]*/||g')
# Download the file
curl -L -O "${url}"
The answer which suggests something like taskkill /f /im java.exe
will probably work, but if you want to kill only one java process instead of all, I can suggest doing it with the help of window titles. Expample:
start "MyProgram" "C:/Program Files/Java/jre1.8.0_201/bin/java.exe" -jar MyProgram.jar
taskkill /F /FI "WINDOWTITLE eq MyProgram" /T
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
UPDATE 3 (Sep 24 '17)
Check VBA-JSON-parser on GitHub for the latest version and examples. Import JSON.bas module into the VBA project for JSON processing.
UPDATE 2 (Oct 1 '16)
However if you do want to parse JSON on 64-bit Office with ScriptControl
, then this answer may help you to get ScriptControl
to work on 64-bit.
UPDATE (Oct 26 '15)
Note that a ScriptControl
-based approachs makes the system vulnerable in some cases, since they allows a direct access to the drives (and other stuff) for the malicious JS code via ActiveX's. Let's suppose you are parsing web server response JSON, like JsonString = "{a:(function(){(new ActiveXObject('Scripting.FileSystemObject')).CreateTextFile('C:\\Test.txt')})()}"
. After evaluating it you'll find new created file C:\Test.txt
. So JSON parsing with ScriptControl
ActiveX is not a good idea.
Trying to avoid that, I've created JSON parser based on RegEx's. Objects {}
are represented by dictionaries, that makes possible to use dictionary's properties and methods: .Count
, .Exists()
, .Item()
, .Items
, .Keys
. Arrays []
are the conventional zero-based VB arrays, so UBound()
shows the number of elements. Here is the code with some usage examples:
Option Explicit
Sub JsonTest()
Dim strJsonString As String
Dim varJson As Variant
Dim strState As String
Dim varItem As Variant
' parse JSON string to object
' root element can be the object {} or the array []
strJsonString = "{""a"":[{}, 0, ""value"", [{""stuff"":""content""}]], b:null}"
ParseJson strJsonString, varJson, strState
' checking the structure step by step
Select Case False ' if any of the checks is False, the sequence is interrupted
Case IsObject(varJson) ' if root JSON element is object {},
Case varJson.Exists("a") ' having property a,
Case IsArray(varJson("a")) ' which is array,
Case UBound(varJson("a")) >= 3 ' having not less than 4 elements,
Case IsArray(varJson("a")(3)) ' where forth element is array,
Case UBound(varJson("a")(3)) = 0 ' having the only element,
Case IsObject(varJson("a")(3)(0)) ' which is object,
Case varJson("a")(3)(0).Exists("stuff") ' having property stuff,
Case Else
MsgBox "Check the structure step by step" & vbCrLf & varJson("a")(3)(0)("stuff") ' then show the value of the last one property.
End Select
' direct access to the property if sure of structure
MsgBox "Direct access to the property" & vbCrLf & varJson.Item("a")(3)(0).Item("stuff") ' content
' traversing each element in array
For Each varItem In varJson("a")
' show the structure of the element
MsgBox "The structure of the element:" & vbCrLf & BeautifyJson(varItem)
Next
' show the full structure starting from root element
MsgBox "The full structure starting from root element:" & vbCrLf & BeautifyJson(varJson)
End Sub
Sub BeautifyTest()
' put sourse JSON string to "desktop\source.json" file
' processed JSON will be saved to "desktop\result.json" file
Dim strDesktop As String
Dim strJsonString As String
Dim varJson As Variant
Dim strState As String
Dim strResult As String
Dim lngIndent As Long
strDesktop = CreateObject("WScript.Shell").SpecialFolders.Item("Desktop")
strJsonString = ReadTextFile(strDesktop & "\source.json", -2)
ParseJson strJsonString, varJson, strState
If strState <> "Error" Then
strResult = BeautifyJson(varJson)
WriteTextFile strResult, strDesktop & "\result.json", -1
End If
CreateObject("WScript.Shell").PopUp strState, 1, , 64
End Sub
Sub ParseJson(ByVal strContent As String, varJson As Variant, strState As String)
' strContent - source JSON string
' varJson - created object or array to be returned as result
' strState - Object|Array|Error depending on processing to be returned as state
Dim objTokens As Object
Dim objRegEx As Object
Dim bMatched As Boolean
Set objTokens = CreateObject("Scripting.Dictionary")
Set objRegEx = CreateObject("VBScript.RegExp")
With objRegEx
' specification http://www.json.org/
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = """(?:\\""|[^""])*""(?=\s*(?:,|\:|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "str"
.Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)e(?:[+-])?\d+(?=\s*(?:,|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "num"
.Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)(?=\s*(?:,|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "num"
.Pattern = "\b(?:true|false|null)(?=\s*(?:,|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "cst"
.Pattern = "\b[A-Za-z_]\w*(?=\s*\:)" ' unspecified name without quotes
Tokenize objTokens, objRegEx, strContent, bMatched, "nam"
.Pattern = "\s"
strContent = .Replace(strContent, "")
.MultiLine = False
Do
bMatched = False
.Pattern = "<\d+(?:str|nam)>\:<\d+(?:str|num|obj|arr|cst)>"
Tokenize objTokens, objRegEx, strContent, bMatched, "prp"
.Pattern = "\{(?:<\d+prp>(?:,<\d+prp>)*)?\}"
Tokenize objTokens, objRegEx, strContent, bMatched, "obj"
.Pattern = "\[(?:<\d+(?:str|num|obj|arr|cst)>(?:,<\d+(?:str|num|obj|arr|cst)>)*)?\]"
Tokenize objTokens, objRegEx, strContent, bMatched, "arr"
Loop While bMatched
.Pattern = "^<\d+(?:obj|arr)>$" ' unspecified top level array
If Not (.Test(strContent) And objTokens.Exists(strContent)) Then
varJson = Null
strState = "Error"
Else
Retrieve objTokens, objRegEx, strContent, varJson
strState = IIf(IsObject(varJson), "Object", "Array")
End If
End With
End Sub
Sub Tokenize(objTokens, objRegEx, strContent, bMatched, strType)
Dim strKey As String
Dim strRes As String
Dim lngCopyIndex As Long
Dim objMatch As Object
strRes = ""
lngCopyIndex = 1
With objRegEx
For Each objMatch In .Execute(strContent)
strKey = "<" & objTokens.Count & strType & ">"
bMatched = True
With objMatch
objTokens(strKey) = .Value
strRes = strRes & Mid(strContent, lngCopyIndex, .FirstIndex - lngCopyIndex + 1) & strKey
lngCopyIndex = .FirstIndex + .Length + 1
End With
Next
strContent = strRes & Mid(strContent, lngCopyIndex, Len(strContent) - lngCopyIndex + 1)
End With
End Sub
Sub Retrieve(objTokens, objRegEx, strTokenKey, varTransfer)
Dim strContent As String
Dim strType As String
Dim objMatches As Object
Dim objMatch As Object
Dim strName As String
Dim varValue As Variant
Dim objArrayElts As Object
strType = Left(Right(strTokenKey, 4), 3)
strContent = objTokens(strTokenKey)
With objRegEx
.Global = True
Select Case strType
Case "obj"
.Pattern = "<\d+\w{3}>"
Set objMatches = .Execute(strContent)
Set varTransfer = CreateObject("Scripting.Dictionary")
For Each objMatch In objMatches
Retrieve objTokens, objRegEx, objMatch.Value, varTransfer
Next
Case "prp"
.Pattern = "<\d+\w{3}>"
Set objMatches = .Execute(strContent)
Retrieve objTokens, objRegEx, objMatches(0).Value, strName
Retrieve objTokens, objRegEx, objMatches(1).Value, varValue
If IsObject(varValue) Then
Set varTransfer(strName) = varValue
Else
varTransfer(strName) = varValue
End If
Case "arr"
.Pattern = "<\d+\w{3}>"
Set objMatches = .Execute(strContent)
Set objArrayElts = CreateObject("Scripting.Dictionary")
For Each objMatch In objMatches
Retrieve objTokens, objRegEx, objMatch.Value, varValue
If IsObject(varValue) Then
Set objArrayElts(objArrayElts.Count) = varValue
Else
objArrayElts(objArrayElts.Count) = varValue
End If
varTransfer = objArrayElts.Items
Next
Case "nam"
varTransfer = strContent
Case "str"
varTransfer = Mid(strContent, 2, Len(strContent) - 2)
varTransfer = Replace(varTransfer, "\""", """")
varTransfer = Replace(varTransfer, "\\", "\")
varTransfer = Replace(varTransfer, "\/", "/")
varTransfer = Replace(varTransfer, "\b", Chr(8))
varTransfer = Replace(varTransfer, "\f", Chr(12))
varTransfer = Replace(varTransfer, "\n", vbLf)
varTransfer = Replace(varTransfer, "\r", vbCr)
varTransfer = Replace(varTransfer, "\t", vbTab)
.Global = False
.Pattern = "\\u[0-9a-fA-F]{4}"
Do While .Test(varTransfer)
varTransfer = .Replace(varTransfer, ChrW(("&H" & Right(.Execute(varTransfer)(0).Value, 4)) * 1))
Loop
Case "num"
varTransfer = Evaluate(strContent)
Case "cst"
Select Case LCase(strContent)
Case "true"
varTransfer = True
Case "false"
varTransfer = False
Case "null"
varTransfer = Null
End Select
End Select
End With
End Sub
Function BeautifyJson(varJson As Variant) As String
Dim strResult As String
Dim lngIndent As Long
BeautifyJson = ""
lngIndent = 0
BeautyTraverse BeautifyJson, lngIndent, varJson, vbTab, 1
End Function
Sub BeautyTraverse(strResult As String, lngIndent As Long, varElement As Variant, strIndent As String, lngStep As Long)
Dim arrKeys() As Variant
Dim lngIndex As Long
Dim strTemp As String
Select Case VarType(varElement)
Case vbObject
If varElement.Count = 0 Then
strResult = strResult & "{}"
Else
strResult = strResult & "{" & vbCrLf
lngIndent = lngIndent + lngStep
arrKeys = varElement.Keys
For lngIndex = 0 To UBound(arrKeys)
strResult = strResult & String(lngIndent, strIndent) & """" & arrKeys(lngIndex) & """" & ": "
BeautyTraverse strResult, lngIndent, varElement(arrKeys(lngIndex)), strIndent, lngStep
If Not (lngIndex = UBound(arrKeys)) Then strResult = strResult & ","
strResult = strResult & vbCrLf
Next
lngIndent = lngIndent - lngStep
strResult = strResult & String(lngIndent, strIndent) & "}"
End If
Case Is >= vbArray
If UBound(varElement) = -1 Then
strResult = strResult & "[]"
Else
strResult = strResult & "[" & vbCrLf
lngIndent = lngIndent + lngStep
For lngIndex = 0 To UBound(varElement)
strResult = strResult & String(lngIndent, strIndent)
BeautyTraverse strResult, lngIndent, varElement(lngIndex), strIndent, lngStep
If Not (lngIndex = UBound(varElement)) Then strResult = strResult & ","
strResult = strResult & vbCrLf
Next
lngIndent = lngIndent - lngStep
strResult = strResult & String(lngIndent, strIndent) & "]"
End If
Case vbInteger, vbLong, vbSingle, vbDouble
strResult = strResult & varElement
Case vbNull
strResult = strResult & "Null"
Case vbBoolean
strResult = strResult & IIf(varElement, "True", "False")
Case Else
strTemp = Replace(varElement, "\""", """")
strTemp = Replace(strTemp, "\", "\\")
strTemp = Replace(strTemp, "/", "\/")
strTemp = Replace(strTemp, Chr(8), "\b")
strTemp = Replace(strTemp, Chr(12), "\f")
strTemp = Replace(strTemp, vbLf, "\n")
strTemp = Replace(strTemp, vbCr, "\r")
strTemp = Replace(strTemp, vbTab, "\t")
strResult = strResult & """" & strTemp & """"
End Select
End Sub
Function ReadTextFile(strPath As String, lngFormat As Long) As String
' lngFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 1, False, lngFormat)
ReadTextFile = ""
If Not .AtEndOfStream Then ReadTextFile = .ReadAll
.Close
End With
End Function
Sub WriteTextFile(strContent As String, strPath As String, lngFormat As Long)
With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 2, True, lngFormat)
.Write (strContent)
.Close
End With
End Sub
One more opportunity of this JSON RegEx parser is that it works on 64-bit Office, where ScriptControl isn't available.
INITIAL (May 27 '15)
Here is one more method to parse JSON in VBA, based on ScriptControl
ActiveX, without external libraries:
Sub JsonTest()
Dim Dict, Temp, Text, Keys, Items
' Converting JSON string to appropriate nested dictionaries structure
' Dictionaries have numeric keys for JSON Arrays, and string keys for JSON Objects
' Returns Nothing in case of any JSON syntax issues
Set Dict = GetJsonDict("{a:[[{stuff:'result'}]], b:''}")
' You can use For Each ... Next and For ... Next loops through keys and items
Keys = Dict.Keys
Items = Dict.Items
' Referring directly to the necessary property if sure, without any checks
MsgBox Dict("a")(0)(0)("stuff")
' Auxiliary DrillDown() function
' Drilling down the structure, sequentially checking if each level exists
Select Case False
Case DrillDown(Dict, "a", Temp, "")
Case DrillDown(Temp, 0, Temp, "")
Case DrillDown(Temp, 0, Temp, "")
Case DrillDown(Temp, "stuff", "", Text)
Case Else
' Structure is consistent, requested value found
MsgBox Text
End Select
End Sub
Function GetJsonDict(JsonString As String)
With CreateObject("ScriptControl")
.Language = "JScript"
.ExecuteStatement "function gettype(sample) {return {}.toString.call(sample).slice(8, -1)}"
.ExecuteStatement "function evaljson(json, er) {try {var sample = eval('(' + json + ')'); var type = gettype(sample); if(type != 'Array' && type != 'Object') {return er;} else {return getdict(sample);}} catch(e) {return er;}}"
.ExecuteStatement "function getdict(sample) {var type = gettype(sample); if(type != 'Array' && type != 'Object') return sample; var dict = new ActiveXObject('Scripting.Dictionary'); if(type == 'Array') {for(var key = 0; key < sample.length; key++) {dict.add(key, getdict(sample[key]));}} else {for(var key in sample) {dict.add(key, getdict(sample[key]));}} return dict;}"
Set GetJsonDict = .Run("evaljson", JsonString, Nothing)
End With
End Function
Function DrillDown(Source, Prop, Target, Value)
Select Case False
Case TypeName(Source) = "Dictionary"
Case Source.exists(Prop)
Case Else
Select Case True
Case TypeName(Source(Prop)) = "Dictionary"
Set Target = Source(Prop)
Value = Empty
Case IsObject(Source(Prop))
Set Value = Source(Prop)
Set Target = Nothing
Case Else
Value = Source(Prop)
Set Target = Nothing
End Select
DrillDown = True
Exit Function
End Select
DrillDown = False
End Function
Because userString is empty. You only declare it
vector<string> userString;
but never add anything, so the for loop won't even run.
data d is in row 0 and column 3 for value d :
DataTable table;
String d = (String)table.Rows[0][3];
Actually...
To hide an absolute positioned element, the container position
must be anything except for static
. It can be relative
or fixed
in addition to absolute
.
if you wish to using dplyr, for to remove row "Foo":
df %>%
filter(!C=="Foo")
Even if you're willing to look up what behavior your implementation defines, multi-character constants will still vary with endianness.
Better to use a (POD) struct { char[4] }; ... and then use a UDL like "WAVE"_4cc to easily construct instances of that class
Yes.
new ArrayList<String>(){{
add("A");
add("B");
}}
What this is actually doing is creating a class derived from ArrayList<String>
(the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this
pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.
I understand that Java 7 will provide additional language constructs to do precisely what you want.
EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)
You should use <span>
, because as specified by the spec, <font>
has been deprecated and probably won't display as you intend.
use tar to split into multiple archives
there are plenty of programs that will work with tar files on windows, including cygwin.
I personally found Josh's jQuery-based answer above to be the best I saw, and worked perfectly for my application... of course, I was already using jQuery... I certainly wouldn't have included the whole jQ library just for that one purpose.
Cheers!
EDIT: OK... so mere seconds after posting this, I saw another answer just below mine (not sure if still below me after an edit) that said to use:
document.getElementById('your_element_ID_here').scrollIntoView();
This works perfectly and in so much less code than the jQuery version! I had no idea that there was a built-in function in JS called .scrollIntoView(), but there it is! So, if you want the fancy animation, go jQuery. Quick n' dirty... use this one!
This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url');
The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.
The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."
Example:
if ($user_logged_in === FALSE)
{
redirect('/account/login', 'refresh');
}
Glide 4.6
1. To Load gif
GlideApp.with(context)
.load(R.raw.gif) // or url
.into(imageview);
2. To get the file object
GlideApp.with(context)
.asGif()
.load(R.raw.gif) //or url
.into(new SimpleTarget<GifDrawable>() {
@Override
public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {
resource.start();
//resource.setLoopCount(1);
imageView.setImageDrawable(resource);
}
});
It sounds like the admin has locked the "authentication" node of the web.config, which one can do in the global web.config pretty easily. Or, in a nutshell, this is working as designed.
Use any()
.
if any(t < 0 for t in x):
# do something
In VirtualBox you should add custom resolution via the command:
VBoxManage setextradata "VM name" "CustomVideoMode1" "800x480x16"
instead of editing a .vbox
file.
This solution works fine for me!
Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange
event:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim clickRng As Range
Dim lastRow As Long
lastRow = Range("A1").End(xlDown).Row
Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A
If Not Intersect(Target, clickRng) Is Nothing Then
MyUserForm.Show //Launch custom userform
End If
End Sub
Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)
Callback functions are part of the C standard, an therefore also part of C++. But if you are working with C++, I would suggest you use the observer pattern instead: http://en.wikipedia.org/wiki/Observer_pattern
Swift 4 version of 4redwings's answer:
let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8)
Since tr:not(:first-child)
is not supported by IE 6, 7, 8. You can use the help of jQuery.
You may find it here
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
void doSomething(int id) {
cout << id << "\n";
}
/**
* Spawns n threads
*/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}
for (auto& th : threads) {
th.join();
}
}
int main()
{
spawnThreads(10);
}
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:
span.add-label{
display:none;
}
.item:hover span.align{
display:none;
}
.item:hover span.add-label{
display:block;
}
Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ
You can use the window.innerWidth and window.innerHeight properties.
BUILD_NUMBER
is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.
See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.
From the relevant Git documentation:
Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the
$GIT_DIR/info/exclude
file.
The .git/info/exclude
file has the same format as any .gitignore
file. Another option is to set core.excludesFile
to the name of a file containing global patterns.
Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:
git update-index --assume-unchanged <file-list>
Note on $GIT_DIR
: This is a notation used all over the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.
Edit: Another way is to use:
git update-index --skip-worktree <file-list>
Reverse it by:
git update-index --no-skip-worktree <file-list>
No, you're creating an array, but there's a big difference:
char *string = "Some CONSTANT string";
printf("%c\n", string[1]);//prints o
string[1] = 'v';//INVALID!!
The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:
char string[] = "Some string";
creates the same, read only, constant string, and copies it to the stack array. That's why:
string[1] = 'v';
Is valid in the latter case.
If you write:
char string[] = {"some", " string"};
the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:
char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
//this is a bit silly, because it's the same as char string[] = "some string";
//or
char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
//or
char string[][10] = {"some", " string"};
Where the last version gives you an array of strings (arrays of chars) that you actually can edit...
import curses
stdscr = curses.initscr()
stdscr.clear()
Instead of having two arrays of Strings, have one array of a custom class which contains your two strings.
I think, from your description, the following would suffice:
DELETE FROM guide_category
WHERE id_guide NOT IN (SELECT id_guide FROM guide)
I assume, that there are no referential integrity constraints on the tables involved, are there?
A deferred can be used in place of a mutex. This is essentially the same as the multiple ajax usage scenarios.
MUTEX
var mutex = 2;
setTimeout(function() {
callback();
}, 800);
setTimeout(function() {
callback();
}, 500);
function callback() {
if (--mutex === 0) {
//run code
}
}
DEFERRED
function timeout(x) {
var dfd = jQuery.Deferred();
setTimeout(function() {
dfd.resolve();
}, x);
return dfd.promise();
}
jQuery.when(
timeout(800), timeout(500)).done(function() {
// run code
});
When using a Deferred as a mutex only, watch out for performance impacts (http://jsperf.com/deferred-vs-mutex/2). Though the convenience, as well as additional benefits supplied by a Deferred is well worth it, and in actual (user driven event based) usage the performance impact should not be noticeable.
Yes, it's possible. for example checkout:
<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date && match.team1.code === main.team1code && match.team2.code === main.team2code">
//Do something here
</div>
I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.
You can create dummy variables to handle the categorical data
# Creating dummy variables for categorical datatypes
trainDfDummies = pd.get_dummies(trainDf, columns=['Col1', 'Col2', 'Col3', 'Col4'])
This will drop the original columns in trainDf and append the column with dummy variables at the end of the trainDfDummies dataframe.
It automatically creates the column names by appending the values at the end of the original column name.
This is my function for the clients timezone, it's lite weight and simple
function getCurrentDateTimeMySql() {
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
var mySqlDT = localISOTime;
return mySqlDT;
}
As of today in 2019, Apple has made life much easier for low budget or one-man project developers like me. You can just use the terminal command from one of the above posts to record videos from the wanted device simulator. And then use iMovie's New App Preview feature.
xcrun /Applications/Xcode.app/Contents/Developer/usr/bin/simctl io booted recordVideo pro3new.mov
iMovie -> File -> New App Preview
In addition to @chanafdo answer, you can use route name
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
This is how I solved my problem:
List<User> list = GetAllUsers(); //Private Method
if (!sortAscending)
{
list = list
.OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
else
{
list = list
.OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
You could say defaultdict
is useful for settings defaults before filling the dict and setdefault
is useful for setting defaults while or after filling the dict.
Probably the most common use case: Grouping items (in unsorted data, else use itertools.groupby
)
# really verbose
new = {}
for (key, value) in data:
if key in new:
new[key].append( value )
else:
new[key] = [value]
# easy with setdefault
new = {}
for (key, value) in data:
group = new.setdefault(key, []) # key might exist already
group.append( value )
# even simpler with defaultdict
from collections import defaultdict
new = defaultdict(list)
for (key, value) in data:
new[key].append( value ) # all keys have a default already
Sometimes you want to make sure that specific keys exist after creating a dict. defaultdict
doesn't work in this case, because it only creates keys on explicit access. Think you use something HTTP-ish with many headers -- some are optional, but you want defaults for them:
headers = parse_headers( msg ) # parse the message, get a dict
# now add all the optional headers
for headername, defaultvalue in optional_headers:
headers.setdefault( headername, defaultvalue )
I've found that using OnTime
can be painful, particularly when:
This article by Chip Pearson was very illuminating. I prefer to use the Windows Timer now, instead of OnTime
.
For anyone using FluentNHibernate (my version is 2.1.2), it's just as repetitive but this works:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("users");
Id(x => x.Id).Column("id").GeneratedBy.SequenceIdentity("users_id_seq");
The JDK_HOME variable should always point to the base dir of the jdk, not the bin dir:
D:\name\name\core java\software\Java\Java_1.6.0_04_win\jdk1.6.0_04
That defined, fix your path to be
C:\Windows\System32;D:\name\name1\Softwares\Maven\apache-maven-3.0.4\bin;C:\Program Files\Notepad++\;%JDK_HOME%\bin
You can use toStringAsFixed
in order to display the limited digits after decimal points. toStringAsFixed
returns a decimal-point string-representation. toStringAsFixed
accepts an argument called fraction Digits
which is how many digits after decimal we want to display. Here is how to use it.
double pi = 3.1415926;
const val = pi.toStringAsFixed(2); // 3.14
This isn't exactly what's asked, but here's an important note: When running Java on a Windows machine, the Oracle installer puts a "java.exe" into C:\Windows\system32, and this is what acts as the launcher for the Java application (UNLESS there's a java.exe earlier in the PATH, and the Java app is run from the command-line). This is why File(".") keeps returning C:\Windows\system32, and why running examples from macOS or *nix implementations keep coming back with different results from Windows.
Unfortunately, there's really no universally correct answer to this one, as far as I have found in twenty years of Java coding unless you want to create your own native launcher executable using JNI Invocation, and get the current working directory from the native launcher code when it's launched. Everything else is going to have at least some nuance that could break under certain situations.
Use the length
property of the [String]
type:
if ($dbUserName.length -gt 8) {
Write-Output "Please enter more than 8 characters."
$dbUserName = Read-Host "Re-enter database username"
}
Please note that you have to use -gt
instead of >
in your if
condition. PowerShell uses the following comparison operators to compare values and test conditions:
Here is how to restore a backup as an additional db with a unique db name.
For SQL 2005 this works very quickly. I am sure newer versions will work the same.
First, you don't have to take your original db offline. But for safety sake, I like to. In my example, I am going to mount a clone of my "billing" database and it will be named "billingclone".
1) Make a good backup of the billing database
2) For safety, I took the original offline as follows:
3) Open a new Query window
**IMPORTANT! Keep this query window open until you are all done! You need to restore the db from this window!
Now enter the following code:
-- 1) free up all USER databases
USE master;
GO
-- 2) kick all other users out:
ALTER DATABASE billing SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
-- 3) prevent sessions from re-establishing connection:
ALTER DATABASE billing SET OFFLINE;
3) Next, in Management Studio, rt click Databases in Object Explorer, choose "Restore Database"
4) enter new name in "To Database" field. I.E. billingclone
5) In Source for Restore, click "From Device" and click the ... navigate button
6) Click Add and navigate to your backup
7) Put a checkmark next to Restore (Select the backup sets to restore)
8) next select the OPTIONS page in upper LH corner
9) Now edit the database file names in RESTORE AS. Do this for both the db and the log. I.E. billingclone.mdf and billingclone_log.ldf
10) now hit OK and wait for the task to complete.
11) Hit refresh in your Object Explorer and you will see your new db
12) Now you can put your billing db back online. Use the same query window you used to take billing offline. Use this command:
-- 1) free up all USER databases
USE master; GO
-- 2) restore access to all users:
ALTER DATABASE billing SET MULTI_USER WITH ROLLBACK IMMEDIATE;GO
-- 3) put the db back online:
ALTER DATABASE billing SET ONLINE;
done!
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
This worked for me like a charm:
proxy = "localhost:8080"
desired_capabilities = webdriver.DesiredCapabilities.CHROME.copy()
desired_capabilities['proxy'] = {
"httpProxy": proxy,
"ftpProxy": proxy,
"sslProxy": proxy,
"noProxy": None,
"proxyType": "MANUAL",
"class": "org.openqa.selenium.Proxy",
"autodetect": False
}
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
If display: inline;
isn't working, try out display: inline-block;
. :)
I think this is what you want, I already tested this code and works
The tools used are: (all these tools can be downloaded as Nuget packages)
http://fluentassertions.codeplex.com/
http://autofixture.codeplex.com/
https://nuget.org/packages/AutoFixture.AutoMoq
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
var sut = fixture.CreateAnonymous<Transfer>();
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
.Throws<System.IO.IOException>();
sut.Invoking(x =>
x.TransferFiles(
myInterface.Object,
It.IsAny<string>(),
It.IsAny<string>()
))
.ShouldThrow<System.IO.IOException>();
Edited:
Let me explain:
When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer
So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code
When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs
In this case your external dependency is IFileConnection
so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected
var fixture = new Fixture().Customize(new AutoMoqCustomization());
: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
: This freezes the IFileConnection
dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object
var sut = fixture.CreateAnonymous<Transfer>();
: Here AutoFixture is creating the SUT for us
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>();
Here you are configuring the dependency to throw an exception whenever the Get
method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception
sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();
: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles
real method from the SUT and as parameters it receives the mocked IFileConnection
so whenever you call the IFileConnection.Get
in the normal flow of your SUT TransferFiles
method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>()
(from the FluentAssertions library)
References recommended:
http://martinfowler.com/articles/mocksArentStubs.html
http://misko.hevery.com/code-reviewers-guide/
http://misko.hevery.com/presentations/
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
Make #site_nav_global_primary
positioned as fixed and set width to 100 % and desired height.
The following awk command prints the last N fields of each line and at the end of the line prints a new line character:
awk '{for( i=6; i<=NF; i++ ){printf( "%s ", $i )}; printf( "\n"); }'
Find below an example that lists the content of the /usr/bin directory and then holds the last 3 lines and then prints the last 4 columns of each line using awk:
$ ls -ltr /usr/bin/ | tail -3
-rwxr-xr-x 1 root root 14736 Jan 14 2014 bcomps
-rwxr-xr-x 1 root root 10480 Jan 14 2014 acyclic
-rwxr-xr-x 1 root root 35868448 May 22 2014 skype
$ ls -ltr /usr/bin/ | tail -3 | awk '{for( i=6; i<=NF; i++ ){printf( "%s ", $i )}; printf( "\n"); }'
Jan 14 2014 bcomps
Jan 14 2014 acyclic
May 22 2014 skype
My requirement was to view the content of a file (like a property file) inside the jar, without actually extracting the jar. If anyone reached this thread just like me, try this command -
unzip -p myjar.jar myfile.txt
This worked well for me!
>>> dict2 = dict1
# dict2 is bind to the same Dict object which binds to dict1, so if you modify dict2, you will modify the dict1
There are many ways to copy Dict object, I simply use
dict_1 = {
'a':1,
'b':2
}
dict_2 = {}
dict_2.update(dict_1)
I used ternary operator and it's working fine for me.
>
{item.lotNum == null ? ('PDF'):(item.lotNum)}
Use this one, I've written this to my app,
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#882C383E"/>
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
Keep in mind that database tables are designed to grow vertically (more rows), not horizontally (more columns)
I'm planning to static import the following to allow for the method reference to be used inline:
public static <T> Predicate<T> not(Predicate<T> t) {
return t.negate();
}
e.g.
Stream<String> s = ...;
long nonEmptyStrings = s.filter(not(String::isEmpty)).count();
Update: Starting from Java-11, the JDK offers a similar solution built-in as well.
This should do it for you - all your files will end up called Part1-Part500.
#!/bin/bash
FILENAME=10000.csv
HDR=$(head -1 $FILENAME) # Pick up CSV header line to apply to each file
split -l 20 $FILENAME xyz # Split the file into chunks of 20 lines each
n=1
for f in xyz* # Go through all newly created chunks
do
echo $HDR > Part${n} # Write out header to new file called "Part(n)"
cat $f >> Part${n} # Add in the 20 lines from the "split" command
rm $f # Remove temporary file
((n++)) # Increment name of output part
done
Right Click on Project >Android Tools >Rename Application Package
Go to src and right click on your main package >Refactor >Rename
Go to manifest file and change your package name .
You can get the instance of the controller from the FXMLLoader
after initialization via getController()
, but you need to instantiate an FXMLLoader
instead of using the static methods then.
I'd pass the stage after calling load()
directly to the controller afterwards:
FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml"));
Parent root = (Parent)loader.load();
MyController controller = (MyController)loader.getController();
controller.setStageAndSetupListeners(stage); // or what you want to do
A dialect is a form of the language that is spoken by a particular group of people.
Here, in context of hibernate framework, When hibernate wants to talk(using queries) with the database it uses dialects.
The SQL dialect's are derived from the Structured Query Language which uses human-readable expressions to define query statements.
A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries.
The dialect of hibernate can be configured using below property:
hibernate.dialect
Here, is a complete list of hibernate dialects.
Note: The dialect property of hibernate is not mandatory.
This can also be done in later versions of handlebars using the key=value
notation:
{{> mypartial foo='bar' }}
Allowing you to pass specific values to your partial context.
Reference: Context different for partial #182
I recently came across this problem myself.
<!--Instead of using input-->
<input type="submit"/>
<!--Use button-->
<button type="submit">
<!--You can then attach your custom CSS to the button-->
Hope that helps.
Angular: 8.2.11
<td>{{ data.DateofBirth | date }}</td>
Output: Jun 9, 1973
<td>{{ data.DateofBirth | date: 'dd/MM/yyyy' }}</td>
Output: 09/06/1973
<td>{{ data.DateofBirth | date: 'dd/MM/yyyy hh:mm a' }}</td>
Output: 09/06/1973 12:00 AM
I just replaced and assigned attributes for su to ~/Android/Sdk/system-images/android-22/google_apis/x86/system.img and now on android 5 I always have root even for new systems, it’s enough to install SuperSu.apk
Android 6 is necessary only
adb root
adb shell
>/system/xbin/su --daemon &
>setenfoce 0
after that, SuperSu.apk sees root. But I do not update the binary file
If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled.
If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied.
Here's an example and some possible fixes.
Here's a demo in Stack Snippets without jquery-ui.css (doesn't work)
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery-ui-bootstrap. Just grab the stylesheet from there and you should be all set.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using.
After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace.
You can use bootstrap's dropdowns.less for inspiration.
Here's a sample CSS that fits pretty well with Bootstrap's default theme:
.ui-autocomplete {
position: absolute;
z-index: 1000;
cursor: default;
padding: 0;
margin-top: 2px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.ui-autocomplete > li {
padding: 3px 20px;
}
.ui-autocomplete > li.ui-state-focus {
background-color: #DDD;
}
.ui-helper-hidden-accessible {
display: none;
}
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
.ui-autocomplete {_x000D_
position: absolute;_x000D_
z-index: 1000;_x000D_
cursor: default;_x000D_
padding: 0;_x000D_
margin-top: 2px;_x000D_
list-style: none;_x000D_
background-color: #ffffff;_x000D_
border: 1px solid #ccc_x000D_
-webkit-border-radius: 5px;_x000D_
-moz-border-radius: 5px;_x000D_
border-radius: 5px;_x000D_
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
}_x000D_
.ui-autocomplete > li {_x000D_
padding: 3px 20px;_x000D_
}_x000D_
.ui-autocomplete > li.ui-state-focus {_x000D_
background-color: #DDD;_x000D_
}_x000D_
.ui-helper-hidden-accessible {_x000D_
display: none;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group ui-widget">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group ui-widget">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control" />_x000D_
</div>_x000D_
</div>
_x000D_
Tip: Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with
.ui-autocomplete
and removedisplay: none;
.
While not exactly renaming, dplyr::select_all()
can be used to reformat column names. This example replaces spaces and periods with an underscore and converts everything to lower case:
iris %>%
select_all(~gsub("\\s+|\\.", "_", .)) %>%
select_all(tolower) %>%
head(2)
sepal_length sepal_width petal_length petal_width species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
This exists in @ManyToOne relation. I solved this issue by just using CascadeType.MERGE instead of CascadeType.PERSIST or CascadeType.ALL. Hope it helps you.
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;
Solution:
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;
It's a GNU extension. In a nutshell it's a convenient way to declare an object having the same type as another. For example:
int x; /* Plain old int variable. */
typeof(x) y; /* Same type as x. Plain old int variable. */
It works entirely at compile-time and it's primarily used in macros. One famous example of macro relying on typeof
is container_of
.
LGrind does this. It's a mature LaTeX package that's been around since adam was a cowboy and has support for many programming languages.
There is not much which I would like to add to Rody Oldenhuis answer. I usually follow the strategy that all functions which I write should run in Matlab.
Some specific functions I test on both systems, for the following use cases:
a) octave does not need a license server - e.g. if your institution does not support local licenses. I used it once in a situation where the system I used a script on had no connection to the internet and was going to run for a very long time (in a corner in the lab) and used by many different users. Remark: that is not about the license cost, but about the technical issues related.
b) Octave supports other platforms, for example, the Rasberry Pi (http://wiki.octave.org/Rasperry_Pi) - which may come in handy.
Swift 5.0 + , Simple and Short
example:
Style 1
func methodName(completionBlock: () -> Void) {
print("block_Completion")
completionBlock()
}
Style 2
func methodName(completionBlock: () -> ()) {
print("block_Completion")
completionBlock()
}
Use:
override func viewDidLoad() {
super.viewDidLoad()
methodName {
print("Doing something after Block_Completion!!")
}
}
Output
block_Completion
Doing something after Block_Completion!!
Your error is also shown when trying to access the sizeof()
of an non-initialized extern array:
extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'
Note that you would get an array size missing
error without the extern
keyword.
When doing branch updates from master, I notice that I sometimes over-click, and cause the branch to merge into the master, too. Found a way to undo that.
If your last commit was a merge, a little more love is needed:
git revert -m 1 HEAD
\s
matches whitespace (spaces, tabs and new lines). \S
is negated \s
.
You can use sets:
main_list = list(set(list_2) - set(list_1))
Output:
>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> set(list_2) - set(list_1)
set(['m', 'f'])
>>> list(set(list_2) - set(list_1))
['m', 'f']
Per @JonClements' comment, here is a tidier version:
>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> list(set(list_2).difference(list_1))
['m', 'f']
please try to make it as a character
string str = "Tigger";
//then str[0] will return 'T' not "T"
Use the below code. Here -f checks, it's a file or not:
print "File $base_path is exists!\n" if -f $base_path;
and enjoy
The Google Finance Gadget API has been officially deprecated since October 2012, but as of April 2014, it's still active:
http://www.google.com/finance/info?q=NASDAQ:GOOG
http://www.google.com/finance/info?q=CURRENCY:GBPUSD
http://finance.google.com/finance/info?client=ig&q=AAPL,YHOO
You can also get charts: https://www.google.com/finance/getchart?q=YELP
Note that if your application is for public consumption, using the Google Finance API is against Google's terms of service.
Check google-finance-get-stock-quote-realtime for the complete code in python
Ok, I finally resolved this, by completely de-installing Android-Studio, and then installing the latest (0.2.0) from scratch.
EDIT: I also had to use the Android SDK-Manager, and install the component in the 'Extras' section called the Android Support Repository (as mentioned elsewhere).
Note: This does NOT fix my old existing project...that one still will not build, as indicated above.
But, it DOES solve the issue of now being able to at least create NEW projects going forward, that build ok using 'Gradle'. (So, basically, I re-created my proj from scratch under a new name, and copied all my code and project xml-files, etc, from the old project, into the newly-created one.)
[As an aside: I've got an idea, Google! Why don't you refer to versions of Android-Studio using numbers like 0.1.9 and 0.2.0, but then when users click on 'About' menu item, or search elsewhere for what version they are running, you could baffle them with crap like 'the July 11th build' or aka, some build number with 6 or 8 digits of numbering, and make them wonder what version they actually have! That will keep the developers guessing...really will sort the wheat from the chaff, etc.]
For example, I originally installed a kit named: android-studio-bundle-130.687321-windows.exe
Today, I got the "0.2.0" kit???, and it has a name like: android-studio-bundle-130.737825-windows.exe
Yep, this version #ing system is about as clear as mud.
Why bother with the illusion of version#s, when you don't use them!!!???
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
Nope.
But lo! If you use std::vector<Car>
, like you should be (never ever use new[]
), then you can specify exactly how elements should be constructed*.
*Well sort of. You can specify the value of which to make copies of.
Like this:
#include <iostream>
#include <vector>
class Car
{
private:
Car(); // if you don't use it, you can just declare it to make it private
int _no;
public:
Car(int no) :
_no(no)
{
// use an initialization list to initialize members,
// not the constructor body to assign them
}
void printNo()
{
// use whitespace, itmakesthingseasiertoread
std::cout << _no << std::endl;
}
};
int main()
{
int userInput = 10;
// first method: userInput copies of Car(5)
std::vector<Car> mycars(userInput, Car(5));
// second method:
std::vector<Car> mycars; // empty
mycars.reserve(userInput); // optional: reserve the memory upfront
for (int i = 0; i < userInput; ++i)
mycars.push_back(Car(i)); // ith element is a copy of this
// return 0 is implicit on main's with no return statement,
// useful for snippets and short code samples
}
With the additional function:
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i < length; i++) // whitespace! :)
std::cout << cars[i].printNo();
}
int main()
{
// ...
printCarNumbers(&mycars[0], mycars.size());
}
Note printCarNumbers
really should be designed differently, to accept two iterators denoting a range.
man you can use the basic Bootstrap Datepicker this way:
<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pickyDate').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
and inside body:
<body>
<div id="testDIV">
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</div>
</div>
</div>
datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.
You want:
grep -A 5 '19:55' file
From man grep
:
Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a gup separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.
With the -o or --only-matching option, this has no effect and a warning
is given.
--group-separator=SEP
Use SEP as a group separator. By default SEP is double hyphen (--).
--no-group-separator
Use empty string as a group separator.
A very simple solution can be:
try {
requestEntity = RequestEntity
.get(new URI("user String"));
return restTemplate.exchange(requestEntity, String.class);
} catch (RestClientResponseException e) {
return ResponseEntity.status(e.getRawStatusCode()).body(e.getResponseBodyAsString());
}
Your question about performance is moot—both functions are very fast. The speed of your code will be determined by what you do with the random numbers.
However it's important you understand the difference in behaviour of those two functions. One does random sampling with replacement, the other does random sampling without replacement.
Escape special characters with a backslash. \.
, \*
, \+
, \\d
, and so on. If you are unsure, you may escape any non-alphabetical character whether it is special or not. See the javadoc for java.util.regex.Pattern for further information.
This is concerning "Build Solution" option only.
I got totally fed up with Visual Studio's inability to really clean solutions and wrote this little tool that will do it for you.
Close your solution in VS first and drag its folder from Windows Explorer into this app or into its icon. Depending on the setting at the bottom of its window, it can also remove additional stuff, that will help if you try to manually upload your solution to GitHub or share it with someone else:
In a nutshell, it will place all "Debug" folders, Intellisense, and other caches that can be rebuilt by VS into Recycle Bin for you.
Under [branch "master"]
, try adding the following to the repo's Git config file (.git/config
):
[branch "master"]
remote = origin
merge = refs/heads/master
This tells Git 2 things:
git pull
on the master branch, with no remote and branch specified, use the default remote (origin) and merge in the changes from the remote master branch.I'm not sure why this setup would've been removed from your configuration, though. You may have to follow the suggestions that other people have posted, too, but this may work (or help at least).
If you don't want to edit the config file by hand, you can use the command-line tool instead:
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
I'm not entirely surprised that your example exhibits no strange behaviour. Try copying str1
to str1+2
instead and see what happens then. (May not actually make a difference, depends on compiler/libraries.)
In general, memcpy is implemented in a simple (but fast) manner. Simplistically, it just loops over the data (in order), copying from one location to the other. This can result in the source being overwritten while it's being read.
Memmove does more work to ensure it handles the overlap correctly.
EDIT:
(Unfortunately, I can't find decent examples, but these will do). Contrast the memcpy and memmove implementations shown here. memcpy just loops, while memmove performs a test to determine which direction to loop in to avoid corrupting the data. These implementations are rather simple. Most high-performance implementations are more complicated (involving copying word-size blocks at a time rather than bytes).
Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:
if (document.getElementById('customx') == ""){
DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
var indices = [];
var IDs = [0, 1, 2, 3, 4];
for(var i = 0, len = array.length; i < len; i++) {
for(var j = 0; j < IDs.length; j++) {
if(array[i].id == ID) indices.push(i);
}
}
Use following query to print REPAIR
SQL statments for all tables inside a database:
select concat('REPAIR TABLE ', table_name, ';') from information_schema.tables
where table_schema='mydatabase';
After that copy all the queries and execute it on mydatabase
.
Note: replace mydatabase
with desired DB name
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
I just click on latest swift convert button and set App target build setting-> Swift language version: swift 4.0,
Hope this will help.
use request.getContextPath()
instead of ${pageContext.request.contextPath}
in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
I got this error after creating a new sysadmin user under my SQL instance. My admin user was created under a specific domain MyOrganization/useradmin
Using useradmin on a disconnected environment allows you to create other users using SQL Server authentication, but as soon as you try to login you get
Microsoft SQL Server Error: 18456
To fix the problem, try to connect again to your Organization network and create the user while you are connected and then you can get disconnected and will work.
if in case you are not using name in input but other element, then you can target other element with there attribute.
[title~=flower] {_x000D_
border: 5px solid yellow;_x000D_
}
_x000D_
<img src="klematis.jpg" title="klematis flower" width="150" height="113">_x000D_
<img src="img_flwr.gif" title="flower" width="224" height="162">_x000D_
<img src="img_flwr.gif" title="flowers" width="224" height="162">
_x000D_
hope its help. Thank you
You can simply do:
var ms = new MemoryStream(File.ReadAllBytes(filePath));
Stream position is 0 and ready to use.
I have used a syntax like this before:
$(ProjectDir)..\headers
or
..\headers
As other have pointed out, the starting directory is the one your project file is in(vcproj
or vcxproj
), not where your main code is located.
select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table
Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!
What I did, by reading all of above answers and it worked as well: 7 deadly steps
If you get it running, please help others too.
or, in PHP 7.2 or later:
This notice occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.
One of the most common causes of this notice is a failure to quote a string used as an associative array key.
For example:
// Wrong
echo $array[key];
// Right
echo $array['key'];
Another common cause is a missing $
(dollar) sign in front of a variable name:
// Wrong
echo varName;
// Right
echo $varName;
Or perhaps you have misspelled some other constant or keyword:
// Wrong
$foo = fasle;
// Right
$foo = false;
It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.
Related Questions:
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
To get the job done, use
<table cellspacing=12>
If you’d rather “be right” than get things done, you can instead use the CSS property border-spacing
, which is supported by some browsers.
Let's create an empty list (not required, but good to know):
> mylist <- vector(mode="list")
Let's put some stuff in it - 3 components/indexes/tags (whatever you want to call it) each with differing amounts of elements:
> mylist <- list(record1=c(1:10),record2=c(1:5),record3=c(1:2))
If you are interested in just the number of components in a list use:
> length(mylist)
[1] 3
If you are interested in the length of elements in a specific component of a list use: (both reference the same component here)
length(mylist[[1]])
[1] 10
length(mylist[["record1"]]
[1] 10
If you are interested in the length of all elements in all components of the list use:
> sum(sapply(mylist,length))
[1] 17
The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.
You need to add the parameters both to the URL and to the signature creating process. Creating a signature is the article that helped me. Here is my code:
$oauth = array(
'screen_name' => 'DwightHoward',
'count' => 2,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:
L[0] += 1
is not guaranteed to actually increase L[0] by one if another thread does the same thing, because +=
is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.
MySQL is getting stupid here. It tries to create files under /tmp/data/.... So what you can do is the following:
mkdir /tmp/data
mount --bind /data /tmp/data
Then try your query. This worked for me after hours of debugging the issue.
You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.
Here are some other options:
I have used xml2js
and it has worked fine for me. The rest you might have to try out for yourself.
@Alexander Mills answer - just to make it easier to find:
RUN npm set unsafe-perm true
In HTML:
<form id="my_form"><input id="my_field" type="date" /></form>
In JavaScript
// test and transform if needed_x000D_
if($('#my_field').attr('type') === 'text'){_x000D_
$('#my_field').attr('type', 'text').attr('placeholder','aaaa-mm-dd'); _x000D_
};_x000D_
_x000D_
// check_x000D_
if($('#my_form')[0].elements[0].value.search(/(19[0-9][0-9]|20[0-1][0-5])[- \-.](0[1-9]|1[012])[- \-.](0[1-9]|[12][0-9]|3[01])$/i) === 0){_x000D_
$('#my_field').removeClass('bad');_x000D_
} else {_x000D_
$('#my_field').addClass('bad');_x000D_
};
_x000D_
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
I also ran into this issue just now while messing with laravel.
I am using wampserver for windows and had to copy the /bin/apache/apacheversion/bin/php.ini file to /bin/php/phpversion/php.ini
I did it only using boostrap, you must be very careful in the location of the row and the column, here is my example.
<section>_x000D_
<div class="container">_x000D_
<div ng-app="myApp">_x000D_
_x000D_
<div ng-controller="SubregionController">_x000D_
<div class="row text-center">_x000D_
<div class="col-md-4" ng-repeat="post in posts">_x000D_
<div >_x000D_
<div>{{post.title}}</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div> _x000D_
</div>_x000D_
</div>_x000D_
</div> _x000D_
_x000D_
</section>
_x000D_
Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme
. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage
file in a language's directory/package. For example, the JavaScript.tmLanguage
file assigns the scopes source.js
and variable.language.js
to the this
keyword. Since Sublime Text 3 is using the .sublime-package
zip file format to store all the default settings it's not very straightforward to edit the individual files.
Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.
As it so happens, I've developed the Neon Color Scheme
, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon
still has a lot more diversity than some of the defaults like Monokai
or Solarized
.
I should note that I used @int3h's Better JavaScript
language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.
UPDATE
Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax
. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:
Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer
via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package
packages. So, if you choose, you can directly edit the color schemes included with Sublime.
ANOTHER UPDATE
With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.
If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript
(or whatever language(s) you want) into your Packages
directory - find it on your system by selecting Preferences -> Browse Packages...
. Then, simply do a git pull
in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax
format instead of the old .tmLanguage
one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).
I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.
why don't you try pip list
Remember I'm using pip version 19.1 on python version 3.7.3
Another option would be to suppress the PHP undefined index notice with the @
symbol in front of the GET variable like so:
$s = @$_GET['s'];
This will disable the notice. It is better to check if the variable has been set and act accordingly.
But this also works.
A tested one-liner:
int number = ((NSNumber*)[dict objectForKey:@"integer"]).intValue;
You can override the constructor. Something like:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
public MyAsyncTask(boolean showLoading) {
super();
// do stuff
}
// doInBackground() et al.
}
Then, when calling the task, do something like:
new MyAsyncTask(true).execute(maybe_other_params);
Edit: this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:
MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();
Example fetch with authorization header:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': 'Basic '+btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: 'A=1&B=2'
});
As stated by Taylor L, you can't just "stop" a thread (by calling a simple method) due to the fact that it could leave your system in an unstable state as the external calling thread may not know what is going on inside your thread.
With this said, the best way to "stop" a thread is to have the thread keep an eye on itself and to have it know and understand when it should stop.
Instead of doing
function setSelectedIndex(s, v) {
for ( var i = 0; i < s.options.length; i++ ) {
if ( s.options[i].value == v ) {
s.options[i].selected = true;
return;
}
}
}
I solved this problem by doing this
function setSelectedValue(dropDownList, valueToSet) {
var option = dropDownList.firstChild;
for (var i = 0; i < dropDownList.length; i++) {
if (option.text.trim().toLowerCase() == valueToSet.trim().toLowerCase()) {
option.selected = true;
return;
}
option = option.nextElementSibling;
}
}
If you work with strings, you should use the .trim()
method, sometimes blank spaces can cause trouble and they are hard to detect in javascript debugging sessions.
dropDownList.firstChild
will actually be your first option
tag. Then, by doing option.nextElementSibling
you can go to the next option
tag, so the next choice in your dropdownlist element. If you want to get the number of option
tags you can use dropDownList.length
which I used in the for loop.
Hope this helps someone.
os.Executable
: https://tip.golang.org/pkg/os/#Executable
filepath.EvalSymlinks
: https://golang.org/pkg/path/filepath/#EvalSymlinks
Full Demo:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var dirAbsPath string
ex, err := os.Executable()
if err == nil {
dirAbsPath = filepath.Dir(ex)
fmt.Println(dirAbsPath)
return
}
exReal, err := filepath.EvalSymlinks(ex)
if err != nil {
panic(err)
}
dirAbsPath = filepath.Dir(exReal)
fmt.Println(dirAbsPath)
}
Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:
@Autowired
public TestController(KeeperClient testClient) {
TestController.testClient = testClient;
}
In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.
In this answer I choose to approach the "Simple Java AES encrypt/decrypt example" main theme and not the specific debugging question because I think this will profit most readers.
This is a simple summary of my blog post about AES encryption in Java so I recommend reading through it before implementing anything. I will however still provide a simple example to use and give some pointers what to watch out for.
In this example I will choose to use authenticated encryption with Galois/Counter Mode or GCM mode. The reason is that in most case you want integrity and authenticity in combination with confidentiality (read more in the blog).
Here are the steps required to encrypt/decrypt with AES-GCM with the Java Cryptography Architecture (JCA). Do not mix with other examples, as subtle differences may make your code utterly insecure.
As it depends on your use-case, I will assume the simplest case: a random secret key.
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
SecretKey secretKey = SecretKeySpec(key, "AES");
Important:
SecureRandom
An initialization vector (IV) is used so that the same secret key will create different cipher texts.
byte[] iv = new byte[12]; //NEVER REUSE THIS IV WITH SAME KEY
secureRandom.nextBytes(iv);
Important:
SecureRandom
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); //128 bit auth tag length
cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
byte[] cipherText = cipher.doFinal(plainText);
Important:
CipherInputStream
when encrypting large chunks of datacipher.updateAAD(associatedData);
More here.Just append IV and ciphertext. As stated above, the IV doesn't need to be secret.
ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + cipherText.length);
byteBuffer.put(iv);
byteBuffer.put(cipherText);
byte[] cipherMessage = byteBuffer.array();
Optionally encode with Base64 if you need a string representation. Either use Android's or Java 8's built-in implementation (do not use Apache Commons Codec - it's an awful implementation). Encoding is used to "convert" byte arrays to string representation to make it ASCII safe e.g.:
String base64CipherMessage = Base64.getEncoder().encodeToString(cipherMessage);
If you have encoded the message, first decode it to byte array:
byte[] cipherMessage = Base64.getDecoder().decode(base64CipherMessage)
Important:
Initialize the cipher and set the same parameters as with the encryption:
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
//use first 12 bytes for iv
AlgorithmParameterSpec gcmIv = new GCMParameterSpec(128, cipherMessage, 0, 12);
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmIv);
//use everything from 12 bytes on as ciphertext
byte[] plainText = cipher.doFinal(cipherMessage, 12, cipherMessage.length - 12);
Important:
cipher.updateAAD(associatedData);
if you added it during encryption.A working code snippet can be found in this gist.
Note that most recent Android (SDK 21+) and Java (7+) implementations should have AES-GCM. Older versions may lack it. I still choose this mode, since it is easier to implement in addition to being more efficient compared to similar mode of Encrypt-then-Mac (with e.g. AES-CBC + HMAC). See this article on how to implement AES-CBC with HMAC.
For JQuery 1.7+ use:
$('input[type=checkbox]').on('change', function() {
...
});
From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).
The problem might be you have not created server on your local machine which listens to port 8000.
For that you have to set up server on localhost which can serve your request.
Create server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Run server.js : node server.js
Run file that contains code to make request.
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)