My shaded jar file did not contain the third-party library using AlirezaFattahi's solution. however, I remeber that it was working once I had tried it for the same project last time. So, I tried my own solution:
Finally, It worked for me. :)
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
If the above solution doesn't work, check to see if you have $(LibraryPath) in Properties->VC++ Directories->Library Directories. If you are missing it, try adding it.
Some time you may just need to add maven { url "https://jitpack.io" }
in your allprojects block in project level build.gradle file.
Example:
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
A library performs specific, well-defined operations.
A framework is a skeleton where the application defines the "meat" of the operation by filling out the skeleton. The skeleton still has code to link up the parts but the most important work is done by the application.
Examples of libraries: Network protocols, compression, image manipulation, string utilities, regular expression evaluation, math. Operations are self-contained.
Examples of frameworks: Web application system, Plug-in manager, GUI system. The framework defines the concept but the application defines the fundamental functionality that end-users care about.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.
The fix is to change logger.trace to logger.error in the body of errorLogger.
For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.
Next open Configuration Properties and then Linker.
Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,
Linker -> Input you'll add the actual library files under Additional Dependencies.
For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.
If there is a dll have a copy of it in your main project folder, and done.
I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.
Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.
This was written for Visual Studio 2008. For 2010 it should be roughly the same.
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
It is a textual file that includes a description of the library.
It allows libtool
to create platform-independent names.
For example, libfoo
goes to:
Under Linux:
/lib/libfoo.so # Symlink to shared object
/lib/libfoo.so.1 # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a # Static library
/lib/libfoo.la # 'libtool' library
Under Cygwin:
/lib/libfoo.dll.a # Import library
/lib/libfoo.a # Static library
/lib/libfoo.la # libtool library
/bin/cygfoo_1.dll # DLL
Under Windows MinGW:
/lib/libfoo.dll.a # Import library
/lib/libfoo.a # Static library
/lib/libfoo.la # 'libtool' library
/bin/foo_1.dll # DLL
So libfoo.la
is the only file that is preserved between platforms by libtool
allowing to understand what happens with:
Without depending on a specific platform implementation of libraries.
Like it can be seen in other answers you'll have to open a Developer Command Prompt offered in your version of Visual Studio to have dumpbin.exe
in your execution path. Otherwise, you can set the necessary environment variables by hand.
dumpbin /EXPORTS yourlibrary.lib
will usually show just a tiny list of symbols. In many cases, it won't show the functions the library exports.
dumpbin /SYMBOLS /EXPORTS yourlibrary.lib
will show that symbols, but also an incredibly huge amount of other symbos. So, you got to filter them, possibly with a pipe to findstr
(if you want a MS-Windows tool), or grep
.
Searching the Static
keyword using one of these tools seems to be a good hint.
This error also occurred when I compiled with MinGW using gcc with the following options:
-lstdc++ -lm
, rather than g++
I did not notice these options, and added: -static-libgcc -static-libstdc++
I still got the error, and finally realized I was using gcc, and changed the compiler to g++ and removed -stdc++ and -lm
, and everything linked fine.
(I was using LINK.c rather than LINK.cpp... use make -pn | less
to see what everything does!)
I don't know why the previous author was using gcc with -stdc++. I don't see any reason not to use g++ which will link with stdc++ automatically... and as far as I know, provide other benefits (it is the c++ compiler after all).
For Jersey 2 you'd need to modify the code:
return ClientBuilder.newBuilder()
.withConfig(config)
.hostnameVerifier(new TrustAllHostNameVerifier())
.sslContext(ctx)
.build();
https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html
You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.
There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.
Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.
Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:
import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';
@Injectable()
export class MyResolver implements Resolve<MyData> {
constructor(private ms: MyService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
let id = route.params['id'];
return this.ms.getId(id).then(data => {
if (data) {
return data;
} else {
this.router.navigate(['/login']);
return;
}
});
}
}
and in the module:
import { MyResolver } from './my-resolver.service';
@NgModule({
imports: [
RouterModule.forChild(myRoutes)
],
exports: [
RouterModule
],
providers: [
MyResolver
]
})
export class MyModule { }
and you can access it in your Component like this:
/////
ngOnInit() {
this.route.data
.subscribe((data: { mydata: myData }) => {
this.id = data.mydata.id;
});
}
/////
And in the Route something like this (usually in the app.routing.ts file):
////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////
For debugging purposes, you could use print(repr(data))
.
To display text, always print Unicode. Don't hardcode the character encoding of your environment such as Cp850 inside your script. To decode the HTTP response, see A good way to get the charset/encoding of an HTTP response in Python.
To print Unicode to Windows console, you could use win-unicode-console
package.
<div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>
EDIT 01-10-2014:
Since this question is so popular this answer has been improved.
The example above will only get the values from RouteData
, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest
. Fastest way is by calling (as TruMan pointed out) `Request.Querystring' so the answer should be:
<div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>
You can also check RouteValues vs QueryString MVC?
EDIT 03-05-2019:
Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query
object from Context.Request
path. So it would be:
<div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div>
Please notice I am using StringValues("1")
in the statement because Query
returns StringValues
struct instead of pure string
. That's cleanes way for this scenerio which I've found.
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
UPDATE for API 26 to set Max priority
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
i know this is an old question but i have a similar situation ,and my solution was
button.setBackgroundResource( R.drawable.ic_button );
Drawable d = button.getBackground();
and then you can play with the "Drawable", applying color filters, etc
If you have Excel 2007 or later use COUNTIFS
with an "S" on the end, i.e.
=COUNTIFS(B2:B292,">10",B2:B292,"<10000")
You may need to change commas , to semi-colons ;
In earlier versions of excel use SUMPRODUCT
like this
=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))
Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=
Use the backslash \
or choose a different delimiter, ie m#.\d#
instead of /.\d/
"In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"
I know this question is old and already has an accepted answer, but I want to offer a few examples (hoping it'll be useful to someone).
As far as I know old ASCII characters took one byte per character.
Right. Actually, since ASCII is a 7-bit encoding, it supports 128 codes (95 of which are printable), so it only uses half a byte (if that makes any sense).
How many bytes does a Unicode character require?
Unicode just maps characters to codepoints. It doesn't define how to encode them. A text file does not contain Unicode characters, but bytes/octets that may represent Unicode characters.
I assume that one Unicode character can contain every possible character from any language - am I correct?
No. But almost. So basically yes. But still no.
So how many bytes does it need per character?
Same as your 2nd question.
And what do UTF-7, UTF-6, UTF-16 etc mean? Are they some kind Unicode versions?
No, those are encodings. They define how bytes/octets should represent Unicode characters.
A couple of examples. If some of those cannot be displayed in your browser (probably because the font doesn't support them), go to http://codepoints.net/U+1F6AA
(replace 1F6AA
with the codepoint in hex) to see an image.
a
©
®
?
—
‰
€
™
?
?
?
?
?
?
?
?
?
?
Okay I'm getting carried away...
Fun facts:
Have them try to write a program that can evaluate arbitrary simple arithmetic expressions. This is a simple problem to understand but as you start getting deeper into it a lot of basic parsing starts to make sense.
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
In angular 1.4 +, in addition to adding the dependency
angular.module('myApp', ['ngRoute'])
,we also need to reference the separate angular-route.js file
<script src="angular.js">
<script src="angular-route.js">
If the command should work with both tabs and spaces as the delimiter I would use awk
:
awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile
As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for
loop:
awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile
If you want to use cut
, you need to use the -f
option:
cut -f100-105 myfile > outfile
If the field delimiter is different from TAB
you need to specify it using -d
:
cut -d' ' -f100-105 myfile > outfile
Check the man page for more info on the cut command.
Using nargs parameter in argparse's add_argument method
I use nargs='*'
as an add_argument parameter. I specifically used nargs='*'
to the option to pick defaults if I am not passing any explicit arguments
Including a code snippet as example:
Example: temp_args1.py
Please Note: The below sample code is written in python3. By changing the print statement format, can run in python2
#!/usr/local/bin/python3.6
from argparse import ArgumentParser
description = 'testing for passing multiple arguments and to get list of args'
parser = ArgumentParser(description=description)
parser.add_argument('-i', '--item', action='store', dest='alist',
type=str, nargs='*', default=['item1', 'item2', 'item3'],
help="Examples: -i item1 item2, -i item3")
opts = parser.parse_args()
print("List of items: {}".format(opts.alist))
Note: I am collecting multiple string arguments that gets stored in the list - opts.alist
If you want list of integers, change the type parameter on parser.add_argument
to int
Execution Result:
python3.6 temp_agrs1.py -i item5 item6 item7
List of items: ['item5', 'item6', 'item7']
python3.6 temp_agrs1.py -i item10
List of items: ['item10']
python3.6 temp_agrs1.py
List of items: ['item1', 'item2', 'item3']
I have resolved this same issue by doing below steps:
File > Close Project
Import Project
Select you project via the system file popup
Check "Import project from external model" radio button and select Maven entry
And some Next buttons (select JDK, ...)
Then the project will be imported as Maven module.
Here are some simple techniques for vertical-align:
This one is easy: set the line-height of the text element to equal that of the container
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>
Absolutely position an inner div relative to its container
<div style="position:relative;width:30px;height:60px;">
<div style="position:absolute;bottom:0">This is positioned on the bottom</div>
</div>
<div style="display:table;width:30px;height:60px;">
<div style="display:table-cell;height:30px;">This is positioned in the middle</div>
</div>
In order to get this to work correctly across the board, you'll have to hack the CSS a bit. Luckily, there is an IE bug that works in our favor. Setting top:50%
on the container and top:-50%
on the inner div, you can achieve the same result. We can combine the two using another feature IE doesn't support: advanced CSS selectors.
<style type="text/css">
#container {
width: 30px;
height: 60px;
position: relative;
}
#wrapper > #container {
display: table;
position: static;
}
#container div {
position: absolute;
top: 50%;
}
#container div div {
position: relative;
top: -50%;
}
#container > div {
display: table-cell;
vertical-align: middle;
position: static;
}
</style>
<div id="wrapper">
<div id="container">
<div><div><p>Works in everything!</p></div></div>
</div>
</div>
This solution requires a slightly more modern browser than the other solutions, as it makes use of the transform: translateY
property. (http://caniuse.com/#feat=transforms2d)
Applying the following 3 lines of CSS to an element will vertically centre it within its parent regardless of the height of the parent element:
position: relative;
top: 50%;
transform: translateY(-50%);
I was having this issue while sending files with regional characters in their names like: VeryRegiónal file - name.pdf
.
The solution was to clear filename before attaching it to the email.
Here's a very simple way to do it;
int main()
{
int s=7,l=1;
vector <bool> v;
v.clear();
while (l <= 4)
{
v.push_back(s%2);
s /= 2;
l++;
}
for (l=(v.size()-1); l >= 0; l--)
{
cout<<v[l]<<" ";
}
return 0;
}
Turns out that Entity Framework will assume that any class that inherits from a POCO class that is mapped to a table on the database requires a Discriminator column, even if the derived class will not be saved to the DB.
The solution is quite simple and you just need to add [NotMapped]
as an attribute of the derived class.
Example:
class Person
{
public string Name { get; set; }
}
[NotMapped]
class PersonViewModel : Person
{
public bool UpdateProfile { get; set; }
}
Now, even if you map the Person class to the Person table on the database, a "Discriminator" column will not be created because the derived class has [NotMapped]
.
As an additional tip, you can use [NotMapped]
to properties you don't want to map to a field on the DB.
my 2cents: start with table with highest fragmentation
for table in `mysql -sss -e "select concat(table_schema,".",table_name) from information_schema.tables where table_schema not in ('mysql','information_schema','performance_schema') order by data_free desc;"
do
mysql -e "OPTIMIZE TABLE $table;"
done
Try using the non-breaking hyphen ‑
. I've replaced the dash with that character in your jsfiddle, shrunk the frame down as small as it can go, and the line doesn't split there any more.
Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.
class Point2D {
double X, Y;
public Point2D(double x, double y) {
init(x, y);
}
public Point2D(Point2D point) {
if (point == null)
throw new ArgumentNullException("point");
init(point.X, point.Y);
}
void init(double x, double y) {
// ... Contracts ...
X = x;
Y = y;
}
}
Following code prints with microsecond precision. All we have to do is use gettimeofday
and strftime
on tv_sec
and append tv_usec
to the constructed string.
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main(void) {
struct timeval tmnow;
struct tm *tm;
char buf[30], usec_buf[6];
gettimeofday(&tmnow, NULL);
tm = localtime(&tmnow.tv_sec);
strftime(buf,30,"%Y:%m:%dT%H:%M:%S", tm);
strcat(buf,".");
sprintf(usec_buf,"%dZ",(int)tmnow.tv_usec);
strcat(buf,usec_buf);
printf("%s",buf);
return 0;
}
Like Giampaolo Rodolà's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles,
For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).
def pr(s):
try:
print(s)
except UnicodeEncodeError:
for c in s:
try:
print( c, end='')
except UnicodeEncodeError:
print( '?', end='')
NB "pr" is shorter to type than "print" (and quite a bit shorter to type than "safeprint")...!
if (true)
{
return View();
}
else
{
return View("another view name");
}
For mocking static functions i was able to do it that way:
wrapper code snippet (not really functional, just for illustration)
class myWrapperClass ...
def myWrapperFunction (...) {
return theOriginalFunction (...)
}
of course having multiple such functions accumulated in a single wrapper class might be beneficial in terms of code reuse.
Did you try format?
@font-face {
font-family: 'The name of the Font Family Here';
src: URL('font.ttf') format('truetype');
}
Read this article: http://css-tricks.com/snippets/css/using-font-face/
Also, might depend on browser as well.
Back in 1967, Edgar Dijkstra wrote an article in a trade magazine about why goto should be eliminated from high level languages to improve code quality. A whole programming paradigm called "structured programming" came out of this, though certainly not everyone agrees that goto automatically means bad code.
The crux of structured programming is essentially that the structure of the code should determine its flow rather than having gotos or breaks or continues to determine flow, wherever possible. Similiarly, having multiple entry and exit points to a loop or function are also discouraged in that paradigm.
Obviously this is not the only programming paradigm, but often it can be easily applied to other paradigms like object oriented programming (ala Java).
Your teachers has probably been taught, and is trying to teach your class that we would best avoid "spaghetti code" by making sure our code is structured, and following the implied rules of structured programming.
While there is nothing inherently "wrong" with an implementation that uses break, some consider it significantly easier to read code where the condition for the loop is explicitly specified within the while() condition, and eliminates some possibilities of being overly tricky. There are definitely pitfalls to using a while(true) condition that seem to pop up frequently in code by novice programmers, such as the risk of accidentally creating an infinite loop, or making code that is hard to read or unnecessarily confusing.
Ironically, exception handling is an area where deviation from structured programming will certainly come up and be expected as you get further into programming in Java.
It is also possible your instructor may have expected you to demonstrate your ability to use a particular loop structure or syntax being taught in that chapter or lesson of your text, and while the code you wrote is functionally equivalent, you may not have been demonstrating the particular skill you were supposed to be learning in that lesson.
You need to put that code into the constructor of your class:
private Reminders reminder = new Reminders();
private dynamic defaultReminder;
public YourClass()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}
The reason is that you can't use one instance variable to initialize another one using a field initializer.
height: 100%
gives the element 100% height of its parent container.
height: auto
means the element height will depend upon the height of its children.
Consider these examples:
height: 100%
<div style="height: 50px">
<div id="innerDiv" style="height: 100%">
</div>
</div>
#innerDiv
is going to have height: 50px
height: auto
<div style="height: 50px">
<div id="innerDiv" style="height: auto">
<div id="evenInner" style="height: 10px">
</div>
</div>
</div>
#innerDiv
is going to have height: 10px
Like that we can do....
int main(int argc, char *argv[]) {
int a, b, c;
*// Converting string type to integer type
// using function "atoi( argument)"*
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
}
Finaly, my service provider answered :
This is a limitation of the virtualization system we use (OpenVZ), basic iptables rules are possible but not those who use the nat table.
If this really is a problem, we can offer you to migrate to a other system virtualization (KVM) as we begin to offer our customers.
SO I had to migrate my server to the new system...
Firstly a quick recap on RSA key generation.
The public key consists of the modulus and the public exponent.
A minimal private key would consist of the modulus and the private exponent. There is no computationally feasible surefire way to go from a known modulus and private exponent to the corresponding public exponent.
However:
So in most practical RSA implementations you can get the public key from the private key. It would be possible to build a RSA based cryptosystem where this was not possible, but it is not the done thing.
Sorry for replying on an older question, but I would like to clarify the last question.
You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:
https://www.google.com/search?g=[value from input-field]
But when you search with google, you notice the following URL:
https://www.google.nl/search?q=google+search+bar
Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.
Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.
If you know the key you should use splice i.e.
myArray.splice(key, 1);
For someone in Steven's position you can try something like this:
for (var key in myArray) {
if (key == 'bar') {
myArray.splice(key, 1);
}
}
or
for (var key in myArray) {
if (myArray[key] == 'bar') {
myArray.splice(key, 1);
}
}
template <typename T> bool IsInVector(const T & what, const std::vector<T> & vec)
{
return std::find(vec.begin(),vec.end(),what)!=vec.end();
}
override func viewDidLoad()
{
super.viewDidLoad()
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'm a test label"
self.view.addSubview(label)
}
Swift 3.0+ Update:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "I'm a test label"
self.view.addSubview(label)
add "throws IOException" to your method like this:
public static void main(String args[]) throws IOException{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
}
You can get access to the options array of a selected object by going document.getElementById("cars").options
where 'cars' is the select object.
Once you have that you can call option[i].setAttribute('selected', 'selected');
to select an option.
I agree with every one else that you are better off doing this server side though.
A non-lodash way to solve this in a fairly readable and efficient manner:
function filterByKeys(obj, keys = []) {_x000D_
const filtered = {}_x000D_
keys.forEach(key => {_x000D_
if (obj.hasOwnProperty(key)) {_x000D_
filtered[key] = obj[key]_x000D_
}_x000D_
})_x000D_
return filtered_x000D_
}_x000D_
_x000D_
const myObject = {_x000D_
a: 1,_x000D_
b: 'bananas',_x000D_
d: null_x000D_
}_x000D_
_x000D_
const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}_x000D_
console.log(result)
_x000D_
If you want to do it without clicking too much, open the Command Window (Ctrl + W, A) and type:
ReSharper_Suspend
or ReSharper_Resume
depending on what you want.
Or you can even set a keyboard shortcut for this purpose. In Visual Studio, go to Tools -> Options -> Environment -> Keyboard.
There you can assign a keyboard shortcut to ReSharper_Suspend
and ReSharper_Resume
.
The Command Window can also be opened with Ctrl + Alt + A, just in case you're in the editor.
Here's a rather contrived way to do it without explicitly using an constructor argument. You need to extend a parameterized abstract class.
public class Test {
public static void main(String [] args) throws Exception {
Generic g = new Generic();
g.initParameter();
}
}
import java.lang.reflect.ParameterizedType;
public abstract class GenericAbstract<T extends Foo> {
protected T parameter;
@SuppressWarnings("unchecked")
void initParameter() throws Exception, ClassNotFoundException,
InstantiationException {
// Get the class name of this instance's type.
ParameterizedType pt
= (ParameterizedType) getClass().getGenericSuperclass();
// You may need this split or not, use logging to check
String parameterClassName
= pt.getActualTypeArguments()[0].toString().split("\\s")[1];
// Instantiate the Parameter and initialize it.
parameter = (T) Class.forName(parameterClassName).newInstance();
}
}
public class Generic extends GenericAbstract<Foo> {
}
public class Foo {
public Foo() {
System.out.println("Foo constructor...");
}
}
1) Server.MapPath(".")
-- Returns the "Current Physical Directory" of the file (e.g. aspx
) being executed.
Ex. Suppose D:\WebApplications\Collage\Departments
2) Server.MapPath("..")
-- Returns the "Parent Directory"
Ex. D:\WebApplications\Collage
3) Server.MapPath("~")
-- Returns the "Physical Path to the Root of the Application"
Ex. D:\WebApplications\Collage
4) Server.MapPath("/")
-- Returns the physical path to the root of the Domain Name
Ex. C:\Inetpub\wwwroot
You can use
select from_unixtime(1300464000,"%Y-%m-%d %h %i %s") from table;
For in details description about
Use this regular expression to match ten digits only:
@"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
@"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits and not more you can use negative lookarounds:
@"(?<!\d)\d{10}(?!\d)"
handles lookinng for something > 1 char long. feel free to increase the parm sizes if you like.
couldnt resist posting
drop function if exists lastIndexOf
go
create function lastIndexOf(@searchFor varchar(100),@searchIn varchar(500))
returns int
as
begin
if LEN(@searchfor) > LEN(@searchin) return 0
declare @r varchar(500), @rsp varchar(100)
select @r = REVERSE(@searchin)
select @rsp = REVERSE(@searchfor)
return len(@searchin) - charindex(@rsp, @r) - len(@searchfor)+1
end
and tests
select dbo.lastIndexof('greg','greg greg asdflk; greg sadf' ) -- 18
select dbo.lastIndexof('greg','greg greg asdflk; grewg sadf' ) --5
select dbo.lastIndexof(' ','greg greg asdflk; grewg sadf' ) --24
Another simple Vanilla solution based on the A1rPun answer (see his fiddle for the jQuery solution, and both are in this one).
It seems that to NOT trigger a single-click handler when the user double-clicks, the single-click handler is necessarily triggered after a delay...
var single = function(e){console.log('single')},
double = function(e){console.log('double')};
var makeDoubleClick = function(e) {
var clicks = 0,
timeout;
return function (e) {
clicks++;
if (clicks == 1) {
timeout = setTimeout(function () {
single(e);
clicks = 0;
}, 250);
} else {
clearTimeout(timeout);
double(e);
clicks = 0;
}
};
}
document.getElementById('btnVanilla').addEventListener('click', makeDoubleClick(), false);
I was poking around stuff like: int cc = 'cc'; It happens that it's basically a byte-wise copy to an integer. Hence the way to look at it is that 'cc' which is basically 2 c's are copied to lower 2 bytes of the integer cc. If you are looking for a trivia, then
printf("%d %d", 'c', 'cc'); would give:
99 25443
that's because 25443 = 99 + 256*99
So 'cc' is a multi-character constant and not a string.
Cheers
The final keyword is used to declare constants.
final int FILE_TYPE = 3;
The finally keyword is used in a try catch statement to specify a block of code to execute regardless of thrown exceptions.
try
{
//stuff
}
catch(Exception e)
{
//do stuff
}
finally
{
//this is always run
}
And finally (haha), finalize im not entirely sure is a keyword, but there is a finalize() function in the Object class.
This is my summary of the above and works perfectly for me. Thanks for the info!
<script language='javascript' type='text/javascript'>
$(document).ready(function () {
var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
if (firstInput != null) {
firstInput.focus();
}
});
</script>
Simple, but effective!
Math.floor(number) === number;
it's better to use whereargs too;
db.delete("tablename","id=? and name=?",new String[]{"1","jack"});
this is like useing this command:
delete from tablename where id='1' and name ='jack'
and using delete function in such way is good because it removes sql injections.
I couldn't get the selected answer to work but after a bit of research, I found that the horizontal scrolling div must have white-space: nowrap
in the css.
Here's complete working code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Something</title>
<style type="text/css">
#scrolly{
width: 1000px;
height: 190px;
overflow: auto;
overflow-y: hidden;
margin: 0 auto;
white-space: nowrap
}
img{
width: 300px;
height: 150px;
margin: 20px 10px;
display: inline;
}
</style>
</head>
<body>
<div id='scrolly'>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
</div>
</body>
</html>
This is example of my own UserControl with Up and Down key catching.
Xaml code:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="13" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="13" />
<RowDefinition Height="13" />
</Grid.RowDefinitions>
<TextBox Name="NUDTextBox" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" TextAlignment="Right" PreviewKeyDown="NUDTextBox_PreviewKeyDown" PreviewKeyUp="NUDTextBox_PreviewKeyUp" TextChanged="NUDTextBox_TextChanged"/>
<RepeatButton Name="NUDButtonUP" Grid.Column="1" Grid.Row="0" FontSize="8" FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="NUDButtonUP_Click">5</RepeatButton>
<RepeatButton Name="NUDButtonDown" Grid.Column="1" Grid.Row="1" FontSize="8" FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Height="13" VerticalAlignment="Bottom" Click="NUDButtonDown_Click">6</RepeatButton>
</Grid>
And the code:
public partial class NumericUpDown : UserControl
{
int minvalue = 0,
maxvalue = 100,
startvalue = 10;
public NumericUpDown()
{
InitializeComponent();
NUDTextBox.Text = startvalue.ToString();
}
private void NUDButtonUP_Click(object sender, RoutedEventArgs e)
{
int number;
if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
else number = 0;
if (number < maxvalue)
NUDTextBox.Text = Convert.ToString(number + 1);
}
private void NUDButtonDown_Click(object sender, RoutedEventArgs e)
{
int number;
if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
else number = 0;
if (number > minvalue)
NUDTextBox.Text = Convert.ToString(number - 1);
}
private void NUDTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
{
NUDButtonUP.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { true });
}
if (e.Key == Key.Down)
{
NUDButtonDown.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { true });
}
}
private void NUDTextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { false });
if (e.Key == Key.Down)
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { false });
}
private void NUDTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
int number = 0;
if (NUDTextBox.Text!="")
if (!int.TryParse(NUDTextBox.Text, out number)) NUDTextBox.Text = startvalue.ToString();
if (number > maxvalue) NUDTextBox.Text = maxvalue.ToString();
if (number < minvalue) NUDTextBox.Text = minvalue.ToString();
NUDTextBox.SelectionStart = NUDTextBox.Text.Length;
}
}
It would be better to have a check before getting the string.
$newstring = substr($dynamicstring, -7);
if characters are greater then 7 return last 7 characters else return the provided string.
or do this if you need to return message or error if length is less then 7
$newstring = (strlen($dynamicstring)>7)?substr($dynamicstring, -7):"message";
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
Use position:fixed
, as previously stated, IE6 doesn't recognize position:fixed
, but with some css magic you can get IE6 to behave:
html, body {
height: 100%;
overflow:auto;
}
body #fixedElement {
position:fixed !important;
position: absolute; /*ie6 */
bottom: 0;
}
The !important
flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement
use position:fixed
in all browsers but IE, and in IE
, position:absolute
will take effect with bottom:0
. This will simulate position:fixed
for IE6
train_test_split
splits arrays or matrices into random train and test subsets. That means that everytime you run it without specifying random_state
, you will get a different result, this is expected behavior. For example:
Run 1:
>>> a, b = np.arange(10).reshape((5, 2)), range(5)
>>> train_test_split(a, b)
[array([[6, 7],
[8, 9],
[4, 5]]),
array([[2, 3],
[0, 1]]), [3, 4, 2], [1, 0]]
Run 2
>>> train_test_split(a, b)
[array([[8, 9],
[4, 5],
[0, 1]]),
array([[6, 7],
[2, 3]]), [4, 2, 0], [3, 1]]
It changes. On the other hand if you use random_state=some_number
, then you can guarantee that the output of Run 1 will be equal to the output of Run 2, i.e. your split will be always the same.
It doesn't matter what the actual random_state
number is 42, 0, 21, ... The important thing is that everytime you use 42, you will always get the same output the first time you make the split.
This is useful if you want reproducible results, for example in the documentation, so that everybody can consistently see the same numbers when they run the examples.
In practice I would say, you should set the random_state
to some fixed number while you test stuff, but then remove it in production if you really need a random (and not a fixed) split.
Regarding your second question, a pseudo-random number generator is a number generator that generates almost truly random numbers. Why they are not truly random is out of the scope of this question and probably won't matter in your case, you can take a look here form more details.
Complete code with error handling and added file stream closes. Add it to your class that you want to be able to serialize and deserialize. In my case the class name is CreateResumeForm
. You should change it to your own class name. Android
interface Serializable
is not sufficient to save your objects to the file, it only creates streams.
// Constant with a file name
public static String fileName = "createResumeForm.ser";
// Serializes an object and saves it to a file
public void saveToFile(Context context) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Creates an object by reading it from a file
public static CreateResumeForm readFromFile(Context context) {
CreateResumeForm createResumeForm = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
createResumeForm = (CreateResumeForm) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return createResumeForm;
}
Use it like this in your Activity
:
form = CreateResumeForm.readFromFile(this);
Yes you can do that by just creating a BroadcastReceiver
that calls your Service
when your Application boots. Here is a complete answer given by me.
Android - Start service on boot
If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Just declare your Service
as declared normally.
$id = $access_data['Privilege']['id'];
if(!in_array($id,$user_access_arr));
$user_access_arr[] = $id;
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
To get the native reference to something like an ion-input
, ry using this
@ViewChild('fileInput', { read: ElementRef }) fileInput: ElementRef;
and then
this.fileInput.nativeElement.querySelector('input').click()
In a column with blanks, you can get the last value with
=+sort(G:G,row(G:G)*(G:G<>""),)
As docgnome mentioned, rewriting history is dangerous and will break other people's repositories.
But if you really want to do that and you are in a bash environment (no problem in Linux, on Windows, you can use git bash, that is provided with the installation of git), use git filter-branch:
git filter-branch --env-filter '
if [ $GIT_AUTHOR_EMAIL = bad@email ];
then GIT_AUTHOR_EMAIL=correct@email;
fi;
export GIT_AUTHOR_EMAIL'
To speed things up, you can specify a range of revisions you want to rewrite:
git filter-branch --env-filter '
if [ $GIT_AUTHOR_EMAIL = bad@email ];
then GIT_AUTHOR_EMAIL=correct@email;
fi;
export GIT_AUTHOR_EMAIL' HEAD~20..HEAD
Edit: It seems like new installers do not have this problem anymore, see this answer by Parag Meshram as my answer is likely obsolete now.
Original answer:
Follow these steps, closely:
C:\Program Files\nodejs
PATH
and choose to edit it.If the PATH variable is empty
, change it to this: C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs
If the PATH variable already contains C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm
, append the following right after: ;C:\Program Files\nodejs
If the PATH variable contains information, but nothing regarding npm, append this to the end of the PATH: ;C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs
Now that the PATH variable is set correctly, you will still encounter errors. Manually go into the AppData directory and you will find that there is no npm directory inside Roaming. Manually create this directory.
Re-start the command prompt and npm will now work.
This post asked a similar question and used LINQ to solve it, maybe it will help you out too.
string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
mysql->SHOW PROCESSLIST;
kill xxxx;
and then kill which one in sleep. In my case it is 2456.
No need to get too complicated, try this one liner:
String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
$(document).ready(function() {
$('td').on('click', function() {
var value = $this.text();
});
});
I have tested it (Chrome) and it working for me( both [^]
and [^\0]
), by changing the dot (.
) by either [^\0]
or [^]
, because dot doesn't match line break (See here: http://www.regular-expressions.info/dot.html).
var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";_x000D_
var arr= ss.match( /<pre[^\0]*?<\/pre>/gm );_x000D_
alert(arr); //Working
_x000D_
start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"
You may try this, I did it finally, it works!
Swift 3/4
Custom separator line, put this code in a custom cell that's a subclass of UITableViewCell(or in CellForRow or WillDisplay TableViewDelegates for non custom cell):
let separatorLine = UIView.init(frame: CGRect(x: 8, y: 64, width: cell.frame.width - 16, height: 2))
separatorLine.backgroundColor = .blue
addSubview(separatorLine)
in viewDidLoad method:
tableView.separatorStyle = .none
MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.
While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.
I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.
MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.
I would still recommend Firebug. Not only it can debug JS within your JSP files, it can enhance debugging experience with addons like JS Deminifier
(if your production JS is minified), FireQuery
, FireRainbow
and more.
There is also Firebug lite which is nothing but a bookmarklet. It lets you do limited things but still is useful.
Chrome as a developer console built-in that would let you modify javascript.
Using these tools, you should be able to inject your own JS too.
I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:
public class RoomService {
public Room findByName(String roomName) {...}
public void persist(Room room) {...}
}
The service mock uses a map to store the Room instances.
RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();
// mock for method persist
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
Room room = (Room) arguments[0];
roomMap.put(room.getName(), room);
}
return null;
}
}).when(roomService).persist(any(Room.class));
// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
@Override
public Room answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
String key = (String) arguments[0];
if (roomMap.containsKey(key)) {
return roomMap.get(key);
}
}
return null;
}
});
We can now run our tests on this mock. For example:
String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));
If you have an Activity
object hanging around, you can use the isDestroyed()
method:
Activity activity;
// ...
if (!activity.isDestroyed()) {
// ...
}
This is nice if you have a non-anonymous AsyncTask
subclass that you use in various places.
If you really want to cover the case that a script is called via execfile(...)
, you can use the inspect
module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed:
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
A good example of real time found from here:-
A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.
A business example:
I have a persistance engine that will work against any data sourcer (XML, ASCII (delimited and fixed-length), various JDBC sources (Oracle, SQL, ODBC, etc.) I created a base, abstract class to provide common functionality in this persistance, but instantiate the appropriate "Port" (subclass) when persisting my objects. (This makes development of new "Ports" much easier, since most of the work is done in the superclasses; especially the various JDBC ones; since I not only do persistance but other things [like table generation], I have to provide the various differences for each database.) The best business examples of Interfaces are the Collections. I can work with a java.util.List without caring how it is implemented; having the List as an abstract class does not make sense because there are fundamental differences in how anArrayList works as opposed to a LinkedList. Likewise, Map and Set. And if I am just working with a group of objects and don't care if it's a List, Map, or Set, I can just use the Collection interface.
///
/// Convert a color hex-string to a Color object.
///
Color getColorFromHex(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll('#', '');
if (hexColor.length == 6) {
hexColor = 'FF' + hexColor;
}
return Color(int.parse(hexColor, radix: 16));
}
Text(
'hello world',
style: TextStyle(
color: getColorFromHex('#aabbcc'),
fontWeight: FontWeight.bold,
)
)
An example of using logging.basicConfig
rather than logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
self.logger = logging.getLogger('urbanGUI')
In order, the five parts do the following:
filename=logname
)filemode='a'
)format=...
)datefmt='%H:%M:%S'
)level=logging.DEBUG
).Cstr()
is compiled inline for better performance.
CType
allows for casts between types if a conversion operator is defined
ToString()
Between base type and string throws an exception if conversion is not possible.
TryParse()
From String to base typeif
possible otherwise returns false
DirectCast
used if the types are related via inheritance or share a common interface , will throw an exception if the cast is not possible, trycast
will return nothing in this instance
$url = "https://chart.googleapis....";
$json = file_get_contents($url);
Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:
$data = json_decode($json);
var_dump($data);
For Firefox, Chrome, Opera, Internet Explorer and Safari
var ua="Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)";
//ua = navigator.userAgent;
var b;
var browser;
if(ua.indexOf("Opera")!=-1) {
b=browser="Opera";
}
if(ua.indexOf("Firefox")!=-1 && ua.indexOf("Opera")==-1) {
b=browser="Firefox";
// Opera may also contains Firefox
}
if(ua.indexOf("Chrome")!=-1) {
b=browser="Chrome";
}
if(ua.indexOf("Safari")!=-1 && ua.indexOf("Chrome")==-1) {
b=browser="Safari";
// Chrome always contains Safari
}
if(ua.indexOf("MSIE")!=-1 && (ua.indexOf("Opera")==-1 && ua.indexOf("Trident")==-1)) {
b="MSIE";
browser="Internet Explorer";
//user agent with MSIE and Opera or MSIE and Trident may exist.
}
if(ua.indexOf("Trident")!=-1) {
b="Trident";
browser="Internet Explorer";
}
// now for version
var version=ua.match(b+"[ /]+[0-9]+(.[0-9]+)*")[0];
console.log("broswer",browser);
console.log("version",version);
function Parent() {_x000D_
const [Name, setName] = useState("");_x000D_
getChildChange = getChildChange.bind(this);_x000D_
function getChildChange(value) {_x000D_
setName(value);_x000D_
}_x000D_
_x000D_
return <div> {Name} :_x000D_
<Child getChildChange={getChildChange} ></Child>_x000D_
</div>_x000D_
}_x000D_
_x000D_
function Child(props) {_x000D_
const [Name, setName] = useState("");_x000D_
handleChange = handleChange.bind(this);_x000D_
collectState = collectState.bind(this);_x000D_
_x000D_
function handleChange(ele) {_x000D_
setName(ele.target.value);_x000D_
}_x000D_
_x000D_
function collectState() {_x000D_
return Name;_x000D_
}_x000D_
_x000D_
useEffect(() => {_x000D_
props.getChildChange(collectState());_x000D_
});_x000D_
_x000D_
return (<div>_x000D_
<input onChange={handleChange} value={Name}></input>_x000D_
</div>);_x000D_
}
_x000D_
useEffect
act as componentDidMount, componentDidUpdate, so after updating state it will work
Below is an image showing nested frames and the effect of different target values, followed by an explanation of the image.
Imagine a webpage containing 3 nested <iframe>
aka "frame"/"frameset". So:
Then target attributes have these effects:
target="_self"
, the link targets frame 1 (i.e. the link targets the frame containing the link (i.e. targets itself))target="_parent"
, the link targets frame 2 (i.e. the link targets the parent frame)target="_top"
, the link targets the initial webpage (i.e. the link targets the topmost/outermost frame; (in this case; the link skips past the grandparent frame 3))
target="_top"
, the link also targets the initial webpage (i.e. again, the link targets the topmost/outermost frame)target="_blank"
, the link targets an auxiliary browsing context, aka a "new window"/"new tab"
target="_blank"
; use the rel="noopener"
attributeIn simple word you can understand that whenever page load, by this second pair of brackets () function will have called default.We need not call the function.It is known as anonymous function.
i.e.
(function(a,b){
//Do your code here
})(1,2);
It same like as
var test = function(x,y) {
// Do your code here
}
test(1,2);
The given answer wont always work. If it does not fix your issue. Make sure that you are also using the correct symbol in your package.json
. This is very important to fix that headache. For example:
warning " > @angular/[email protected]" has incorrect peer dependency "typescript@>=2.4.2 <2.7".
warning " > [email protected]" has incorrect peer dependency "typescript@>=2.4.2 <2.6".
So my typescript needs to be between 2.4.2 and 2.6 right?
So I changed my typescript library from using "typescript": "^2.7"
to using "typescript": "^2.5"
. Seems correct?
Wrong.
The ^
means that you are okay with npm using "typescript": "2.5"
or "2.6"
or "2.7"
etc...
If you want to learn what the ^
and ~
it mean see: What's the difference between tilde(~) and caret(^) in package.json?
Also you have to make sure that the package exists. Maybe there is no "typescript": "2.5.9"
look up the package numbers. To be really safe just remove the ~
or the ^
if you dont want to read what they mean.
this
on a C++ compilerThe C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf
instead of print
. this->printf
would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this
.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
Assuming you start with variables:
int i=12;
int j=12;
This will give output 1212
:
System.out.print(i+""+j);
And this will give output 24
:
System.out.print(i+j);
If you installed SQL Server with the default collation options, you might find that the following queries return the same results:
CREATE TABLE mytable
(
mycolumn VARCHAR(10)
)
GO
SET NOCOUNT ON
INSERT mytable VALUES('Case')
GO
SELECT mycolumn FROM mytable WHERE mycolumn='Case'
SELECT mycolumn FROM mytable WHERE mycolumn='caSE'
SELECT mycolumn FROM mytable WHERE mycolumn='case'
You can alter your query by forcing collation at the column level:
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'caSE'
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'case'
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'Case'
-- if myColumn has an index, you will likely benefit by adding
-- AND myColumn = 'case'
SELECT DATABASEPROPERTYEX('<database name>', 'Collation')
As changing this setting can impact applications and SQL queries, I would isolate this test first. From SQL Server 2000, you can easily run an ALTER TABLE statement to change the sort order of a specific column, forcing it to be case sensitive. First, execute the following query to determine what you need to change it back to:
EXEC sp_help 'mytable'
The second recordset should contain the following information, in a default scenario:
Column_Name Collation
mycolumn SQL_Latin1_General_CP1_CI_AS
Whatever the 'Collation' column returns, you now know what you need to change it back to after you make the following change, which will force case sensitivity:
ALTER TABLE mytable
ALTER COLUMN mycolumn VARCHAR(10)
COLLATE Latin1_General_CS_AS
GO
SELECT mycolumn FROM mytable WHERE mycolumn='Case'
SELECT mycolumn FROM mytable WHERE mycolumn='caSE'
SELECT mycolumn FROM mytable WHERE mycolumn='case'
If this screws things up, you can change it back, simply by issuing a new ALTER TABLE statement (be sure to replace my COLLATE identifier with the one you found previously):
ALTER TABLE mytable
ALTER COLUMN mycolumn VARCHAR(10)
COLLATE SQL_Latin1_General_CP1_CI_AS
If you are stuck with SQL Server 7.0, you can try this workaround, which might be a little more of a performance hit (you should only get a result for the FIRST match):
SELECT mycolumn FROM mytable WHERE
mycolumn = 'case' AND
CAST(mycolumn AS VARBINARY(10)) = CAST('Case' AS VARBINARY(10))
SELECT mycolumn FROM mytable WHERE
mycolumn = 'case' AND
CAST(mycolumn AS VARBINARY(10)) = CAST('caSE' AS VARBINARY(10))
SELECT mycolumn FROM mytable WHERE
mycolumn = 'case' AND
CAST(mycolumn AS VARBINARY(10)) = CAST('case' AS VARBINARY(10))
-- if myColumn has an index, you will likely benefit by adding
-- AND myColumn = 'case'
It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).
BTW gdb
watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.
The standard way to add Multiple functions
<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>
or
<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>
It sounds like you need to set up passwordless sudo. Try:
%admin ALL=(ALL) NOPASSWD: osascript myscript.scpt
Also comment out the following line (in /etc/sudoers via visudo), if it is there:
Defaults requiretty
When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.
However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.
Tomcat itself has size limit for each port, and this is defined in conf\server.xml
. This is controlled by maxPostSize
attribute of each Connector
(port). If this attribute does not exist, which it is by default, there is no limit on the request size.
To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="209715200" />
After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.
To set limit through java annotation
@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// ...
}
}
To set limit through web.xml
<web-app>
...
<servlet>
...
<multipart-config>
<file-size-threshold>0</file-size-threshold>
<max-file-size>209715200</max-file-size>
<max-request-size>209715200</max-request-size>
</multipart-config>
...
</servlet>
...
</web-app>
Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml
configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml
and follow the above guide to change the size limit and finally restart tomcat.
I guess this is what you want:
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
(You need to escape the "\" in your string (turning it into a double-"\"), otherwise it will become a newline in the JSON source, not the JSON data.)
If the object implements IDisposable
, then yes, you should dispose it. The object could be hanging on to native resources (file handles, OS objects) that might not be freed immediately otherwise. This can lead to resource starvation, file-locking issues, and other subtle bugs that could otherwise be avoided.
See also Implementing a Dispose Method on MSDN.
<form (submit)="onSubmit()">
<input [(ngModel)]="playerName">
</form>
let playerName: string;
onSubmit() {
return this.playerName;
}
I solved this problem by enabling WCF Services
Programs and Features > NET Framework 4.5 Services > WCF Services> HTTP Activation node
But you have to admit it guys this ENTIRE IIS setup configure/guess/trial and see/try this/try that spends 4 or 5 of our days trying to find a solution around approach IS A COMPLETE AND UTTER JOKE.
SURELY, 'IIS' IS THE BIGGEST CONFIDENCE TRICK EVER PLAYED ON MANKIND TO DATE
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)Use combinations of these to get the desired result:
Set Anchor
property to None, the controls will not be resized, they only shift their position.
Set Anchor
property to Top+Bottom+Left+Right, the controls will be resized but they don't change their position.
Set the Minimum Size
of the form to a proper value.
Set Dock
property.
Use Form Resize
event to change whatever you want
I don't know how font size (label, textbox, combobox, etc.) will be affected in (1) - (4), but it can be controlled in (5).
Apart from other answer There are calculator provided by Youtube to check your usage. It is good to identify your usage. https://developers.google.com/youtube/v3/determine_quota_cost
CSS :
ul{
list-style-type:none;
}
You can take a look at W3School
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
IF NOT EXISTS(SELECT * FROM Clock
WHERE clockDate = '08/10/2012') AND userName = 'test')
Has an extra parenthesis. I think it's fine if you remove it:
IF NOT EXISTS(SELECT * FROM Clock WHERE
clockDate = '08/10/2012' AND userName = 'test')
Also, GETDATE() will put the current date in the column, though if you don't want the time you'll have to play a little. I think CONVERT(varchar(8), GETDATE(), 112) would give you just the date (not time) portion.
IF NOT EXISTS(SELECT * FROM Clock WHERE
clockDate = CONVERT(varchar(8), GETDATE(), 112)
AND userName = 'test')
should probably do it.
PS: use a merge statement :)
You can always wrap Double.parseDouble() in a try catch block.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
This usually happens when you update the java, the easiest way to solve this is to just uninstall the JDK & then reinstall it. NOTE: This doesnt remove the path or classpath so no need to worry.
In the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler
interface.
ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
ASP.NET offers a few default HTTP handlers:
You can create your own custom HTTP handlers that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example
You implement the IHttpHandler
interface to create a synchronous handler and the IHttpAsyncHandler
interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest
method and the IsReusable
property.
The ProcessRequest
method handles the actual processing for requests made, while the Boolean IsReusable
property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.
Try:
gradle assemble
To list all available tasks for your project, try:
gradle tasks
UPDATE:
This may not seem the most correct answer at first, but read carefully gradle tasks
output or docs.
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
You can use the for command:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
Type
for /?
at the command prompt. Also, you can parse ini files!
{ thetop : 10 }
is a valid object literal. The code will create an object with a property named thetop
that has a value of 10. Both the following are the same:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
var thetop = "top";
// create the object literal
var aniArgs = {};
// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;
// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
You can use this new syntax in the latest versions of each mainstream browser.
e.preventDefault() works fine only if you dont have problem on your javascripts, check your javascripts if e.preventDefault() doesn't work chances are some other parts of your JS doesn't work also
SELECT p.*, f.Fear
FROM Persons p
LEFT JOIN Person_Fear pf ON pf.PersonID = p.PersonID
LEFT JOIN Fears f ON f.FearID = pf.FearID
ORDER BY p.PersonID
Persons
table to ensure you generate a row for every person, whether they have fears or not.Person_Fear
to every person, which will just be NULL
if they don't have any entries (as you want).Fears
on Person_Fear
so that you can select the name of the fear.Person_Fear
table at different times.Yes, I wrote a little groovy script which does the trick You should add a 'Dynamic Choice Parameter' to your job and customize the following groovy script to your needs :
#!/usr/bin/groovy
def gitURL = "git repo url"
def command = "git ls-remote --heads --tags ${gitURL}"
def proc = command.execute()
proc.waitFor()
if ( proc.exitValue() != 0 ) {
println "Error, ${proc.err.text}"
System.exit(-1)
}
def text = proc.in.text
# put your version string match
def match = /<REGEX>/
def tags = []
text.eachMatch(match) { tags.push(it[1]) }
tags.unique()
tags.sort( { a, b ->
def a1 = a.tokenize('._-')
def b1 = b.tokenize('._-')
try {
for (i in 1..<[a1.size(), b1.size()].min()) {
if (a1[i].toInteger() != b1[i].toInteger()) return a1[i].toInteger() <=> b1[i].toInteger()
}
return 1
} catch (e) {
return -1;
}
} )
tags.reverse()
I my case the version string was in the following format X.X.X.X and could have user branches in the format X.X.X-username ,etc... So I had to write my own sort function. This was my first groovy script so if there are better ways of doing thing I would like to know.
When using matplotlib.pyplot
, you must first save your plot and then close it using these 2 lines:
fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED
as @INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.
You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;
you can find all the documentation at http://getbootstrap.com/css.
If you really want to do this, create an HttpServletRequestWrapper.
public class AddableHttpRequest extends HttpServletRequestWrapper {
private HashMap params = new HashMap();
public AddableingHttpRequest(HttpServletRequest request) {
super(request);
}
public String getParameter(String name) {
// if we added one, return that one
if ( params.get( name ) != null ) {
return params.get( name );
}
// otherwise return what's in the original request
HttpServletRequest req = (HttpServletRequest) super.getRequest();
return validate( name, req.getParameter( name ) );
}
public void addParameter( String name, String value ) {
params.put( name, value );
}
}
First of all, with regards to FormatType.JSON: JSON is not a member of FormatType, it's a possible value of the type. FormatType isn't even a composite type — it's a scalar.
Second, the only way to do this is to create a mapping table. The more common way to do this in Objective-C is to create a series of constants referring to your "symbols", so you'd have NSString *FormatTypeJSON = @"JSON"
and so on.
Here is mine solution (hope it is plug-n-play enough too):
// SlideAlongScroll_x000D_
var SlideAlongScroll = function(el) {_x000D_
var _this = this;_x000D_
this.el = el;_x000D_
// elements original position_x000D_
this.elpos_original = el.parent().offset().top; _x000D_
// scroller timeout_x000D_
this.scroller_timeout;_x000D_
// scroller calculate function_x000D_
this.scroll = function() {_x000D_
// 20px gap for beauty_x000D_
var windowpos = $(window).scrollTop() + 20;_x000D_
// targeted destination_x000D_
var finaldestination = windowpos - this.elpos_original;_x000D_
// define stopper object and correction amount_x000D_
var stopper = ($('.footer').offset().top); // $(window).height() if you dont need it_x000D_
var stophere = stopper - el.outerHeight() - this.elpos_original - 20;_x000D_
// decide what to do_x000D_
var realdestination = 0;_x000D_
if(windowpos > this.elpos_original) {_x000D_
if(finaldestination >= stophere) {_x000D_
realdestination = stophere;_x000D_
} else {_x000D_
realdestination = finaldestination;_x000D_
}_x000D_
}_x000D_
el.css({'top': realdestination });_x000D_
};_x000D_
// scroll listener_x000D_
$(window).on('scroll', function() {_x000D_
// debounce it_x000D_
clearTimeout(_this.scroller_timeout);_x000D_
// set scroll calculation timeout_x000D_
_this.scroller_timeout = setTimeout(function() { _this.scroll(); }, 300);_x000D_
});_x000D_
// initial position (in case page is pre-scrolled by browser after load)_x000D_
this.scroll();_x000D_
};_x000D_
// init action, little timeout for smoothness_x000D_
$(document).ready(function() {_x000D_
$('.slide-along-scroll').each(function(i, el) {_x000D_
setTimeout(function(el) { new SlideAlongScroll(el); }, 300, $(el));_x000D_
});_x000D_
});
_x000D_
/* part you need */_x000D_
.slide-along-scroll {_x000D_
padding: 20px;_x000D_
background-color: #CCCCCC;_x000D_
transition: top 300ms ease-out;_x000D_
position: relative;_x000D_
}_x000D_
/* just demo */_x000D_
div { _x000D_
box-sizing: border-box;_x000D_
}_x000D_
.side-column {_x000D_
float: left;_x000D_
width: 20%; _x000D_
}_x000D_
.main-column {_x000D_
padding: 20px;_x000D_
float: right;_x000D_
width: 75%;_x000D_
min-height: 1200px;_x000D_
background-color: #EEEEEE;_x000D_
}_x000D_
.body { _x000D_
padding: 20px 0; _x000D_
}_x000D_
.body:after {_x000D_
content: ' ';_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
.header {_x000D_
padding: 20px;_x000D_
text-align: center;_x000D_
border-bottom: 2px solid #CCCCCC; _x000D_
}_x000D_
.footer {_x000D_
padding: 20px;_x000D_
border-top: 2px solid #CCCCCC;_x000D_
min-height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="header">_x000D_
<h1>Your super-duper website</h1>_x000D_
</div>_x000D_
<div class="body"> _x000D_
<div class="side-column">_x000D_
<!-- part you need -->_x000D_
<div class="slide-along-scroll">_x000D_
Side menu content_x000D_
<ul>_x000D_
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>_x000D_
<li>Aliquam tincidunt mauris eu risus.</li>_x000D_
<li>Vestibulum auctor dapibus neque.</li>_x000D_
</ul> _x000D_
</div>_x000D_
</div>_x000D_
<div class="main-column">_x000D_
Main content area (1200px)_x000D_
</div>_x000D_
</div>_x000D_
<div class="footer">_x000D_
Footer (slide along is limited by it)_x000D_
</div>_x000D_
</div>
_x000D_
public class Person{
String s;
Date d;
...
public Person clone(){
Person p = new Person();
p.s = this.s.clone();
p.d = this.d.clone();
...
return p;
}
}
In your executing code:
ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
clone.add(p.clone());
See if you have a file located under /etc/my.cnf
. If so, it should tell you where the data directory is.
For example:
[mysqld]
set-variable=local-infile=0
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
...
My guess is that your mysql might be installed to /usr/local/mysql-XXX.
You may find these MySQL reference manual links useful:
I eventually figured it out. Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py
. I'm leaving this question and answer for the record in case anyone else comes across the same issue.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
I got this error writing a Jasmine unit test. I had the line:
angular.injector(['myModule'])
It needed to be:
angular.injector(['ng', 'myModule'])
I actually found an extension method that will do what I want nicely
public static IEnumerable<T> ForEach<T>(
this IEnumerable<T> source,
Action<T> act)
{
foreach (T element in source) act(element);
return source;
}
There are two solutions for this are :-
(1) do not put onClick in xml
(2) remove
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
and put
public void setLogin(View v) {
// Your code here
}
Better way to reset your form with jQuery is Simply trigger
a reset
event on your form.
$("#btn1").click(function () {
$("form").trigger("reset");
});
In case of :
<?xml version="1.0" encoding="iso-8859-1"?>
<info xmlns="http://namespaces.default" xmlns:ns2="http://namespaces.ns2" >
<id> 954 </id>
<idboss> 954 </idboss>
<name> Fausto </name>
<sorname> Anonimo </sorname>
<phone> 040000000 </phone>
<fax> 040000001 </fax>
</info>
Query :
Select *
from xmltable(xmlnamespaces(default 'http://namespaces.default'
'http://namespaces.ns2' as "ns",
),
'/info'
passing xmltype.createxml(xml)
columns id varchar2(10) path '/id',
idboss varchar2(500) path '/idboss',
etc....
) nice_xml_table
Probably the author won't need my answer anymore. Still, for sake of completeness i feel other users might find it useful. The best and most simple solution is to use $(window).load()
inside the body of the returned function. (alternatively you can use document.ready
. It really depends if you need all the images or not).
Using $timeout
in my humble opinion is a very weak option and may fail in some cases.
Here is the complete code i'd use:
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function($scope, $elem, attrs){
$(window).load(function() {
//...JS here...
});
}
}
});
This can also happen when trying to throw an ArgumentException
where you inadvertently call the ArgumentException
constructor overload
public static void Dostuff(Foo bar)
{
// this works
throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));
//this gives the error
throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);
}
var myEle = document.getElementById("myElement");
if(myEle){
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
If it's bigin when you try to acces to joomla administrator panel, Just a username and password problem !! You have just to update a jos_user in your joomla database.
Go to your joomla web site directory and open a configuration.php with bloc note or note pad to show what database name your joomla administrator site use. You have to find a line who have:
public $user = 'joomlauser251'; //MySQL username
In my case joomlauser251
is my DB name.
Login to your mysql:
mysql -uyourusername -pyourpassword
Select database for your joomla:
use joomlauser251;
Change password for admin:
UPDATE jos_users SET password=MD5(‘NewPassword’) WHERE username=’admin’;
And retry to acces again.
That’s all !!!
Now you can use the pluck
method on a Collection
instance:
This will return only the uuid
attribute of the Post model
App\Models\User::find(2)->posts->pluck('uuid')
=> Illuminate\Support\Collection {#983
all: [
"1",
"2",
"3",
],
}
This might not be the most useful answer, more of an addendum, but the above answer (from greenkode) confused me for all of 10 seconds.
"Add Folder" only lets you see folders that are the sub-folders of the project whose build path you are looking at.
The "Link Source" button in the above image would be called "Add External Folder" in an ideal world.
I had to make a properties file that is to be shared between multiple projects, and by keeping the properties file in an external folder, I am able to have only one, instead of having a copy in each project.
Let's start with this small df:
import pandas as pd
import time as tm
import numpy as np
n=10
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
We'll so have
df
Out[25]:
0 1 2 3 4 5 6 7 8 9
0 0 1 2 3 4 5 6 7 8 9
1 10 11 12 13 14 15 16 17 18 19
2 20 21 22 23 24 25 26 27 28 29
3 30 31 32 33 34 35 36 37 38 39
4 40 41 42 43 44 45 46 47 48 49
5 50 51 52 53 54 55 56 57 58 59
6 60 61 62 63 64 65 66 67 68 69
7 70 71 72 73 74 75 76 77 78 79
8 80 81 82 83 84 85 86 87 88 89
9 90 91 92 93 94 95 96 97 98 99
With this we have:
df.iloc[3,3]
Out[33]: 33
df.iat[3,3]
Out[34]: 33
df.iloc[:3,:3]
Out[35]:
0 1 2 3
0 0 1 2 3
1 10 11 12 13
2 20 21 22 23
3 30 31 32 33
df.iat[:3,:3]
Traceback (most recent call last):
... omissis ...
ValueError: At based indexing on an integer index can only have integer indexers
Thus we cannot use .iat for subset, where we must use .iloc only.
But let's try both to select from a larger df and let's check the speed ...
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 7 09:58:39 2018
@author: Fabio Pomi
"""
import pandas as pd
import time as tm
import numpy as np
n=1000
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
t1=tm.time()
for j in df.index:
for i in df.columns:
a=df.iloc[j,i]
t2=tm.time()
for j in df.index:
for i in df.columns:
a=df.iat[j,i]
t3=tm.time()
loc=t2-t1
at=t3-t2
prc = loc/at *100
print('\nloc:%f at:%f prc:%f' %(loc,at,prc))
loc:10.485600 at:7.395423 prc:141.784987
So with .loc we can manage subsets and with .at only a single scalar, but .at is faster than .loc
:-)
On macOS (El Capitan). You can simply use: brew install postgresql
overload operator<<:
template<typename OutStream, typename T>
OutStream& operator<< (OutStream& out, const vector<T>& v)
{
for (auto const& tmp : v)
out << tmp << " ";
out << endl;
return out;
}
Usage:
vector <int> test {1,2,3};
wcout << test; // or any output stream
Create a file named .gitignore
in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):
dir_to_ignore/
More information is here.
GroupBox
is better.But not only group box, even you can use Panels
(System.Windows.Forms.Panel
).
I found out that my back-up project worked well if I precompile without bundle update
. Maybe something went wrong with gem updated but I don't know which gem has an error.
This is not a fix, but in my case, I had multiple RN apps installed on my device and I was unknowingly attempting to 'Reload` from within the wrong application. (I'm developing two apps simultaneously at the moment) So make sure you're in the correct application!
An important point is to consider if you perform tasks based on difference between 2 timestamps because you will get odd behavior if you generate it with gettimeofday()
, and even clock_gettime(CLOCK_REALTIME,..)
at the moment where you will set the time of your system.
To prevent such problem, use clock_gettime(CLOCK_MONOTONIC_RAW, &tms)
instead.
If you're in a situation like @Keith you could try:
print(a.__dict__)
It goes against what I would consider good style but if you're just trying to debug then it should do what you want.
If empName is a VARCHAR(50) column:
ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;
EDIT
Per the comments, you can also do this:
ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;
Note that the repetition of empName
is deliberate. You have to tell MySQL that you want to keep the same column name.
You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.
Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER
modifier. The above examples just have VARCHAR(50)
, but if you need other characteristics (such as NOT NULL
or a default value) you need to include those as well. Consult the docs on ALTER TABLE
for more info.
From the Java Language Specification - 15.26.2 Compound Assignment Operators.
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
So a &= b;
is equivalent to a = a & b;
.
(In some usages, the type-casting makes a difference to the result, but in this one b
has to be boolean
and the type-cast does nothing.)
And, for the record, a &&= b;
is not valid Java. There is no &&=
operator.
In practice, there is little semantic difference between a = a & b;
and a = a && b;
. (If b
is a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference when b
is a subexpression that has side-effects. In the &
case, the side-effect always occurs. In the &&
case it occurs depending on the value of a
.)
On the performance side, the trade-off is between the cost of evaluating b
, and the cost of a test and branch of the value of a
, and the potential saving of avoiding an unnecessary assignment to a
. The analysis is not straight-forward, but unless the cost of calculating b
is non-trivial, the performance difference between the two versions is too small to be worth considering.
Use doubleValue method present in BigDecimal class :
double doubleValue()
Converts this BigDecimal
to a double
.
sth's solution didn't work for me
because in ...
Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension
It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case
You can bypass the format detection by setting the format yourself in a parameter
import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()
I faced the same issue, I tried the below solution and it worked for me
In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."
In case of Allow IP to mysql server linux machine. you can do following command--
nano /etc/httpd/conf.d/phpMyAdmin.conf and add Desired IP.
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
Order allow,deny
allow from all
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
Require ip 192.168.9.1(Desired IP)
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
#Allow from All
Allow from 192.168.9.1(Desired IP)
</IfModule>
And after Update, please restart using following command--
sudo systemctl restart httpd.service
Seems a current version of the purrr
(0.2.2) package is the fastest solution:
by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out
Let's compare the most interesting solutions:
data("Batting", package = "Lahman")
x <- Batting[1:10000, 1:10]
library(benchr)
library(purrr)
benchmark(
split = split(x, seq_len(.row_names_info(x, 2L))),
mapply = .mapply(function(...) structure(list(...), class = "data.frame", row.names = 1L), x, NULL),
purrr = by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out
)
Rsults:
Benchmark summary:
Time units : milliseconds
expr n.eval min lw.qu median mean up.qu max total relative
split 100 983.0 1060.0 1130.0 1130.0 1180.0 1450 113000 34.3
mapply 100 826.0 894.0 963.0 972.0 1030.0 1320 97200 29.3
purrr 100 24.1 28.6 32.9 44.9 40.5 183 4490 1.0
Also we can get the same result with Rcpp
:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List df2list(const DataFrame& x) {
std::size_t nrows = x.rows();
std::size_t ncols = x.cols();
CharacterVector nms = x.names();
List res(no_init(nrows));
for (std::size_t i = 0; i < nrows; ++i) {
List tmp(no_init(ncols));
for (std::size_t j = 0; j < ncols; ++j) {
switch(TYPEOF(x[j])) {
case INTSXP: {
if (Rf_isFactor(x[j])) {
IntegerVector t = as<IntegerVector>(x[j]);
RObject t2 = wrap(t[i]);
t2.attr("class") = "factor";
t2.attr("levels") = t.attr("levels");
tmp[j] = t2;
} else {
tmp[j] = as<IntegerVector>(x[j])[i];
}
break;
}
case LGLSXP: {
tmp[j] = as<LogicalVector>(x[j])[i];
break;
}
case CPLXSXP: {
tmp[j] = as<ComplexVector>(x[j])[i];
break;
}
case REALSXP: {
tmp[j] = as<NumericVector>(x[j])[i];
break;
}
case STRSXP: {
tmp[j] = as<std::string>(as<CharacterVector>(x[j])[i]);
break;
}
default: stop("Unsupported type '%s'.", type2name(x));
}
}
tmp.attr("class") = "data.frame";
tmp.attr("row.names") = 1;
tmp.attr("names") = nms;
res[i] = tmp;
}
res.attr("names") = x.attr("row.names");
return res;
}
Now caompare with purrr
:
benchmark(
purrr = by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out,
rcpp = df2list(x)
)
Results:
Benchmark summary:
Time units : milliseconds
expr n.eval min lw.qu median mean up.qu max total relative
purrr 100 25.2 29.8 37.5 43.4 44.2 159.0 4340 1.1
rcpp 100 19.0 27.9 34.3 35.8 37.2 93.8 3580 1.0
Two reasons to use integers for PK columns:
We can set identity for integer field which incremented automatically.
When we create PKs, the db creates an index (Cluster or Non Cluster) which sorts the data before it's stored in the table. By using an identity on a PK, the optimizer need not check the sort order before saving a record. This improves performance on big tables.
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin
is a method that detects if under current conditions admin privileges are required. If this returns false
the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
ngOnInit()
is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
ngAfterViewInit()
is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.
Edit the application tag in manifest file.
<application
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
Change the label attribute and give the latest name over there.
This code helped find my problem when I had issue with my Entity VAlidation Erros. It told me the exact problem with my Entity Definition. Try following code where you need to cover storeDB.SaveChanges(); in following try catch block.
try
{
if (TryUpdateModel(theEvent))
{
storeDB.SaveChanges();
return RedirectToAction("Index");
}
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
This way you can Create NSArray, NSMutableArray.
NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
Setting python.pythonPath
in VSCode's settings.json
file doesn't work for me, but another method does. According to the Anaconda documentation at Microsoft Visual Studio Code (VS Code):
When you launch VS Code from Navigator, VS Code is configured to use the Python interpreter in the currently selected environment.
Assuming you want to change the url to another within the same domain, you can use this:
history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');
You can use EL if you want to work as IF:
<h:outputLabel value="#{row==10? '10' : '15'}"/>
Changing styles or classes:
style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"
class="#{test eq testMB.test? 'divRred' : 'divGreen'}"
Just went to build.gradle
and deleted the line:
implementation 'com.android.support:appcompat-v7:26.1.0'
After that, I re-synced the Gradle. Then, I pasted the line of code back, re-synced the Gradle again and it worked.
Note: While I was making this changes, I also updated all the SDK Tools that needed update.
Regex: match everything but:
foo
):
world.
at the end):
foo
) (no POSIX compliant patern, sorry):
|
symbol):
foo
):
cat
): /cat(*SKIP)(*FAIL)|[^c]*(?:c(?!at)[^c]*)*/i
or /cat(*SKIP)(*FAIL)|(?:(?!cat).)+/is
(cat)|[^c]*(?:c(?!at)[^c]*)*
(or (?s)(cat)|(?:(?!cat).)*
, or (cat)|[^c]+(?:c(?!at)[^c]*)*|(?:c(?!at)[^c]*)+[^c]*
) and then check with language means: if Group 1 matched, it is not what we need, else, grab the match value if not empty[^a-z]+
(any char other than a lowercase ASCII letter)|
: [^|]+
Demo note: the newline \n
is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.
Anchor note: In many languages, use \A
to define the unambiguous start of string, and \z
(in Python, it is \Z
, in JavaScript, $
is OK) to define the very end of the string.
Dot note: In many flavors (but not POSIX, TRE, TCL), .
matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s
in PCRE/Boost/.NET/Python/Java and /m
in Ruby) for the .
to match any char including a newline.
Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n
for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\.
will be declared as "world\\."
, or use a character class: "world[.]"
). Use raw string literals (Python r'\bworld\b'
), C# verbatim string literals @"world\."
, or slashy strings/regex literal notations like /world\./
.
A survey of automatic memory leak checkers
In this answer, I compare several different memory leak checkers in a simple easy to understand memory leak example.
Before anything, see this huge table in the ASan wiki which compares all tools known to man: https://github.com/google/sanitizers/wiki/AddressSanitizerComparisonOfMemoryTools/d06210f759fec97066888e5f27c7e722832b0924
The example analyzed will be:
main.c
#include <stdlib.h>
void * my_malloc(size_t n) {
return malloc(n);
}
void leaky(size_t n, int do_leak) {
void *p = my_malloc(n);
if (!do_leak) {
free(p);
}
}
int main(void) {
leaky(0x10, 0);
leaky(0x10, 1);
leaky(0x100, 0);
leaky(0x100, 1);
leaky(0x1000, 0);
leaky(0x1000, 1);
}
We will try to see how clearly do the different tools point us to the leaky calls.
tcmalloc from gperftools by Google
https://github.com/gperftools/gperftools
Usage on Ubuntu 19.04:
sudo apt-get install google-perftools
gcc -ggdb3 -o main.out main.c -ltcmalloc
PPROF_PATH=/usr/bin/google-pprof \
HEAPCHECK=normal \
HEAPPROFILE=ble \
./main.out \
;
google-pprof main.out ble.0001.heap --text
The output of the program run contains the memory leak analysis:
WARNING: Perftools heap leak checker is active -- Performance may suffer
Starting tracking the heap
Dumping heap profile to ble.0001.heap (Exiting, 4 kB in use)
Have memory regions w/o callers: might report false leaks
Leak check _main_ detected leaks of 272 bytes in 2 objects
The 2 largest leaks:
Using local file ./main.out.
Leak of 256 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581d3 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
Leak of 16 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581b5 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
If the preceding stack traces are not enough to find the leaks, try running THIS shell command:
pprof ./main.out "/tmp/main.out.24744._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --gv
If you are still puzzled about why the leaks are there, try rerunning this program with HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with HEAP_CHECK_MAX_POINTER_OFFSET=-1
If the leak report occurs in a small fraction of runs, try running with TCMALLOC_MAX_FREE_QUEUE_SIZE of few hundred MB or with TCMALLOC_RECLAIM_MEMORY=false, it might help find leaks more re
Exiting with error code (instead of crashing) because of whole-program memory leaks
and the output of google-pprof
contains the heap usage analysis:
Using local file main.out.
Using local file ble.0001.heap.
Total: 0.0 MB
0.0 100.0% 100.0% 0.0 100.0% my_malloc
0.0 0.0% 100.0% 0.0 100.0% __libc_start_main
0.0 0.0% 100.0% 0.0 100.0% _start
0.0 0.0% 100.0% 0.0 100.0% leaky
0.0 0.0% 100.0% 0.0 100.0% main
The output points us to two of the three leaks:
Leak of 256 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581d3 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
Leak of 16 bytes in 1 objects allocated from:
@ 555bf6e5815d my_malloc
@ 555bf6e5817a leaky
@ 555bf6e581b5 main
@ 7f71e88c9b6b __libc_start_main
@ 555bf6e5808a _start
I'm not sure why the third one didn't show up
In any case, when usually when something leaks, it happens a lot of times, and when I used it on a real project, I just ended up being pointed out to the leaking function very easily.
As mentioned on the output itself, this incurs a significant execution slowdown.
Further documentation at:
See also: How To Use TCMalloc?
Tested in Ubuntu 19.04, google-perftools 2.5-2.
Address Sanitizer (ASan) also by Google
https://github.com/google/sanitizers
Previously mentioned at: How to find memory leak in a C++ code/project? TODO vs tcmalloc.
This is already integrated into GCC, so you can just do:
gcc -fsanitize=address -ggdb3 -o main.out main.c
./main.out
and execution outputs:
=================================================================
==27223==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 4096 byte(s) in 1 object(s) allocated from:
#0 0x7fabbefc5448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
#1 0x55bf86c5f17c in my_malloc /home/ciro/test/main.c:4
#2 0x55bf86c5f199 in leaky /home/ciro/test/main.c:8
#3 0x55bf86c5f210 in main /home/ciro/test/main.c:20
#4 0x7fabbecf4b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
Direct leak of 256 byte(s) in 1 object(s) allocated from:
#0 0x7fabbefc5448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
#1 0x55bf86c5f17c in my_malloc /home/ciro/test/main.c:4
#2 0x55bf86c5f199 in leaky /home/ciro/test/main.c:8
#3 0x55bf86c5f1f2 in main /home/ciro/test/main.c:18
#4 0x7fabbecf4b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
Direct leak of 16 byte(s) in 1 object(s) allocated from:
#0 0x7fabbefc5448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
#1 0x55bf86c5f17c in my_malloc /home/ciro/test/main.c:4
#2 0x55bf86c5f199 in leaky /home/ciro/test/main.c:8
#3 0x55bf86c5f1d4 in main /home/ciro/test/main.c:16
#4 0x7fabbecf4b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
SUMMARY: AddressSanitizer: 4368 byte(s) leaked in 3 allocation(s).
which clearly identifies all leaks. Nice!
ASan can also do other cool checks such as out-of-bounds writes: Stack smashing detected
Tested in Ubuntu 19.04, GCC 8.3.0.
Valgrind
Previously mentioned at: https://stackoverflow.com/a/37661630/895245
Usage:
sudo apt-get install valgrind
gcc -ggdb3 -o main.out main.c
valgrind --leak-check=yes ./main.out
Output:
==32178== Memcheck, a memory error detector
==32178== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==32178== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==32178== Command: ./main.out
==32178==
==32178==
==32178== HEAP SUMMARY:
==32178== in use at exit: 4,368 bytes in 3 blocks
==32178== total heap usage: 6 allocs, 3 frees, 8,736 bytes allocated
==32178==
==32178== 16 bytes in 1 blocks are definitely lost in loss record 1 of 3
==32178== at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==32178== by 0x10915C: my_malloc (main.c:4)
==32178== by 0x109179: leaky (main.c:8)
==32178== by 0x1091B4: main (main.c:16)
==32178==
==32178== 256 bytes in 1 blocks are definitely lost in loss record 2 of 3
==32178== at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==32178== by 0x10915C: my_malloc (main.c:4)
==32178== by 0x109179: leaky (main.c:8)
==32178== by 0x1091D2: main (main.c:18)
==32178==
==32178== 4,096 bytes in 1 blocks are definitely lost in loss record 3 of 3
==32178== at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==32178== by 0x10915C: my_malloc (main.c:4)
==32178== by 0x109179: leaky (main.c:8)
==32178== by 0x1091F0: main (main.c:20)
==32178==
==32178== LEAK SUMMARY:
==32178== definitely lost: 4,368 bytes in 3 blocks
==32178== indirectly lost: 0 bytes in 0 blocks
==32178== possibly lost: 0 bytes in 0 blocks
==32178== still reachable: 0 bytes in 0 blocks
==32178== suppressed: 0 bytes in 0 blocks
==32178==
==32178== For counts of detected and suppressed errors, rerun with: -v
==32178== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
So once again, all leaks were detected.
See also: How do I use valgrind to find memory leaks?
Tested in Ubuntu 19.04, valgrind 3.14.0.
Try this simple code:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int a[4], i, b;
printf("enter nos ");
for (i = 1; i <= 5; i++) {
scanf("%d", &a[i]);
}
for(i = 1; i <= 5; i++) {
printf("\n%d", a[i]);
}
printf("\nenter element you want to delete ");
scanf("%d", &b);
for (i = 1; i <= 5; i++) {
if(i == b) {
a[i] = i++;
}
printf("\n%d", a[i]);
}
getch();
}
Well there's no difference between the first two - they're just using different names for the type parameter (E
or T
).
The third isn't a valid declaration - ?
is used as a wildcard which is used when providing a type argument, e.g. List<?> foo = ...
means that foo
refers to a list of some type, but we don't know what.
All of this is generics, which is a pretty huge topic. You may wish to learn about it through the following resources, although there are more available of course:
Also remember that it must be:
#include "stdafx.h"
#include <iostream>
and not the other way around
#include <iostream>
#include "stdafx.h"
Simply change encoding of loaded file in IntelliJ IDEA IDE, on the right of status bar (bottom), where current charset is indicated. It prompts to Reload or Convert, use Convert. Make sure you backed up original file in advance.
Vinsa almost had it right you should add
<base href="{{URL::asset('/')}}" target="_top">
and scripts should go in their regular path
<script src="js/jquery/jquery-1.11.1.min.js"></script>
the reason for this is because Images and other things with relative path like image source or ajax requests won't work correctly without the base path attached.
Converting millis to datetime (UTC):
import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)
Converting datetime to string following the RFC3339 standard (used by Open API specification):
from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z
Brian Cauthon's answer is excellent! Just a little update, for EF 6, the class got moved to another namespace. So, before EF 6, you should include:
System.Data.Objects.SqlClient
If you update to EF 6, or simply are using this version, include:
System.Data.Entity.SqlServer
By including the incorrect namespace with EF6, the code will compile just fine but will throw a runtime error. I hope this note helps to avoid some confusion.
Wikipedia shows a nice string hash function called Jenkins One At A Time Hash. It also quotes improved versions of this hash.
uint32_t jenkins_one_at_a_time_hash(char *key, size_t len)
{
uint32_t hash, i;
for(hash = i = 0; i < len; ++i)
{
hash += key[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
As per my knowledge there is no BulkInsert
in EntityFramework
to increase the performance of the huge inserts.
In this scenario you can go with SqlBulkCopy in ADO.net
to solve your problem
Try to use getActivity();
This will solve your problem.
View randview = new View(getBaseContext());
randview = (View)findViewById(R.id.container);
randview.setBackgroundColor(Color.BLUE);
worked for me. thank you.
Put breakpoints - double click on the margin. Run > Debug > Yes (if dialog appears), then use commands from Run menu or shortcuts - F5, F6, F7, F8.
Try this:
public static void main(String[] args)
{
Pattern p = Pattern.compile("^\\d+$");
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
String temp;
Matcher numberMatcher;
System.out.print("Enter number 1: ");
try
{
num1 = kb.nextInt();
}
catch (java.util.InputMismatchException e)
{
System.out.println("Invalid Input");
//
return;
}
while(num2<num1)
{
System.out.print("Enter number 2: ");
temp = kb.next();
numberMatcher = p.matcher(temp);
if (numberMatcher.matches())
{
num2 = Integer.parseInt(temp);
}
else
{
System.out.println("Invalid Number");
}
}
}
You could try to parse the string into an int
as well, but usually people try to avoid throwing exceptions.
What I have done is that I have defined a regular expression that defines a number, \d
means a numeric digit. The +
sign means that there has to be one or more numeric digits. The extra \
in front of the \d
is because in java, the \
is a special character, so it has to be escaped.
You can also use Rest Assured library. For a demo with sample script, refer to http://artoftesting.com/automationTesting/restAPIAutomationGetRequest.html
My first impulse was to google for "php math" and I discovered that there's a core math library function called "round()" that likely is what you want.
I needed to convert a specific PDF to plain text within a python module. I used PDFMiner 20110515, after reading through their pdf2txt.py tool I wrote this simple snippet:
from cStringIO import StringIO
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
def to_txt(pdf_path):
input_ = file(pdf_path, 'rb')
output = StringIO()
manager = PDFResourceManager()
converter = TextConverter(manager, output, laparams=LAParams())
process_pdf(manager, converter, input_)
return output.getvalue()
Having
Clause is the easiest way to find duplicate entry in Oracle and using rowid
we can remove duplicate data..
DELETE FROM products WHERE rowid IN (
SELECT MAX(sl) FROM (
SELECT itemcode, (rowid) sl FROM products WHERE itemcode IN (
SELECT itemcode FROM products GROUP BY itemcode HAVING COUNT(itemcode)>1
)) GROUP BY itemcode);
I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.
According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.
According to their documentation, here's what you would send:
http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>
And here's what you would receive back:
<?xml version="1.0"?>
<CityStateLookupResponse>
<ZipCode ID="0">
<Zip5>90210</Zip5>
<City>BEVERLY HILLS</City>
<State>CA</State>
</ZipCode>
</CityStateLookupResponse>
USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.
Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here
This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:
GET http://ziptasticapi.com/48867
And they will return a JSON object along the lines of:
{"country": "US", "state": "MI", "city": "OWOSSO"}
Indeed, it works. You can test this from a command line by doing something like:
curl http://ziptasticapi.com/48867
Although this isn't using the np array format, (to lazy to modify my code) this should do what you want... If, you truly want a column vector you will want to transpose the vector result. It all depends on how you are planning to use this.
def getVector(data_array,col):
vector = []
imax = len(data_array)
for i in range(imax):
vector.append(data_array[i][col])
return ( vector )
a = ([1,2,3], [4,5,6])
b = getVector(a,1)
print(b)
Out>[2,5]
So if you need to transpose, you can do something like this:
def transposeArray(data_array):
# need to test if this is a 1D array
# can't do a len(data_array[0]) if it's 1D
two_d = True
if isinstance(data_array[0], list):
dimx = len(data_array[0])
else:
dimx = 1
two_d = False
dimy = len(data_array)
# init output transposed array
data_array_t = [[0 for row in range(dimx)] for col in range(dimy)]
# fill output transposed array
for i in range(dimx):
for j in range(dimy):
if two_d:
data_array_t[j][i] = data_array[i][j]
else:
data_array_t[j][i] = data_array[j]
return data_array_t
Hi you can use icon as SVG and set colors. See this code
/*_x000D_
* declare map and places as a global variable_x000D_
*/_x000D_
var map;_x000D_
var places = [_x000D_
['Place 1', "<h1>Title 1</h1>", -0.690542, -76.174856,"red"],_x000D_
['Place 2', "<h1>Title 2</h1>", -5.028249, -57.659052,"blue"],_x000D_
['Place 3', "<h1>Title 3</h1>", -0.028249, -77.757507,"green"],_x000D_
['Place 4', "<h1>Title 4</h1>", -0.800101286, -76.78747820,"orange"],_x000D_
['Place 5', "<h1>Title 5</h1>", -0.950198, -78.959302,"#FF33AA"]_x000D_
];_x000D_
/*_x000D_
* use google maps api built-in mechanism to attach dom events_x000D_
*/_x000D_
google.maps.event.addDomListener(window, "load", function () {_x000D_
_x000D_
/*_x000D_
* create map_x000D_
*/_x000D_
var map = new google.maps.Map(document.getElementById("map_div"), {_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP,_x000D_
});_x000D_
_x000D_
/*_x000D_
* create infowindow (which will be used by markers)_x000D_
*/_x000D_
var infoWindow = new google.maps.InfoWindow();_x000D_
/*_x000D_
* create bounds (which will be used auto zoom map)_x000D_
*/_x000D_
var bounds = new google.maps.LatLngBounds();_x000D_
_x000D_
/*_x000D_
* marker creater function (acts as a closure for html parameter)_x000D_
*/_x000D_
function createMarker(options, html) {_x000D_
var marker = new google.maps.Marker(options);_x000D_
bounds.extend(options.position);_x000D_
if (html) {_x000D_
google.maps.event.addListener(marker, "click", function () {_x000D_
infoWindow.setContent(html);_x000D_
infoWindow.open(options.map, this);_x000D_
map.setZoom(map.getZoom() + 1)_x000D_
map.setCenter(marker.getPosition());_x000D_
});_x000D_
}_x000D_
return marker;_x000D_
}_x000D_
_x000D_
/*_x000D_
* add markers to map_x000D_
*/_x000D_
for (var i = 0; i < places.length; i++) {_x000D_
var point = places[i];_x000D_
createMarker({_x000D_
position: new google.maps.LatLng(point[2], point[3]),_x000D_
map: map,_x000D_
icon: {_x000D_
path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",_x000D_
scale: 0.6,_x000D_
strokeWeight: 0.2,_x000D_
strokeColor: 'black',_x000D_
strokeOpacity: 1,_x000D_
fillColor: point[4],_x000D_
fillOpacity: 0.85,_x000D_
},_x000D_
}, point[1]);_x000D_
};_x000D_
map.fitBounds(bounds);_x000D_
});
_x000D_
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3"></script>_x000D_
<div id="map_div" style="height: 400px;"></div>
_x000D_
Locate the file at /etc/mysql/my.cnf
Edit the file by adding the following lines:
[mysqld]
lower_case_table_names=1
sudo /etc/init.d/mysql restart
Run mysqladmin -u root -p variables | grep table
to check that lower_case_table_names
is 1
now
You might need to recreate these tables to make it work.
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
Usefull Link for IE transform
This tool converts CSS3 Transform properties (which almost all modern browsers use) to the equivalent CSS using Microsoft's proprietary Visual Filters technology.
I also get this error quite often.
I solve this by modifying the code (doing a very small change), saving it, then building the solution again.
I think you have to be sure what type of installation you have binary or source. To check what binary packages is installed: with root rights execute following command:
dpkg -l |grep apache2
result should be something like:
dpkg -l |grep apache2
ii apache2 2.4.10-10+deb8u8 amd64 Apache HTTP Server
ii apache2-bin 2.4.10-10+deb8u8 amd64 Apache HTTP Server (modules and other binary files)
ii apache2-data 2.4.10-10+deb8u8 all Apache HTTP Server (common files)
ii apache2-doc 2.4.10-10+deb8u8 all Apache HTTP Server (on-site documentation)
To find version you can run :
apache2ctl -V |grep -i "Server version"
result should be something like: Server version: Apache/2.4.10 (Debian)
I tried to run insertion of random data into MyISAM and InnoDB tables. The result was quite shocking. MyISAM needed a few seconds less for inserting 1 million rows than InnoDB for just 10 thousand!
Not the best solution, but for those who are facing LazyInitializationException
especially on Serialization
this will help. Here you will check lazily initialized properties and setting null
to those. For that create the below class
public class RepositoryUtil {
public static final boolean isCollectionInitialized(Collection<?> collection) {
if (collection instanceof PersistentCollection)
return ((PersistentCollection) collection).wasInitialized();
else
return true;
}
}
Inside your Entity class which you are having lazily initialized properties add a method like shown below. Add all your lazily loading properties inside this method.
public void checkLazyIntialzation() {
if (!RepositoryUtil.isCollectionInitialized(yourlazyproperty)) {
yourlazyproperty= null;
}
Call this checkLazyIntialzation()
method after on all the places where you are loading data.
YourEntity obj= entityManager.find(YourEntity.class,1L);
obj.checkLazyIntialzation();
You will not able to convert it into data frame until you use implicit conversion.
val sqlContext = new SqlContext(new SparkContext())
import sqlContext.implicits._
After this only you can convert this to data frame
case class Test(id:String,filed2:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()
After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals
and then a bit farther down res.locals
held the answers I needed.
I discovered for myself that the function app.locals
takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals
, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.
So for my case in my app.js
what I did was add:
app.locals({
site: {
title: 'ExpressBootstrapEJS',
description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
},
author: {
name: 'Cory Gross',
contact: '[email protected]'
}
});
Then all of these variables are accessible in my views as site.title
, site.description
, author.name
, author.contact
.
I could also define local variables for each response to a request with res.locals
, or simply pass variables like the page's title in as the options
parameter in the render
call.
EDIT: This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals
for each response and then call next
. This middleware function will need to be placed above any other middleware which needs to use these locals.
EDIT: Another difference between declaring locals via app.locals
and res.locals
is that with app.locals
the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals
in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals
unless the value depends on the request req
variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals
.
Don't use a symbolic Link to move the docker folder to /mnt (for example). This may cause in trouble with the docker rm command.
Better use the -g Option for docker. On Ubuntu you can set it permanently in /etc/default/docker.io. Enhance or replace the DOCKER_OPTS Line.
Here an example: `DOCKER_OPTS="-g /mnt/somewhere/else/docker/"
You need to use the Thread.sleep()
call.
More info here: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
Use like this:
when(
fooDao.getBar(
Matchers.<Bazoo>any()
)
).thenReturn(myFoo);
Before you need to import Mockito.Matchers
An adaption from praneybehl answer to work with nested objects and tab separator
function ConvertToCSV(objArray) {
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
if(!Array.isArray(array))
array = [array];
let str = '';
for (let i = 0; i < array.length; i++) {
let line = '';
for (let index in array[i]) {
if (line != '') line += ','
const item = array[i][index];
line += (typeof item === 'object' && item !== null ? ConvertToCSV(item) : item);
}
str += line + '\r\n';
}
do{
str = str.replace(',','\t').replace('\t\t', '\t');
}while(str.includes(',') || str.includes('\t\t'));
return str.replace(/(\r\n|\n|\r)/gm, ""); //removing line breaks: https://stackoverflow.com/a/10805198/4508758
}
Just for completeness, changing overflow
to auto
/hidden
should do the trick too.
body {_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
}_x000D_
_x000D_
header {_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
height: 20em;_x000D_
background-color: #C0C0C0;_x000D_
overflow: auto;_x000D_
}
_x000D_
<header>_x000D_
<h1>OQ Online Judge</h1>_x000D_
_x000D_
<form action="<?php echo base_url();?>/index.php/base/si" method="post">_x000D_
<label for="email1">E-mail :</label>_x000D_
<input type="text" name="email" id="email1">_x000D_
<label for="password1">Password :</label>_x000D_
<input type="password" name="password" id="password1">_x000D_
<input type="submit" name="submit" value="Login">_x000D_
</form>_x000D_
</header>
_x000D_