This link has more information:
https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory * 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers * 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory * 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger * 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files * 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory * 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory * 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory * 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash. * 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory * 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
Try Fiddler2 it will let you inspect the requests and response. It might be worth noting that Fiddler works with both http and https traffic.
Short answer: using as.data.frame.matrix(mytable)
, as @Victor Van Hee suggested.
Long answer: as.data.frame(mytable)
may not work on contingency tables generated by table()
function, even if is.matrix(your_table)
returns TRUE
. It will still melt you table into the factor1 factor2 factori counts
format.
Example:
> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)
> freq_t
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> is.matrix(freq_t)
[1] TRUE
> as.data.frame(freq_t)
cyl gear Freq
1 4 3 1
2 6 3 2
3 8 3 12
4 4 4 8
5 6 4 4
6 8 4 0
7 4 5 2
8 6 5 1
9 8 5 2
> as.data.frame.matrix(freq_t)
3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
This SO answer might help in this case.
If the main project already references the resource project, then you could just explicitly work with your generated-resource class in your code, and access its ResourceManager
from that. Hence, something along the lines of:
ResourceManager resMan = YeagerTechResources.Resources.ResourceManager;
// then, you could go on working with that
ResourceSet resourceSet = resMan.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// ...
Go to Help -> About Eclipse Sdk
To get this to work, I had to use ALL three of the things (ellipsize, selected, and singleLine) mentioned already:
TextView tv = (TextView)findViewById(R.id.someTextView);
tv.setSelected(true);
tv.setEllipsize(TruncateAt.MARQUEE);
tv.setSingleLine(true):
Using Lambda:
new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
.setTitle(getString(R.string.info))
.setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
moveTaskToBack(true);
finish();
})
.setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
})
.show();
You also need to set level language to support java 8 in your gradle.build:
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
I was looking for a ES6 example (so it could pass my linter) So for other people who are looking for the same:
$('#dSuggest').keyup((e) => {
console.log(e.currentTarget.value);
});
I would also use keyup because you get the current value that is filled in.
https://angular.io/guide/user-input - there's a simple example .
cd apache-tomcat-6.0.43 ====: Go to Tomcat Directory
sh bin/startup.sh =====: Start the tomcat on Linux
sh bin/shutdown.sh ======:Shut Down the tomcat on Linux
tail -f logs/catelina.out ====: Check the logs
This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()
Execute at Admin privilege using sudo
in order to avoid permission denied
(Unable to change file mode) error.
sudo chmod 777 <directory location>
I wrote how to write LaTeX in Jupyter Notebook in this article.
You need to enclose them in dollar($) signs.
$P(A)=\frac{n(A)}{n(U)}$
$$P(A)=\frac{n(A)}{n(U)}$$
Use \limits
for \lim
, \sum
and \int
to add limits to the top and the bottom of each sign.
Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.
Try this one.
$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i $$
$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$
The above code will create this.
If you want to know how to add numbering to equations and align equations, please read this article for details.
Best example for dynamic linking is, when the library is dependent on the used hardware. In ancient times the C math library was decided to be dynamic, so that each platform can use all processor capabilities to optimize it.
An even better example might be OpenGL. OpenGl is an API that is implemented differently by AMD and NVidia. And you are not able to use an NVidia implementation on an AMD card, because the hardware is different. You cannot link OpenGL statically into your program, because of that. Dynamic linking is used here to let the API be optimized for all platforms.
Press Alt+shift+R
key and change package name
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
In HTML:
<a href="index.php?link=home" name="home">home</a>
Then in PHP:
if(isset($_GET['link'])){$_SESSION['link'] = $_GET['link'];}
Beware of circular references when DOM objects are involved:
Memory leak patterns in JavaScript
Keep in mind that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines will not check which variables actually are referenced in inner functions and just keep all local variables of the enclosing functions.
Here's a simple example:
function init() {
var bigString = new Array(1000).join('xxx');
var foo = document.getElementById('foo');
foo.onclick = function() {
// this might create a closure over `bigString`,
// even if `bigString` isn't referenced anywhere!
};
}
A naive JS implementation can't collect bigString
as long as the event handler is around. There are several ways to solve this problem, eg setting bigString = null
at the end of init()
(delete
won't work for local variables and function arguments: delete
removes properties from objects, and the variable object is inaccessible - ES5 in strict mode will even throw a ReferenceError
if you try to delete a local variable!).
I recommend to avoid unnecessary closures as much as possible if you care for memory consumption.
In Swift 4 You can use
->Go Info.plist
-> Click plus of Information properties list
->Add App Transport Security Settings as dictionary
-> Click Plus icon App Transport Security Settings
-> Add Allow Arbitrary Loads set YES
Bellow image look like
Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -
function isExtensionLoaded($extension_name){
return extension_loaded($extension_name);
}
Usage
echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');
Thanks Kip, for those who may be looking to achieve the same using $(this) whilst iterating or associating within a function:
$("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );
I looked for a while whilst working this project but couldn't find a good example so I hope this helps others who may be looking to resolve the same issue.
In the example above, my objective was to hide the radio inputs and style the labels to provide a slicker user experience (changing the orientation of the flowchart).
You can see an example here
If you like the example, here is the css:
.orientation { position: absolute; top: -9999px; left: -9999px;}
.orienlabel{background:#1a97d4 url('http://www.ifreight.solutions/process.html/images/icons/flowChart.png') no-repeat 2px 5px; background-size: 40px auto;color:#fff; width:50px;height:50px;display:inline-block; border-radius:50%;color:transparent;cursor:pointer;}
.orR{ background-position: 9px -57px;}
.orT{ background-position: 2px -120px;}
.orB{ background-position: 6px -177px;}
.orienSel {background-color:#323232;}
and the relevant part of the JavaScript:
function changeHandler() {
$(".orienSel").removeClass( "orienSel" );
if(this.checked) {
$("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );
}
};
An alternate root to the original question, given the label follows the input, you could go with a pure css solution and avoid using JavaScript altogether...:
input[type=checkbox]:checked+label {}
Now that TypeScript 2.2 supports Mixins through Class expressions we have a much better way to express Mixins on Components. Mind you that you can also use Component inheritance since angular 2.3 (discussion) or a custom decorator as discussed in other answers here. However, I think Mixins have some properties that make them preferable for reusing behavior across components:
I strongly suggest you read the TypeScript 2.2 announcement above to understand how Mixins work. The linked discussions in angular GitHub issues provide additional detail.
You'll need these types:
export type Constructor<T> = new (...args: any[]) => T;
export class MixinRoot {
}
And then you can declare a Mixin like this Destroyable
mixin that helps components keep track of subscriptions that need to be disposed in ngOnDestroy
:
export function Destroyable<T extends Constructor<{}>>(Base: T) {
return class Mixin extends Base implements OnDestroy {
private readonly subscriptions: Subscription[] = [];
protected registerSubscription(sub: Subscription) {
this.subscriptions.push(sub);
}
public ngOnDestroy() {
this.subscriptions.forEach(x => x.unsubscribe());
this.subscriptions.length = 0; // release memory
}
};
}
To mixin Destroyable
into a Component
, you declare your component like this:
export class DashboardComponent extends Destroyable(MixinRoot)
implements OnInit, OnDestroy { ... }
Note that MixinRoot
is only necessary when you want to extend
a Mixin composition. You can easily extend multiple mixins e.g. A extends B(C(D))
. This is the obvious linearization of mixins I was talking about above, e.g. you're effectively composing an inheritnace hierarchy A -> B -> C -> D
.
In other cases, e.g. when you want to compose Mixins on an existing class, you can apply the Mixin like so:
const MyClassWithMixin = MyMixin(MyClass);
However, I found the first way works best for Components
and Directives
, as these also need to be decorated with @Component
or @Directive
anyway.
Serge is right - my workaround:
function mySleep (sec)
{
SpreadsheetApp.flush();
Utilities.sleep(sec*1000);
SpreadsheetApp.flush();
}
It looks like there's not a straightforward solution for HTTPS-based cloning regarding GitLab. Therefore if you want a SSH-based cloning, you should take account these three forthcoming steps:
Create properly an SSH key using your email used to sign up. I would use the default filename to key for Windows. Don't forget to introduce a password!
$ ssh-keygen -t rsa -C "[email protected]" -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key ($PWD/.ssh/id_rsa): [\n]
Enter passphrase (empty for no passphrase):[your password]
Enter same passphrase again: [your password]
Your identification has been saved in $PWD/.ssh/id_rsa.
Your public key has been saved in $PWD/.ssh/id_rsa.pub.
Copy and paste all content from the recently id_rsa.pub
generated into Setting>SSH keys>Key from your GitLab profile.
Get locally connected:
$ ssh -i $PWD/.ssh/id_rsa [email protected]
Enter passphrase for key "$PWD/.ssh/id_rsa": [your password]
PTY allocation request failed on channel 0
Welcome to GitLab, you!
Connection to gitlab.com closed.
Finally, clone any private or internal GitLab repository!
$ git clone https://git.metabarcoding.org/obitools/ROBIBarcodes.git
Cloning into 'ROBIBarcodes'...
remote: Counting objects: 69, done.
remote: Compressing objects: 100% (65/65), done.
remote: Total 69 (delta 14), reused 0 (delta 0)
Unpacking objects: 100% (69/69), done.
To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100
in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application.
If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.
Assuming you are using the command line:
show databases;
e.g. USE classicmodels;
and you should be off to the races! (Obviously, you'll have to use the correctly named database in your list.
Mysql requires you to select the particular database you are working on. I presume it is a design decision they made: it avoids a lot of potential problems: e.g. it is entirely possible, for you to use the same table names across multiple databases e.g. a users
table. In order to avoid these types of issues, they probably thought: "let's make users select the database they want".
Do that like this
db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
HTML Code:-
<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />
<input type="button" id="btnclick">
Java Script Code
function AddKeyPress(e) {
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById('btnEmail').click();
return false;
}
return true;
}
Your Form do not have Default Submit Button
require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"
if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)
However, you can implement an interface with a function like so :
Comparator<String> c = new Comparator<String>() {
int compare(String s, String s2) { ... }
};
and you can use this with inner classes to get an almost-anonymous function :)
An array length
is not the number of elements in a array, it is the highest index + 1
. length
property will report correct element count only if there are valid elements in consecutive indices.
var a = [];
a[23] = 'foo';
a.length; // 24
Saying that, there is no way to exclude undefined elements from count without using any form of a loop.
Try these ...
Option1
window.location=document.referrer;
Option2
window.location.reload(history.back());
Inline items cannot have a width. You have to use display: block
or display:inline-block
, but the latter is not supported everywhere.
If you mean how to check whether member variables have been initialized, you can do this by assigning them sentinel values in the constructor. Choose sentinel values as values that will never occur in normal usage of that variable. If a variables entire range is considered valid, you can create a boolean to indicate whether it has been initialized.
#include <limits>
class MyClass
{
void SomeMethod();
char mCharacter;
bool isCharacterInitialized;
double mDecimal;
MyClass()
: isCharacterInitialized(false)
, mDecimal( std::numeric_limits<double>::quiet_NaN() )
{}
};
void MyClass::SomeMethod()
{
if ( isCharacterInitialized == false )
{
// do something with mCharacter.
}
if ( mDecimal != mDecimal ) // if true, mDecimal == NaN
{
// define mDecimal.
}
}
For making alert just put below javascript code in footer.
<script>
$(document).ready(function(){
alert('Hi');
});
</script>
You need to also load jquery min file. Please insert this script in header.
<script type='text/javascript' src='https://code.jquery.com/jquery-1.12.0.min.js'></script>
First of all you have to fetch the remote repository:
git fetch remoteName
Than you can create the new branch and set it up to track the remote branch you want:
git checkout -b newLocalBranch remoteName/remoteBranch
You can also use "git branch --track" instead of "git checkout -b" as max specified.
git branch --track newLocalBranch remoteName/remoteBranch
I use this type of decorator in some debugging situations, it allows overriding class properties by decorating, without having to find the calling function.
class myclass(object):
def __init__(self):
self.property = "HELLO"
@adecorator(property="GOODBYE")
def method(self):
print self.property
Here is the decorator code
class adecorator (object):
def __init__ (self, *args, **kwargs):
# store arguments passed to the decorator
self.args = args
self.kwargs = kwargs
def __call__(self, func):
def newf(*args, **kwargs):
#the 'self' for a method function is passed as args[0]
slf = args[0]
# replace and store the attributes
saved = {}
for k,v in self.kwargs.items():
if hasattr(slf, k):
saved[k] = getattr(slf,k)
setattr(slf, k, v)
# call the method
ret = func(*args, **kwargs)
#put things back
for k,v in saved.items():
setattr(slf, k, v)
return ret
newf.__doc__ = func.__doc__
return newf
Note: because I've used a class decorator you'll need to use @adecorator() with the brackets on to decorate functions, even if you don't pass any arguments to the decorator class constructor.
How you detect EOF depends on what you're using to read the stream:
function result on EOF or error
-------- ----------------------
fgets() NULL
fscanf() number of succesful conversions
less than expected
fgetc() EOF
fread() number of elements read
less than expected
Check the result of the input call for the appropriate condition above, then call feof()
to determine if the result was due to hitting EOF or some other error.
Using fgets()
:
char buffer[BUFFER_SIZE];
while (fgets(buffer, sizeof buffer, stream) != NULL)
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fscanf()
:
char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fgetc()
:
int c;
while ((c = fgetc(stream)) != EOF)
{
// process c
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fread()
:
char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1
// element of size
// BUFFER_SIZE
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted read
}
Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:
while(!feof(stream))
{
fscanf(stream, "%s", buffer);
...
}
This form doesn't work the way people think it does, because feof()
won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.
Here's a category that allows you to quickly find the first responder by calling [UIResponder currentFirstResponder]
. Just add the following two files to your project:
UIResponder+FirstResponder.h
#import <Cocoa/Cocoa.h>
@interface UIResponder (FirstResponder)
+(id)currentFirstResponder;
@end
UIResponder+FirstResponder.m
#import "UIResponder+FirstResponder.h"
static __weak id currentFirstResponder;
@implementation UIResponder (FirstResponder)
+(id)currentFirstResponder {
currentFirstResponder = nil;
[[UIApplication sharedApplication] sendAction:@selector(findFirstResponder:) to:nil from:nil forEvent:nil];
return currentFirstResponder;
}
-(void)findFirstResponder:(id)sender {
currentFirstResponder = self;
}
@end
The trick here is that sending an action to nil sends it to the first responder.
(I originally published this answer here: https://stackoverflow.com/a/14135456/322427)
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
With ASP.net Web API 2 install Microsoft ASP.NET Cross Origin support via nuget.
http://enable-cors.org/server_aspnet.html
public static void Register(HttpConfiguration config)
{
var enableCorsAttribute = new EnableCorsAttribute("http://mydomain.com",
"Origin, Content-Type, Accept",
"GET, PUT, POST, DELETE, OPTIONS");
config.EnableCors(enableCorsAttribute);
}
Its my code
jQuery(document).ready(function(e) {
var WindowHeight = jQuery(window).height();
var load_element = 0;
//position of element
var scroll_position = jQuery('.product-bottom').offset().top;
var screen_height = jQuery(window).height();
var activation_offset = 0;
var max_scroll_height = jQuery('body').height() + screen_height;
var scroll_activation_point = scroll_position - (screen_height * activation_offset);
jQuery(window).on('scroll', function(e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > scroll_activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if (element_in_view || has_reached_bottom_of_page) {
jQuery('.product-bottom').addClass("change");
} else {
jQuery('.product-bottom').removeClass("change");
}
});
});
Its working Fine
android:largeHeap="true"
didn't fix the error
In my case, I got this error after I added an icon/image to Drawable folder by converting SVG to vector. Simply, go to the icon xml file and set small numbers for the width and height
android:width="24dp"
android:height="24dp"
android:viewportWidth="3033"
android:viewportHeight="3033"
printf("type a number ");
int converted = scanf("%d", &a);
printf("\n");
if( converted == 0)
{
printf("enter integer");
system("PAUSE \n");
return 0;
}
scanf() returns the number of format specifiers that match, so will return zero if the text entered cannot be interpreted as a decimal integer
My problem was that POST requests need trailing slashes '/'.
You can tab between div tags. Just add a tab index to the div. It's best to use jQuery and CSS classes to solve this problem. Here's a working sample tested in IE, Firefox, and Chrome (Latest versions... didn't test older).
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var divParentIdFocus;
var divParentIdUnfocus = null;
$(document).ready(function() {
$("div").focus(function() {
//$(this).attr("class", "highlight");
var curDivId = $(this).attr("id");
// This Check needs to be performed when/if div regains focus
// from child element.
if (divParentIdFocus != curDivId){
divParentIdUnfocus = divParentIdFocus;
divParentIdFocus = curDivId;
refreshHighlight();
}
divParentIdFocus = curDivId;
});
$("textarea").focus(function(){
var curDivId = $(this).closest("div").attr("id");
if(divParentIdFocus != curDivId){
divParentIdUnfocus = divParentIdFocus;
divParentIdFocus = curDivId;
refreshHighlight();
}
});
$("#div1").focus();
});
function refreshHighlight()
{
if(divParentIdUnfocus != null){
$("#" +divParentIdUnfocus).attr("class", "noHighlight");
divParentIdUnfocus = null;
}
$("#" + divParentIdFocus).attr("class", "highlight");
}
</script>
<style type="text/css">
.highlight{
background-color:blue;
border: 3px solid black;
font-weight:bold;
color: white;
}
.noHighlight{
}
div, h1,textarea, select { outline: none; }
</style>
<head>
<body>
<div id = "div1" tabindex="100">
<h1>Div 1</h1> <br />
<textarea rows="2" cols="25" tabindex="101">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="102">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="103">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="104">~Your Text Here~</textarea> <br />
</div>
<div id = "div2" tabindex="200">
<h1>Div 2</h1> <br />
<textarea rows="2" cols="25" tabindex="201">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="202">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="203">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="204">~Your Text Here~</textarea> <br />
</div>
<div id = "div3" tabindex="300">
<h1>Div 3</h1> <br />
<textarea rows="2" cols="25" tabindex="301">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="302">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="303">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="304">~Your Text Here~</textarea> <br />
</div>
<div id = "div4" tabindex="400">
<h1>Div 4</h1> <br />
<textarea rows="2" cols="25" tabindex="401">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="402">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="403">~Your Text Here~</textarea> <br />
<textarea rows="2" cols="25" tabindex="404">~Your Text Here~</textarea> <br />
</div>
</body>
</html>
print "Number of lines: $nids\n";
print "Content: $ids\n";
How did Perl complain? print $ids
should work, though you probably want a newline at the end, either explicitly with print
as above or implicitly by using say
or -l/$\.
If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}
:
print "foo${ids}bar";
Its just a warning that is telling you to start using newer methods of connecting to your db such as pdo objects
http://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338
The manual is here
My solution breaks down in 3 parts: the state of the user is stored in a service, in the run method you watch when the route changes and you check if the user is allowed to access the requested page, in your main controller you watch if the state of the user change.
app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
console.log('DENY');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
$location.path('/home');
}
});
}]);
You should create a service (I will name it Auth
) which will handle the user object and have a method to know if the user is logged or not.
service:
.factory('Auth', function(){
var user;
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
})
From your app.run
, you should listen the $routeChangeStart
event. When the route will change, it will check if the user is logged (the isLoggedIn
method should handle it). It won't load the requested route if the user is not logged and it will redirect the user to the right page (in your case login).
The loginController
should be used in your login page to handle login. It should just interract with the Auth
service and set the user as logged or not.
loginController:
.controller('loginCtrl', [ '$scope', 'Auth', function ($scope, Auth) {
//submit
$scope.login = function () {
// Ask to the server, do your job and THEN set the user
Auth.setUser(user); //Update the state of the user in the app
};
}])
From your main controller, you could listen if the user state change and react with a redirection.
.controller('mainCtrl', ['$scope', 'Auth', '$location', function ($scope, Auth, $location) {
$scope.$watch(Auth.isLoggedIn, function (value, oldValue) {
if(!value && oldValue) {
console.log("Disconnect");
$location.path('/login');
}
if(value) {
console.log("Connect");
//Do something when the user is connected
}
}, true);
Mine was quite a unique case but this could help someone. On Android I tried to copy nano from my termux binary folder to /system/xbin. Placed all the library dependencies in /system/lib and got this error. The libncurses.so.6 file I copied from termux had it's TERMINFO file still pointed to /data/data/com.termux/files/usr/share/terminfo
View pointed path with command
strings path-to-libncurses.so | grep /terminfo
To fix either make the termux terminfo dir and subdirs readable and executable by the nano user or copy the terminfo folder somewhere else and use a hexeditor to modify the plain text path in the shared library file.
Link to zipped terminfo folder https://drive.google.com/file/d/1m1tfHgkGRehBGh1jPMK4EaTgQb9EyCG7/view?usp=drivesdk
Here is a complete example for navigating valid URL on a new tab with focused.
HTML:
<div class="panel">
<p>
Enter Url:
<input type="text" id="txturl" name="txturl" size="30" class="weburl" />
<input type="button" id="btnopen" value="Open Url in New Tab" onclick="openURL();"/>
</p>
</div>
CSS:
.panel{
font-size:14px;
}
.panel input{
border:1px solid #333;
}
JAVASCRIPT:
function isValidURL(url) {
var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (RegExp.test(url)) {
return true;
} else {
return false;
}
}
function openURL() {
var url = document.getElementById("txturl").value.trim();
if (isValidURL(url)) {
var myWindow = window.open(url, '_blank');
myWindow.focus();
document.getElementById("txturl").value = '';
} else {
alert("Please enter valid URL..!");
return false;
}
}
I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw
In my case, i was calling twice the import...
@click="$router.push({ path: 'searcherresult' })"
import SearcherResult from "../views/SearcherResult"; --- ERROR
Cause i call in other component...
You can call a ant task called merge on maven, to put all coverage files (*.exec) together in the same file.
If you are run unit tests use the phase prepare-package, if you run integration test so use post-integration-test.
This site has an example to how call jacoco ant task in maven project
You can use this merged file on sonar.
well, i just added button
in data.
For Example,
i should code like this:
$(target).DataTable().row.add(message).draw()
And, in message
, i added button like this : [blah, blah ... "<button>Click!</button>"]
and.. it works!
If you need to cast objects at runtime without knowing destination type, you can use reflection to make a dynamic converter.
This is a simplified version (without caching generated method):
public static class Tool
{
public static object CastTo<T>(object value) where T : class
{
return value as T;
}
private static readonly MethodInfo CastToInfo = typeof (Tool).GetMethod("CastTo");
public static object DynamicCast(object source, Type targetType)
{
return CastToInfo.MakeGenericMethod(new[] { targetType }).Invoke(null, new[] { source });
}
}
then you can call it:
var r = Tool.DynamicCast(myinstance, typeof (MyClass));
@Liem Vo's answer is correct if you are using android.widget.Button without any overriding. If you are overriding your theme using MaterialComponents, this will not solve the issue.
So if you are
Use app:icon parameter.
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:textSize="24sp"
app:icon="@android:drawable/ic_menu_search" />
here's another one:
Drawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
You can try with ParseExact
method
Sample
Dim format As String
format = "d"
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)
Here's @SLaks answer, but in pure ES6 JavaScript.
var start = new Date,_x000D_
$timer = document.querySelector('.Timer');_x000D_
_x000D_
setInterval(function(timestamp) {_x000D_
$timer.innerText = `${timestamp - start) / 1000} Seconds`;_x000D_
}, 1000);
_x000D_
You don't need to necessarily use Objects, you can do it with normal multi-dimensional Arrays.
This is my solution without Objects:
// Javascript
const matrix = [];
matrix.key1 = [
'value1',
'value2',
];
matrix.key2 = [
'value3',
];
which in PHP is equivalent to:
// PHP
$matrix = [
"key1" => [
'value1',
'value2',
],
"key2" => [
'value3',
]
];
Generally, it means the program you are trying to run does not have a "main" method. If you are going to execute a Java program, the class being executed must have a main
method:
For example, in the file Foo.java
public class Foo {
public static void main(final String args[]) {
System.out.println("hello");
}
}
This program should compile and run no problem - if main
was called something else, or was not static, it would generate the error you experienced.
Every executable program, regardless of language, needs an entry point, to tell the interpreter, operating system or machine where to start execution. In Java's case, this is the static method main
, which is passed the parameter args[]
containing the command line arguments. This method is equivalent to int main(int argc, char** argv)
in C language.
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
The Mozilla.org FAQ on debugging Mozilla on Windows is of interest here.
In short, the Visual Studio debugger can be invoked on a program from the command line, allowing one to specify the command line arguments when invoking a command line program, directly on the command line.
This looks like the following for Visual Studio 8 or 9 (Visual Studio 2005 or Visual Studio 2008, respectively)
devenv /debugexe 'program name' 'program arguments'
It is also possible to have an explorer action to start a program in the Visual Studio debugger.
Removing the .lock
file and reinstalling did not solve the issue on my machine (Ubuntu 19.10). The problem was that after unexpected shutdown, the MongoDB sock does not belong to the MongoDB group and user anymore.
So, I follow the steps below:
Change the user:group permission:
chown mongodb:mongodb <YOUR_SOCK>
sudo systemctl start mongod
check for existence of all keys in a dict:
{'key_1', 'key_2', 'key_3'} <= set(my_dict)
check for existence of one or more keys in a dict:
{'key_1', 'key_2', 'key_3'} & set(my_dict)
You could possibly surround the span with another span, then simply test if the width of the original/inner span is greater than that of the new/outer span. Note that I say possibly -- it is roughly based on my situation where I had a span
inside of a td
so I don't actually know that if it will work with a span
inside of a span
.
Here though is my code for others who may find themselves in a position similar to mine; I'm copying/pasting it without modification even though it is in an Angular context, I don't think that detracts from the readability and the essential concept. I coded it as a service method because I needed to apply it in more than one place. The selector I've been passing in has been a class selector that will match multiple instances.
CaseService.applyTooltip = function(selector) {
angular.element(selector).on('mouseenter', function(){
var td = $(this)
var span = td.find('span');
if (!span.attr('tooltip-computed')) {
//compute just once
span.attr('tooltip-computed','1');
if (span.width() > td.width()){
span.attr('data-toggle','tooltip');
span.attr('data-placement','right');
span.attr('title', span.html());
}
}
});
}
Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.
Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:
public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime { get { return utcDateTime; } }
public TimeZoneInfo TimeZone { get { return timeZone; } }
public DateTime LocalTime
{
get
{
return TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}
}
}
You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
Ok, already having DOM, JaxB and XStream in the list of answers, there is still a complete different way to read and write XML: Data projection You can decouple the XML structure and the Java structure by using a library that provides read and writeable views to the XML Data as Java interfaces. From the tutorials:
Given some real world XML:
<weatherdata>
<weather
...
degreetype="F"
lat="50.5520210266113" lon="6.24060010910034"
searchlocation="Monschau, Stadt Aachen, NW, Germany"
... >
<current ... skytext="Clear" temperature="46"/>
</weather>
</weatherdata>
With data projection you can define a projection interface:
public interface WeatherData {
@XBRead("/weatherdata/weather/@searchlocation")
String getLocation();
@XBRead("/weatherdata/weather/current/@temperature")
int getTemperature();
@XBRead("/weatherdata/weather/@degreetype")
String getDegreeType();
@XBRead("/weatherdata/weather/current/@skytext")
String getSkytext();
/**
* This would be our "sub projection". A structure grouping two attribute
* values in one object.
*/
interface Coordinates {
@XBRead("@lon")
double getLongitude();
@XBRead("@lat")
double getLatitude();
}
@XBRead("/weatherdata/weather")
Coordinates getCoordinates();
}
And use instances of this interface just like POJOs:
private void printWeatherData(String location) throws IOException {
final String BaseURL = "http://weather.service.msn.com/find.aspx?outputview=search&weasearchstr=";
// We let the projector fetch the data for us
WeatherData weatherData = new XBProjector().io().url(BaseURL + location).read(WeatherData.class);
// Print some values
System.out.println("The weather in " + weatherData.getLocation() + ":");
System.out.println(weatherData.getSkytext());
System.out.println("Temperature: " + weatherData.getTemperature() + "°"
+ weatherData.getDegreeType());
// Access our sub projection
Coordinates coordinates = weatherData.getCoordinates();
System.out.println("The place is located at " + coordinates.getLatitude() + ","
+ coordinates.getLongitude());
}
This works even for creating XML, the XPath expressions can be writable.
Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is the code :
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
Declare extern int x;
in file.h.
And define int x;
only in one cpp file.cpp.
ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121
S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ;
RemoteServerName => abcd123 ;
2121 => port number ;
ftps => command is part of ftps client software ;
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>';
In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like
class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>
{
...
}
then just issue the command
Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName
and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:
Update-Database -ConfigurationTypeName MyNewContextConfiguration
Done.
You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.
You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.
In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds
file. Not so for Rda
> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)
## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5
## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to <environment: R_GlobalEnv>
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values.
> x
[1] 1 2 3 4 5
public async Task<Product> GetValue(int id)
{
Product Products = await _context.Products.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
return Products;
}
AsNoTracking()
You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.
//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()//Your tableView here
})
//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {
// Call your function here
DispatchQueue.main.async {
// Update UI
self.tableView.reloadData()
}
}
//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()
})
}
From the javadoc
@param the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.
example
import java.util.*;
public class HelloWorld {
public static void main(String args[]) {
// create an array of string objs
String initList[] = { "One", "Two", "Four", "One",};
// create one list
List list = new ArrayList(Arrays.asList(initList));
System.out.println("List value before: "+list);
// create singleton list
list = Collections.singletonList("OnlyOneElement");
list.add("five"); //throws UnsupportedOperationException
System.out.println("List value after: "+list);
}
}
Use it when code expects a read-only list, but you only want to pass one element in it. singletonList
is (thread-)safe and fast.
I actually took my time went through all the above answers on this page but to no avail. I just happened to change the owner and the permissions of directory and sub-directories using the following command.I changed the owner of the web project directory in /usr/share/nginx/html
to the root
user using:
chown root /usr/share/nginx/html/mywebprojectdir/*
And finally changed the permissions of that directory and sub-directories using:
chmod 755 /usr/share/nginx/html/mywebprojectdir/*
NOTE: if denied , you can use sudo
I was getting exactly that error too: Connection reset by peer
. The exception was being raised by Spring's REST template upon running the postForObject()
method. For me the problem was too long HTTP URL request. So first check whether the URL produced is what it should be and, if your server really should be able to handle requests of that length, simply go to server's configuration and raise the default allowed length of URL requests.
That solved the problem for me, but be aware: the application might not run on some internet browsers, especially old ones, as they have fixed max length of URL requests.
Hope it helps...
Transient
Scoped
Singleton
Use Singletons where you need to maintain application wide state. Application configuration or parameters, Logging Service, caching of data is some of the examples where you can use singletons.
A line break is defined differently on different platforms, \r\n, \r or \n.
Using RegExp to split the string you can match all three with \R
So for your problem:
$array = preg_split ('/$\R?^/m', $string);
That would match line breaks on Windows, Mac and Linux!
in my case i made a custom view i added to custom view constructor
new RoomView(getAplicationContext());
the correct context is activity so changed it to:
new RoomView(getActivity());
or
new RoomView(this);
My grep-a-like program ack
has a -1
option that stops at the first match found anywhere. It supports the -m 1
that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.
Diff Doc may be what you're looking for.
- Compare documents of MS Word (DOC, DOCX etc), Excel, PDF, Rich Text (RTF), Text, HTML, XML, PowerPoint, or Wordperfect and retain formatting
- Choose any portion of any document (file) and compare it against any portion of the same or different document (file).
In my case root cause of this issue was multiple http bindings defined at parent web site i.e. InetMgr->Sites->Mysite->properties->EditBindings. I deleted one http binding which was not required and problem got resolved.
To my knowledge, the surefire plugin doesn't provide any way to do this. But feel free to open an issue :)
You can do get id value by using
test_alert = $('#myDiv').val();_x000D_
alert(test_alert);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
You can also use callto:########### replacing the email code mail with call, at least according to W3Cschool site but I haven't had an opportunity to test it out.
Take a look at this:
<input type="number" step="0.01" />
It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
I faced similar issue with Spring MVC application. I used < mvc:resources >
tag to resolve this issue.
Please find the following link having more details.
http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/
The document.mouseover does not work for IE and FireFox. However I have tried this :
$(document).ready(function () {
setInterval(function () {
var $sample = $("body");
if ($sample.is(":hover")) {
window.innerDocClick = true;
} else {
window.innerDocClick = false;
}
});
});
window.onhashchange = function () {
if (window.innerDocClick) {
//Your own in-page mechanism triggered the hash change
} else {
//Browser back or forward button was pressed
}
};
This works for Chrome and IE and not FireFox. Still working to get FireFox right. Any easy way on detecting Browser back/forward button click are welcome, not particularly in JQuery but also AngularJS or plain Javascript.
You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document
Try this runner I wrote. It could be helpful.
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ProxyAuthHelper {
public static void main(String[] args) throws Exception {
String tmp = System.getProperty("http.proxyUser", System.getProperty("https.proxyUser"));
if (tmp == null) {
System.out.println("Proxy username: ");
tmp = new Scanner(System.in).nextLine();
}
final String userName = tmp;
tmp = System.getProperty("http.proxyPassword", System.getProperty("https.proxyPassword"));
if (tmp == null) {
System.out.println("Proxy password: ");
tmp = new Scanner(System.in).nextLine();
}
final char[] password = tmp.toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("\n--------------\nProxy auth: " + userName);
return new PasswordAuthentication (userName, password);
}
});
Class<?> clazz = Class.forName(args[0]);
Method method = clazz.getMethod("main", String[].class);
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
method.invoke(null, new Object[]{newArgs});
}
}
Just want to update, that in Spring 5, as mentioned in Spring docs, Spring supports 6 scopes, four of which are available only if you use a web-aware ApplicationContext.
singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
it's straight forward to do in programatic way. just follow these steps
add an observer to content length of textfield
[yourTextViewObject addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
implement observer
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
//Center vertical alignment
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
mTextViewHeightConstraint.constant = tv.contentSize.height;
[UIView animateWithDuration:0.2 animations:^{
[self.view layoutIfNeeded];
}];
}
if you want to stop textviewHeight to increase after some time during typing then implement this and set textview delegate to self.
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if(range.length + range.location > textView.text.length)
{
return NO;
}
NSUInteger newLength = [textView.text length] + [text length] - range.length;
return (newLength > 100) ? NO : YES;
}
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
In the above code "60" stands for the minutes.
The session will expired after 60 minutes.
So if you want to more time. For Example -1
that is described your session never expires.
ListItem item = ddlComputedliat1.Items.FindByText("Amt D");
if (item == null) {
ddlComputedliat1.Items.Insert(1, lblnewamountamt.Text);
}
Header files needed:
#include <iostream>
#include <fstream>
declare input file stream:
ifstream in("in.txt");
declare output file stream:
ofstream out("out.txt");
if you want to use variable for a file name, instead of hardcoding it, use this:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());
reading from file into variables (assume file has 2 int variables in):
int num1,num2;
in >> num1 >> num2;
or, reading a line a time from file:
string line;
while(getline(in,line)){
//do something with the line
}
write variables back to the file:
out << num1 << num2;
close the files:
in.close();
out.close();
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.
Put a breakpoint in your code at a somewhere close to a reference to the $scope variable (so that the $scope is in the current 'plain old JavaScript' scope). Then your can inspect the $scope value in the console.
It's pandas
label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label
The boolean array is basically a selection method using a mask.
You can set custom git aliases using git's config. Here's the syntax:
git config --global alias.<aliasName> "<git command>"
For example, if you need an alias to display a list of files which have merge conflicts, run:
git config --global alias.conflicts "diff --name-only --diff-filter=U"
Now you can use the above command only using "conflicts":
git conflicts
# same as running: git diff --name-only --diff-filter=U
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format>
(here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd
. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff')
.
For parsing weird formatted dates on C# you can use DateTime.ParseExact()
method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture)
. Here you have the DateTime.ParseExact() explanation on MSDN)
If you have object then need to typecast
return (T)(object)(employee);
if you need to return null.
return default(T);
tl;dr version: use ~/.zshrc
And read the man page to understand the differences between:
~/.zshrc
,~/.zshenv
and~/.zprofile
.
In my comment attached to the answer kev gave, I said:
This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.
This turns out to be partially incorrect: /etc/profile
may be sourced by zsh
. However, this only occurs if zsh
is "invoked as sh
or ksh
"; in these compatibility modes:
The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].
The ArchWiki ZSH link says:
At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login
This implys that /etc/profile
is always read by zsh
at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH
set in /etc/profile
do not make it to my zsh sessions).
where exactly should I be placing my rvm, python, node etc additions to my $PATH?
Generally, I would export my $PATH
from ~/.zshrc
, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc
is read for interactive shells, which may or may not suit your needs - if you want the $PATH
for every zsh
shell invoked by you (both interactive
and not, both login
and not, etc), then ~/.zshenv
is a better option.
Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?
There's a bunch of files read on startup (check the linked man
pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv
not existing - if you need it, make it, and it will be read.
.bashrc
and .bash_profile
are not read by zsh
, unless you explicitly source them from ~/.zshrc
or similar; the syntax between bash
and zsh
is not always compatible. Both .bashrc
and .bash_profile
are designed for bash
settings, not zsh
settings.
Building a HashMap of these objects based on the field value as a key could be worthwhile from the performance perspective, e.g. populate Maps once and find objects very efficiently
You can increase the memory allowed to php script by executing the following line above all the codes in the script:
ini_set('memory_limit','-1'); // enabled the full memory available.
And also de allocate the unwanted variables in the script.
Check this php library : Freeing memory with PHP
This can be done by using:
Response.Redirect("http://localhost/YourControllerName/ActionMethodName?querystring1=querystringvalue1&querystring2=querystringvalue2&querystring3=querystringvalue3");
You can find it here: RTL Bootstrap v3.2.0.
I know this is an older question, but I wanted to post an answer for users with the same question:
curl -H 'Cache-Control: no-cache' http://www.example.com
This curl command servers in its header request to return non-cached data from the web server.
You can do it code behind.
Set visible= false
for columns after data binding .
After that you can again do visibility "true" in row_selection function from grid view .It will work!!
<style name="Mytext" parent="@android:style/TextAppearance.Medium">
<item name="android:textSize">20sp</item>
<item name="android:textColor">@color/white</item>
<item name="android:textStyle">bold</item>
<item name="android:typeface">sans</item>
</style>
try this one ...
All the answers that include creating an new object from Form
class are absolutely creating new form
. But you can use Text
property of ActiveForm
subclass in Form
class. For example:
public Form1()
{
InitializeComponent();
Form1.ActiveForm.Text = "Your Title";
}
Maybe the span element is hidden. If that's the case then use the innerHtml property:
By.css:
String kk = wd.findElement(By.cssSelector("#customSelect_3 span.selectLabel"))
.getAttribute("innerHTML");
By.xpath:
String kk = wd.findElement(By.xpath(
"//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel')]"))
.getAttribute("innerHTML");
"/.//" means "look under the selected element".
Other proposals are a little cryptic, so I thought I'd contribute:
Object.prop = function(obj, prop, val){
var props = prop.split('.')
, final = props.pop(), p
while(p = props.shift()){
if (typeof obj[p] === 'undefined')
return undefined;
obj = obj[p]
}
return val ? (obj[final] = val) : obj[final]
}
var obj = { a: { b: '1', c: '2' } }
// get
console.log(Object.prop(obj, 'a.c')) // -> 2
// set
Object.prop(obj, 'a.c', function(){})
console.log(obj) // -> { a: { b: '1', c: [Function] } }
Josh's comments are spot on. If you are not super familiar with critical values I'd suggest playing with qt, reading the manual (?qt
) in conjunction with looking at a look up table (LINK). When I first moved from SPSS to R I created a function that made critical t value look up pretty easy (I'd never use this now as it takes too much time and with the p values that are generally provided in the output it's a moot point). Here's the code for that:
critical.t <- function(){
cat("\n","\bEnter Alpha Level","\n")
alpha<-scan(n=1,what = double(0),quiet=T)
cat("\n","\b1 Tailed or 2 Tailed:\nEnter either 1 or 2","\n")
tt <- scan(n=1,what = double(0),quiet=T)
cat("\n","\bEnter Number of Observations","\n")
n <- scan(n=1,what = double(0),quiet=T)
cat("\n\nCritical Value =",qt(1-(alpha/tt), n-2), "\n")
}
critical.t()
This answer works in SQL Server 2005, 2008, 2012.
At times the value has MANY single quotes. Rather than add a single quote next to each single quote as described above with 'John''s'
. And there are examples using the REPLACE
function to handle many single quotes in a value.
Try the following. This is an update statement but you can use it in an INSERT
statement as well.
SET QUOTED_IDENTIFIER OFF
DECLARE @s VARCHAR(1000)
SET @s = "SiteId:'1'; Rvc:'6'; Chk:'1832'; TrEmp:'150'; WsId:'81'; TtlDue:'-9.40'; TtlDsc:'0'; TtlSvc:'0'; TtlTax:'-0.88'; TtlPay:'0'; TipAmt:'0.00'; SvcSeq:'09'; ReTx:'N'; TraceId:'160110124347N091832';"
UPDATE TransactionPaymentPrompt
set PromptData = @s
from TransactionPaymentPrompt tpp with (nolock)
where tpp.TransactionID = '106627343'
This worked for me, saving to child dir(temp_pdf
) under the root:
$sFilePath = $_SERVER['DOCUMENT_ROOT'] . '//temp_pdf/file.pdf' ;
$pdf->Output( $sFilePath , 'F');
Remember to make the dir writeable.
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
Add the following to your on button click event:
Intent intent = new Intent(First.this, Second.class);
startActivity(intent);
finish();
android:layout_gravity="bottom"
This is because strings are immutable in Python.
Which means that X.replace("hello","goodbye")
returns a copy of X
with replacements made. Because of that you need replace this line:
X.replace("hello", "goodbye")
with this line:
X = X.replace("hello", "goodbye")
More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace
,strip
,translate
,lower
/upper
,join
,...
You must assign their output to something if you want to use it and not throw it away, e.g.
X = X.strip(' \t')
X2 = X.translate(...)
Y = X.lower()
Z = X.upper()
A = X.join(':')
B = X.capitalize()
C = X.casefold()
and so on.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
To Join two string in SQL Query use function CONCAT(Express1,Express2,...)
Like....
SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
try putting a delay on the last color fade.
$("p#44.test").delay(3000).css("background-color","red");
What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!
In Python 3.2+, you can use int.to_bytes:
>>> n = 1245427
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x13\x00\xf3'
>>> (1245427).to_bytes(3, byteorder='big')
b'\x13\x00\xf3'
This example uses Bash's built-in getopts
command and is from the Google Shell Style Guide:
a_flag=''
b_flag=''
files=''
verbose='false'
print_usage() {
printf "Usage: ..."
}
while getopts 'abf:v' flag; do
case "${flag}" in
a) a_flag='true' ;;
b) b_flag='true' ;;
f) files="${OPTARG}" ;;
v) verbose='true' ;;
*) print_usage
exit 1 ;;
esac
done
Note: If a character is followed by a colon (e.g. f:
), that option is expected to have an argument.
Example usage: ./script -v -a -b -f filename
Using getopts has several advantages over the accepted answer:
-a -b -c
? -abc
)However, a big disadvantage is that it doesn't support long options, only single-character options.
>>> import tensorflow as tf
>>> print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Num GPUs Available: 2
TLDR for people comming from c++
It's just overloaded operator of ( )
parentheses
So in scala:
class X {
def apply(param1: Int, param2: Int, param3: Int) : Int = {
// Do something
}
}
Is same as this in c++:
class X {
int operator()(int param1, int param2, int param3) {
// do something
}
};
"a" is an integer, when divided with integer it gives you an integer. Then it is assigned to "b" as an integer and becomes a float.
You should do it like this
b = a / 350.0;
if(sender is TextBox) {
var text = (sender as TextBox).Text;
}
Using mysqli i've created following function. Asuming you have an mysqli instance called $con.
function table_exist($table){
global $con;
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by @jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table
var is clean or even better use parameterised queries.
HTML
<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>
JavaScript
jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));
A simple thing. Disable the vsphere options 3D for the virtual maschine . It works perfect. When you want, reinstall the vm-tools for the virtual maschine.
The best idea is to make js file generation with name + some hash with version, if you do need to clear cache, just generate new files with new hash, this will trigger browser to load new files
$(document).ready(function(){_x000D_
$('.cliked').click(function() {_x000D_
$(".cliked").removeClass("liactive");_x000D_
$(this).addClass("liactive");_x000D_
});_x000D_
});
_x000D_
.liactive {_x000D_
background: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul_x000D_
className="sidebar-nav position-fixed "_x000D_
style="height:450px;overflow:scroll"_x000D_
>_x000D_
<li>_x000D_
<a className="cliked liactive" href="#">_x000D_
check Kyc Status_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Investments_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My SIP_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Tax Savers Fund_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Transaction History_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Invest Now_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Profile_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
FAQ`s_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Suggestion Portfolio_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Bluk Lumpsum / Bulk SIP_x000D_
</a>_x000D_
</li>_x000D_
</ul>;
_x000D_
r = requests.get('https://api.github.com', auth=('user', 'pass'))
r
is a response. It has a request attribute which has the information you need.
r.request.allow_redirects r.request.headers r.request.register_hook
r.request.auth r.request.hooks r.request.response
r.request.cert r.request.method r.request.send
r.request.config r.request.params r.request.sent
r.request.cookies r.request.path_url r.request.session
r.request.data r.request.prefetch r.request.timeout
r.request.deregister_hook r.request.proxies r.request.url
r.request.files r.request.redirect r.request.verify
r.request.headers
gives the headers:
{'Accept': '*/*',
'Accept-Encoding': 'identity, deflate, compress, gzip',
'Authorization': u'Basic dXNlcjpwYXNz',
'User-Agent': 'python-requests/0.12.1'}
Then r.request.data
has the body as a mapping. You can convert this with urllib.urlencode
if they prefer:
import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)
depending on the type of the response the .data
-attribute may be missing and a .body
-attribute be there instead.
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
You have to go to the /etc/nginx/sites-enabled/
and if this is the default configuration, then there should be a file by name: default
.
Edit that file by defining your desired port; in the snippet below, we are serving the Nginx instance on port 81.
server {
listen 81;
}
To start the server, run the command line below;
sudo service nginx start
You may now access your application on port 81 (for localhost, http://localhost:81).
You might be getting the error i.e.
"This application has no explicit mapping for /error, so you are seeing this as a fallback."
This is because it is not scanning your Controller & Service classes which you have to specify in your main() class like this,
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
**@ComponentScan({"com.example.demo", "controller", "service"})**
public class SpringBootMvcExample1Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootMvcExample1Application.class, args);
}
}
Note: Here, I have specified various classes like demo, controller and service to be scanned then only it will work properly.
I had to investigate an endless recursion in smartgwt with IE11, so in order to investigate deeper, I needed a stack trace. The problem was, that I was unable to use the dev console, because the reproduction was more difficult that way.
Use the following in a javascript method:
try{ null.toString(); } catch(e) { alert(e.stack); }
Setting android:background
and android:button
of the RadioButton like the accepted answer didn't work for me. The drawable image was being displayed as a background(eventhough android:button
was being set to transparent ) to the radio button text as
android:background="@drawable/radiobuttonstyle"
android:button="@android:color/transparent"
so gave radiobutton as the custom drawable radiobuttonstyle.xml
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Maintenance"
android:id="@+id/radioButton1"
android:button="@drawable/radiobuttonstyle"
/>
and radiobuttonstyle.xml is as follows
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/ic_radio_checked"></item>
<item android:state_checked="false" android:drawable="@drawable/ic_radio_unchecked"></item>
</selector>
and after this radiobutton with custom button style worked.
For those who want a "standard" text formatting of the hash, you can use something like the following:
static string Hash(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
// can be "x2" if you want lowercase
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
This will produce a hash like 0C2E99D0949684278C30B9369B82638E1CEAD415
.
Or for a code golfed version:
static string Hash(string input)
{
var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));
return string.Concat(hash.Select(b => b.ToString("x2")));
}
In your Eclipse
installation directory you should be able to find the file eclipse.ini
. Open it and find the -vmargs
section. Adjust the value of:
-Xmx1024m
In this example it is set to 1GB.
There's no real danger in not freeing your variables, but if you assign a pointer to a block of memory to a different block of memory without freeing the first block, the first block is no longer accessible but still takes up space. This is what's called a memory leak, and if you do this with regularity then your process will start to consume more and more memory, taking away system resources from other processes.
If the process is short-lived you can often get away with doing this as all allocated memory is reclaimed by the operating system when the process completes, but I would advise getting in the habit of freeing all memory you have no further use for.
If using Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
Example:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;
, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.
When you apply the following CSS to an element
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.
Here's a Fiddle that demonstrates the effect.
HTML
<div id="mydiv" data-myval="10"></div>
JavaScript:
Using DOM's getAttribute()
property
var brand = mydiv.getAttribute("data-myval")//returns "10"
mydiv.setAttribute("data-myval", "20") //changes "data-myval" to "20"
mydiv.removeAttribute("data-myval") //removes "data-myval" attribute entirely
Using JavaScript's dataset
property
var myval = mydiv.dataset.myval //returns "10"
mydiv.dataset.myval = '20' //changes "data-myval" to "20"
mydiv.dataset.myval = null //removes "data-myval" attribute
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
I usually combine PointToScreen
and PointToClient
:
Point locationOnForm = control.FindForm().PointToClient(
control.Parent.PointToScreen(control.Location));
To change width is not that hard. Just remove the width
attribute from the tag and add width: 100%;
in the css for #canvas
#canvas{
border: solid 1px blue;
width: 100%;
}
Changing height is a bit harder: you need javascript. I have used jQuery because i'm more comfortable with.
you need to remove the height
attribute from the canvas tag and add this script:
<script>
function resize(){
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top- Math.abs($("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
}
$(document).ready(function(){
resize();
$(window).on("resize", function(){
resize();
});
});
</script>
You can see this fiddle: https://jsfiddle.net/1a11p3ng/3/
EDIT:
To answer your second question. You need javascript
0) First of all i changed your #border id into a class since ids must be unique for an element inside an html page (you can't have 2 tags with the same id)
.border{
border: solid 1px black;
}
#canvas{
border: solid 1px blue;
width: 100%;
}
1) Changed your HTML to add ids where needed, two inputs and a button to set the values
<div class="row">
<div class="col-xs-2 col-sm-2 border">content left</div>
<div class="col-xs-6 col-sm-6 border" id="main-content">
<div class="row">
<div class="col-xs-6">
Width <input id="w-input" type="number" class="form-control">
</div>
<div class="col-xs-6">
Height <input id="h-input" type="number" class="form-control">
</div>
<div class="col-xs-12 text-right" style="padding: 3px;">
<button id="set-size" class="btn btn-primary">Set</button>
</div>
</div>
canvas
<canvas id="canvas"></canvas>
</div>
<div class="col-xs-2 col-sm-2 border">content right</div>
</div>
2) Set the canvas height and width so that it fits inside the container
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
3) Set the values of the width and height forms
$("#h-input").val($("#canvas").outerHeight());
$("#w-input").val($("#canvas").outerWidth());
4) Finally, whenever you click on the button you set the canvas width and height to the values set. If the width value is bigger than the container's width then it will resize the canvas to the container's width instead (otherwise it will break your layout)
$("#set-size").click(function(){
$("#canvas").outerHeight($("#h-input").val());
$("#canvas").outerWidth(Math.min($("#w-input").val(), $("#main-content").width()));
});
See a full example here https://jsfiddle.net/1a11p3ng/7/
UPDATE 2:
To have full control over the width you can use this:
<div class="container-fluid">
<div class="row">
<div class="col-xs-2 border">content left</div>
<div class="col-xs-8 border" id="main-content">
<div class="row">
<div class="col-xs-6">
Width <input id="w-input" type="number" class="form-control">
</div>
<div class="col-xs-6">
Height <input id="h-input" type="number" class="form-control">
</div>
<div class="col-xs-12 text-right" style="padding: 3px;">
<button id="set-size" class="btn btn-primary">Set</button>
</div>
</div>
canvas
<canvas id="canvas">
</canvas>
</div>
<div class="col-xs-2 border">content right</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
$("#h-input").val($("#canvas").outerHeight());
$("#w-input").val($("#canvas").outerWidth());
$("#set-size").click(function(){
$("#canvas").outerHeight($("#h-input").val());
$("#main-content").width($("#w-input").val());
$("#canvas").outerWidth($("#main-content").width());
});
});
</script>
https://jsfiddle.net/1a11p3ng/8/
the content left and content right columns will move above and belove the central div if the width is too high, but this can't be helped if you are using bootstrap. This is not, however, what responsive means. a truly responsive site will adapt its size to the user screen to keep the layout as you have intended without any external input, letting the user set any size which may break your layout does not mean making a responsive site.
Any user whose login shell setting in /etc/passwd
is an interactive shell can login. I don't think there's a totally reliable way to tell if a program is an interactive shell; checking whether it's in /etc/shells
is probably as good as you can get.
Other users can also login, but the program they run should not allow them to get much access to the system. And users that aren't allowed to login at all should have /etc/false
as their shell -- this will just log them out immediately.
Answers on how to do it using an array are provided here.
However, C# has a very handy thing called System.Collections :)
Collections are fancy alternatives to using an array, though many of them use an array internally.
For example, C# has a collection called List that functions very similar to the PHP array.
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
In my case, I have to run some more steps to build it on RedHat or Centos.
# get system libraries
sudo yum install -y gcc wget
# get stable version and untar it
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
# build dependencies too!
cd deps
make hiredis jemalloc linenoise lua geohash-int
cd ..
# compile it
make
# make it globally accesible
sudo cp src/redis-cli /usr/bin/
GROUP BY
lets you use aggregate functions, like AVG
, MAX
, MIN
, SUM
, and COUNT
.
On the other hand DISTINCT
just removes duplicates.
For example, if you have a bunch of purchase records, and you want to know how much was spent by each department, you might do something like:
SELECT department, SUM(amount) FROM purchases GROUP BY department
This will give you one row per department, containing the department name and the sum of all of the amount
values in all rows for that department.
If you are using ASP.NET Core you could try out the nuget package SaidOut.AspNetCore.HttpsWithStrictTransportSecurity.
Then you only need to add
app.UseHttpsWithHsts(HttpsMode.AllowedRedirectForGet, configureRoutes: routeAction);
This will also add HTTP StrictTransportSecurity header to all request made using https scheme.
Example code and documentation https://github.com/saidout/saidout-aspnetcore-httpswithstricttransportsecurity#example-code
Solution for windows users: XAMPP
Go to: path:\xampp\apache\conf\extra
Open file named httpd-vhosts.conf
comment below lines if they are enabled: comment all lines in between <VirtualHost *:80> all lines between </VirtualHost
According to the doc about Run tests by node ids
since you have all node ids in foo.txt, just run
pytest `cat foo.txt | tr '\n' ' '`
this is same with below command (with file content in the question)
pytest tests_directory/foo.py::test_001 tests_directory/bar.py::test_some_other_test
Methods suggest something has to happen to return the value, properties suggest that the value is already there. This is a rule of thumb, sometimes you might want a property that does a little work (i.e. Count
), but generally it's a useful way to decide.
Ideally you should do both.
First Hash the pass password for the one way security. Use a salt for extra security.
Then encrypt the hash to defend against dictionary attacks if your database of password hashes is compromised.
You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.
void addNode(struct Node *&head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
What about the css opacity
attribute? 0
to 1
values.
But then you probably need to use a more explicit dom element than "font". For instance:
<html><body><span style=\"opacity: 0.5;\"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></span></body></html>
As an additional information I would of course suggest you use CSS declarations outside of your html elements, but as well try to use the font css style instead of the font html tag.
For cross browser css3 styles generator, have a look at http://css3please.com/
The density plot can also be created by using matplotlib: The function plt.hist(data) returns the y and x values necessary for the density plot (see the documentation https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html). Resultingly, the following code creates a density plot by using the matplotlib library:
import matplotlib.pyplot as plt
dat=[-1,2,1,4,-5,3,6,1,2,1,2,5,6,5,6,2,2,2]
a=plt.hist(dat,density=True)
plt.close()
plt.figure()
plt.plot(a[1][1:],a[0])
This code returns the following density plot
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
Maybe use outline property
<div class="borders">
Hello
</div>
.borders{
border: 1px solid grey;
outline: 2px solid white;
}
Generally, no, do not define functions inside functions.
Unless you have a really good reason. Which you don't.
Why not?
lambda
expression instead.What is a really good reason to define functions inside functions?
When what you actually want is a dingdang closure.
For .net core 2.1 console application, the following approaches worked for me:
1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):
dotnet appName.dll
2 - from Visual Studio
R.C solution and click publish
'Target location' -> 'configure' ->
'Deployment Mode' = 'Self-Contained'
'Target Runtime' = 'win-x64 or win-x86 depending on the OS'
References:
For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:
you can follow this step,
By reseeding table
you can delete the data of the table.
delete from table_name
dbcc checkident('table_name',reseed,0)
if some error comes then you have to reseed the primary table.
Since Rails 4 you can do:
User.find_by(name: 'Bob')
which is the equivalent find_by_name
in Rails 3.
Use #where
when #find
and #find_by
are not enough.
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if blabla in line:
found = True
break
return found
if check():
print "true"
else:
print "false"
I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.
I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:
<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">
but it should be:
<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">
Just change <scrip>
to <link>
and src
to href
Use bases if you just want to get the parents, use __mro__
(as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).
Bases (and first getting the class for an existing object):
>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)
For mro in recent Python versions:
>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)
Obviously, when you already have a class definition, you can just call __mro__
on that directly:
>>> class A(): pass
>>> A.__mro__
(__main__.A, object)
While I'm sure there is a better way, nuking only took me less than 60 seconds, and was the only thing I could find that worked.
git remote add <url.git>
, or git remote set-url <url.git>
Use this code..
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
public class ImageUtil
{
public static Bitmap convert(String base64Str) throws IllegalArgumentException
{
byte[] decodedBytes = Base64.decode( base64Str.substring(base64Str.indexOf(",") + 1), Base64.DEFAULT );
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
public static String convert(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
}
This might be useful
function showProps(obj, objName) {
var result = "";
for (var i in obj)
result += objName + "." + i + " = " + obj[i] + "\n";
return result;
}
Copied this from https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects
I had the same issue, and the answer was in the dmenu source code: the stest utility made for that purpose. You can compile the 'stest.c' and 'arg.h' files and it should work. There is a man page for the usage, that I put there for convenience:
STEST(1) General Commands Manual STEST(1)
NAME
stest - filter a list of files by properties
SYNOPSIS
stest [-abcdefghlpqrsuwx] [-n file] [-o file]
[file...]
DESCRIPTION
stest takes a list of files and filters by the
files' properties, analogous to test(1). Files
which pass all tests are printed to stdout. If no
files are given, stest reads files from stdin.
OPTIONS
-a Test hidden files.
-b Test that files are block specials.
-c Test that files are character specials.
-d Test that files are directories.
-e Test that files exist.
-f Test that files are regular files.
-g Test that files have their set-group-ID
flag set.
-h Test that files are symbolic links.
-l Test the contents of a directory given as
an argument.
-n file
Test that files are newer than file.
-o file
Test that files are older than file.
-p Test that files are named pipes.
-q No files are printed, only the exit status
is returned.
-r Test that files are readable.
-s Test that files are not empty.
-u Test that files have their set-user-ID flag
set.
-v Invert the sense of tests, only failing
files pass.
-w Test that files are writable.
-x Test that files are executable.
EXIT STATUS
0 At least one file passed all tests.
1 No files passed all tests.
2 An error occurred.
SEE ALSO
dmenu(1), test(1)
dmenu-4.6 STEST(1)
Here is another possibility, again with Java 8 Streams:
void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
Beware of the use of push method, if you don't use indexes, it won't work!
var main2dArray: Things[][] = []
main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)
gives only a 1 line array!
use
main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray
to get your 2d array working!!!
Other beware! foreach doesn't seem to work with 2d arrays!
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
You can use FormData to submit your data by a POST request. Here is a simple example:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).
top -b -n 1 | mail -s "any subject" [email protected]
The easy and clear way for casting an int to enum in C#:
public class Program
{
public enum Color : int
{
Blue = 0,
Black = 1,
Green = 2,
Gray = 3,
Yellow = 4
}
public static void Main(string[] args)
{
// From string
Console.WriteLine((Color) Enum.Parse(typeof(Color), "Green"));
// From int
Console.WriteLine((Color)2);
// From number you can also
Console.WriteLine((Color)Enum.ToObject(typeof(Color), 2));
}
}
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">#C1000E</item>
<item name="android:titleTextStyle">@style/AppTheme.ActionBar.TitleTextStyle</item>
</style>
<style name="AppTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.StatusBar.Title">
<item name="android:textColor">#E5ED0E</item>
</style>
I have Solved Using That.
You can try this:
<a href="link.html">
<input type="button" value="Visit Page" />
</a>
This will create button inside a link and it works on any browser
call() It’s a predefined method in javascript. This method invokes a method (function) by specifying the owner object.
function sayHello(){
return "Hello " + this.name;
}
var obj = {name: "Sandy"};
sayHello.call(obj);
// Returns "Hello Sandy"
Call accepts argument
function saySomething(message){
return this.name + " is " + message;
}
var person4 = {name: "John"};
saySomething.call(person4, "awesome");
// Returns "John is awesome"
apply() The apply method is similar to the call() method. The only difference is that, call() method takes arguments separately whereas, apply() method takes arguments as an array.
example
function saySomething(message){
return this.name + " is " + message;
}
var person4 = {name: "John"};
saySomething.apply(person4, ["awesome"]);
sklearn.model_selection.train_test_split(*arrays, **options)[source]
Split arrays or matrices into random train and test subsets
Parameters: ...
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. source: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
'''Regarding the random state, it is used in many randomized algorithms in sklearn to determine the random seed passed to the pseudo-random number generator. Therefore, it does not govern any aspect of the algorithm's behavior. As a consequence, random state values which performed well in the validation set do not correspond to those which would perform well in a new, unseen test set. Indeed, depending on the algorithm, you might see completely different results by just changing the ordering of training samples.''' source: https://stats.stackexchange.com/questions/263999/is-random-state-a-parameter-to-tune