There are multiple ways to write same logic. As it mentioned earlier, you can use object notation or simply expression. However, I think you should not that much logic in HTML. Hard to test and find issue. You can use a getter function to assign the class.
For Instance;
public getCustomCss() {
//Logic here;
if(this.x == this.y){
return 'class1'
}
if(this.x == this.z){
return 'class2'
}
}
<!-- HTML -->
<div [ngClass]="getCustomCss()"> Some prop</div>
//OR
get customCss() {
//Logic here;
if(this.x == this.y){
return 'class1'
}
if(this.x == this.z){
return 'class2'
}
}
<!-- HTML -->
<div [ngClass]="customCss"> Some prop</div>
This does happened also when you are cloning a repo without selecting any working directory. just make sure you did cd
into your working directory and i believe it will work just fine.
This can be done as
list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) );
The .NET framework is casting the lambda (emp1,emp2)=>int
as a Comparer<Employee>.
This has the advantage of being strongly typed.
Call ToString()
instead of casting the reader result.
reader[0].ToString();
reader[1].ToString();
// etc...
And if you want to fetch specific data type values (int
in your case) try the following:
reader.GetInt32(index);
You can't compare two Integer
with a simple ==
they're objects so most of the time references won't be the same.
There is a trick, with Integer
between -128 and 127, references will be the same as autoboxing uses Integer.valueOf()
which caches small integers.
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
Resources :
On the same topic :
You can do it with javascript, and I don't think it needs to be that fancy.
If you have a header.js file and a footer.js.
Then the contents of header.js could be something like
document.write("<div class='header'>header content</div> etc...")
Remember to escape any nested quote characters in the string you are writing. You could then call that from your static templates with
<script type="text/javascript" src="header.js"></script>
and similarly for the footer.js.
Note: I am not recommending this solution - it's a hack and has a number of drawbacks (poor for SEO and usability just for starters) - but it does meet the requirements of the questioner.
Here is a SUPER SIMPLE implementation/example of a FSM using just "if-else"s which avoids all of the above subclassing answers (taken from Using Finite State Machines for Pattern Matching in Java, where he is looking for a string which ends with "@" followed by numbers followed by "#"--see state graph here):
public static void main(String[] args) {
String s = "A1@312#";
String digits = "0123456789";
int state = 0;
for (int ind = 0; ind < s.length(); ind++) {
if (state == 0) {
if (s.charAt(ind) == '@')
state = 1;
} else {
boolean isNumber = digits.indexOf(s.charAt(ind)) != -1;
if (state == 1) {
if (isNumber)
state = 2;
else if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
} else if (state == 2) {
if (s.charAt(ind) == '#') {
state = 3;
} else if (isNumber) {
state = 2;
} else if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
} else if (state == 3) {
if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
}
}
} //end for loop
if (state == 3)
System.out.println("It matches");
else
System.out.println("It does not match");
}
P.S: Does not answer your question directly, but shows you how to implement a FSM very easily in Java.
You can do:
timeStamp.toLocalDateTime().toLocalDate();
Note that
timestamp.toLocalDateTime()
will use theClock.systemDefaultZone()
time zone to make the conversion. This may or may not be what you want.
Edit: Use printf("val = 0x%" PRIx64 "\n", val);
instead.
Try printf("val = 0x%llx\n", val);
. See the printf manpage:
ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.
Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t
is not always a unsigned long long
: PRIx64
see also this stackoverflow answer
I'm on Windows 10 x64 and Visual Studio 2017. I copied and pasted rc.exe and rcdll.dll from:
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
to
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64
it's works with: ( qt creator 5.7.1)
I got this error loading a http:// URL where the server replied with a redirect to https. After changing the URL I pass to WKWebView to https://... it worked.
In android studio:
It worked fine for me from there.
There are already a lot of answers, but none worked for me... So this is what I'm using now.
readlink_f() {
local target="$1"
[ -f "$target" ] || return 1 #no nofile
while [ -L "$target" ]; do
target="$(readlink "$target")"
done
echo "$(cd "$(dirname "$target")"; pwd -P)/$target"
}
In an application level, here are something a developer can do:
From server side:
Check if load balancer(if you have),works correctly.
Turn slow TCP timeouts into 503 Fast Immediate response, if you load balancer work correctly, it should pick the working resource to serve, and it's better than hanging there with unexpected error massages.
Eg: If you are using node server, u can use toobusy from npm. Implementation something like:
var toobusy = require('toobusy');
app.use(function(req, res, next) {
if (toobusy()) res.send(503, "I'm busy right now, sorry.");
else next();
});
Why 503? Here are some good insights for overload: http://ferd.ca/queues-don-t-fix-overload.html
We can do some work in client side too:
Try to group calls in batch, reduce the traffic and total requests number b/w client and server.
Try to build a cache mid-layer to handle unnecessary duplicates requests.
I used couple of hours trying to figure how to remove background from launched modal, so far tried
.modal-backdrop { background: none; }
Didn't work even I have tried to work with javascript like
<script type="text/javascript">
$('#modal-id').on('shown.bs.modal', function () {
$(".modal-backdrop.in").hide(); })
</script>
Also didn't work either. I just added
data-backdrop="false"
to
<div class="modal fade" id="myModal" data-backdrop="false">......</div>
And Applying css CLASS
.modal { background-color: transparent !important; }
Now its working like a charm This worked with Bootstrap 3
It can be done, I found it elsewhere on the web...this is no way my work ! :)
Option Explicit
' Import
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long
Private Declare Function SetDlgItemText Lib "user32" _
Alias "SetDlgItemTextA" _
(ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal lpString As String) As Long
Private Declare Function SetWindowsHookEx Lib "user32" _
Alias "SetWindowsHookExA" _
(ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" _
(ByVal hHook As Long) As Long
' Handle to the Hook procedure
Private hHook As Long
' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
' Constants
Public Const IDOK = 1
Public Const IDCANCEL = 2
Public Const IDABORT = 3
Public Const IDRETRY = 4
Public Const IDIGNORE = 5
Public Const IDYES = 6
Public Const IDNO = 7
Public Sub MsgBoxSmile()
' Set Hook
hHook = SetWindowsHookEx(WH_CBT, _
AddressOf MsgBoxHookProc, _
0, _
GetCurrentThreadId)
' Run MessageBox
MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"
End Sub
Private Function MsgBoxHookProc(ByVal lMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
If lMsg = HCBT_ACTIVATE Then
SetDlgItemText wParam, IDYES, "Yes :-)"
SetDlgItemText wParam, IDNO, "No :-("
' Release the Hook
UnhookWindowsHookEx hHook
End If
MsgBoxHookProc = False
End Function
Google allows you to search in the project, but not the code :(
What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a class
, or an interface
does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.
Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:
In typical usage, the TypeSpec (if present) identifies a delegate whose signature matches the arguments passed to the event’s fire method.
However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a List
or a Dictionary
or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.
Add FormsModule
in Imports Array.
i.e
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Or this can be done without using [(ngModel)]
by using
<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">
instead of
<input [(ngModel)]="hero.name" placeholder="Name">
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
For IDEA 13 and OS X 10.9 Mavericks, the correct paths are:
Original: /Applications/IntelliJ IDEA 13.app/Contents/bin/idea.vmoptions
Copy to: ~/Library/Preferences/IntelliJIdea13/idea.vmoptions
header( 'Location: http://www.yoursite.com/new_page.html' );
in your process.php file
Since your list doesn't appear to be sorted, you have to iterate over its elements. Apply startsWith()
or contains()
to each element, and store matches in an auxiliary list. Return the auxiliary list when done.
Use Fiddler to see what is happening. Then change the path accordingly. You will probably find you get a 404 error and the path is wrong.
You do not need to use an anonymous function with setTimeout
. You can do something like this:
setTimeout(doSomething, 3000);
function doSomething() {
//do whatever you want here
}
The base dn is dc=example,dc=com
.
I don't know about openca, but I will try this answer since you got very little traffic so far.
A base dn is the point from where a server will search for users. So I would try to simply use admin
as a login name.
If openca behaves like most ldap aware applications, this is what is going to happen :
admin
will be done by the server starting at the base dn (dc=example,dc=com
).cn=admin,dc=example,dc=com
) will be used to bind with the supplied password.Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :
dn
your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com
.objectClass
for your admin
user. It will be either inetOrgPerson
or user
. There will be others like top
, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson)
. Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user))
. Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.
If it's a major concern to start doing a lot of testing on a Mac, then I would definitely suggest buying a second hand Mac, or perhaps building a Hackintosh. The former gets you up and running quickly, the latter gives you a lot of power for the same price.
For just the odd piece of testing, running OS X in VMWare on your current PC is a cheaper option.
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
This is what I've been using for development:
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.
I dont know if this useful for you when you resize your page:
$(window).resize(function() {
if(screen.width == window.innerWidth){
alert("you are on normal page with 100% zoom");
} else if(screen.width > window.innerWidth){
alert("you have zoomed in the page i.e more than 100%");
} else {
alert("you have zoomed out i.e less than 100%");
}
});
Oracle 10g Express Edition ships with Oracle Application Express (Apex) built-in. You're running this in its SQL Commands window, which doesn't support SQL*Plus syntax.
That doesn't matter, because (as you have discovered) the BEGIN...END syntax does work in Apex.
Another non-allocating alternative: create a singleton, say of class C
, as you need it:
singleton<C>()
using
template <class X>
X& singleton()
{
static X x;
return x;
}
Neither this nor Catalin's answer is automatically thread-safe in current C++, but will be in C++0x.
Old but still valid question, so heres what I created based on the info provided by others here.
create function fnLastIndexOf(@text varChar(max),@char varchar(1))
returns int
as
begin
return len(@text) - charindex(@char, reverse(@text)) -1
end
For Mac OS X, save your CSV file in "Windows Comma Separated (.csv)" format.
Let's first make it clear what's going on.
MySQL 8 has supports pluggable authentication methods. By default, one of them named caching_sha2_password
is used rather than our good old mysql_native_password
(source). It should be obvious that using a crypto algorithm with several handshakes is more secure than plain password passing that has been there for 24 years!
Now, the problem is mysqljs
in Node (the package you install with npm i mysql
and use it in your Node code) doesn't support this new default authentication method of MySQL 8, yet. The issue is in here: https://github.com/mysqljs/mysql/issues/1507 and is still open, after 3 years, as of July 2019.
UPDATE June 2019: There is a new PR in mysqljs now to fix this!
UPDATE Feb 2020: Apparently it's scheduled to come in version 3 of mysqljs.
UPDATE July 2020: Apparently it's still not in yet (as of April 2020 at least), but it's claimed that node-mysql2 is supporting Authentication switch request. Please comment below if node-mysql2
is working fine for this issue -- I will test it later myself.
That's what everybody suggests here (e.g. top answer above). You just get into mysql
and run a query saying root
is fine using old mysql_native_password
method for authentication:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password ...
The good thing is, life is going to be simple and you can still use good old tools like Sequel Pro without any issue. But the problem is, you are not taking advantage of a more secure (and cool, read below) stuffs available to you.
MySQL X DevAPI for Node is a replacement to Node's Mysqljs package, provided by http://dev.mysql.com official guys.
It works like a charm supporting caching_sha2_password
authentication. (Just make sure you use port 33060
for X Protocol communications.)
The bad thing is, you have left our old mysql
package that everyone is so used to and relies on.
The good thing is, your app is more secure now and you can take advantage of a ton of new things that our good old friends didn't provide! Just check out the tutorial of X DevAPI and you'll see it has a ton of new sexy features that can come in handy. You just need to pay the price of a learning curve, which expectedly comes with any technology upgrade. :)
PS. Unfortunately, this XDevAPI Package doesn't have types definition (understandable by TypeScript) yet, so if you are on typescript, you will have problems. I tried to generate .d.ts using dts-gen
and dtsmake
, but no success. So keep that in mind.
Cheers!
In spring boot 2.x you need to reference provider specific properties.
The default, hikari can be set with spring.datasource.hikari.maximum-pool-size
.
Yes. You can use foreach to update the records in linq.There is no performance degrade.
you can verify that the standard Where operator is implemented using the yield construct introduced in C# 2.0.
The use of yield has an interesting benefit which is that the query is not actually evaluated until it is iterated over, either with a foreach statement or by manually using the underlying GetEnumerator and MoveNext methods
For instance,
var query = db.Customers.Where (c => c.Name.StartsWith ("A"));
query = query.Where (c => c.Purchases.Count() >= 2);
var result = query.Select (c => c.Name);
foreach (string name in result) // Only now is the query executed!
Console.WriteLine (name);
Exceptional operators are: First, ElementAt, Sum, Average, All, Any, ToArray and ToList force immediate query evaluation.
So no need to scare to use foreach
for update
the linq result.
In your case code sample given below will be useful to update many properties,
var persons = (from p in Context.person_account_portfolio where p.person_name == personName select p);
//TO update using foreach
foreach(var person in persons)
{
//update property values
}
I hope it helps...
Here is the Swift 2.0 code for the solution that has been provided in accepted answer:
//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibilityIsReduceTransparencyEnabled() {
self.view.backgroundColor = UIColor.clearColor()
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
//always fill the view
blurEffectView.frame = self.view.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed
} else {
self.view.backgroundColor = UIColor.blackColor()
}
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
There is confusing when you are using data picker, for bootstrap datepicker you have to use following code:-
$( ".datepicker" ).datepicker({
format: 'yyyy-mm-dd'
});
and for jquery datepicker following code must be used:-
$( ".datepicker" ).datepicker({
dateFormat: 'dd-mm-yy'
});
So you must be aware which date picker you are using, that is ultimately solve your issue, Hope this hepls you.
Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.
Find a way here without relocating.
a := []string{"A", "B", "C", "D", "E"}
i := 2
// Remove the element at index i from a.
a[i] = a[len(a)-1] // Copy last element to index i.
a[len(a)-1] = "" // Erase last element (write zero value).
a = a[:len(a)-1] // Truncate slice.
fmt.Println(a) // [A B E D]
a := []string{"A", "B", "C", "D", "E"}
i := 2
// Remove the element at index i from a.
copy(a[i:], a[i+1:]) // Shift a[i+1:] left one index.
a[len(a)-1] = "" // Erase last element (write zero value).
a = a[:len(a)-1] // Truncate slice.
fmt.Println(a) // [A B D E]
Using next
or readlines
etc, is not necessary. As the documentation says: "For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code".
Here's an example:
with open('/path/to/file') as myfile:
for line in myfile:
print(line)
If you can't find your settings.gradle file in your project directory
Add settings.gradle file
Add include ':app' inside the settings.gradle file
Rebuild or sync your project
Your app module should appear in your configuration file.
The Main method is the Entry point of your application. If you checkout via ildasm
then
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
This is what helps in calling the method
The arguments are passed as say C:\AppName arg1 arg2 arg3
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
I assume you calculated the "depth of 1024" by the recurring lines in the stack trace?
Obviously, the stack trace array length in Throwable seems to be limited to 1024. Try the following program:
public class Test {
public static void main(String[] args) {
try {
System.out.println(fact(1 << 15));
}
catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was " +
e.getStackTrace().length);
}
}
private static int level = 0;
public static long fact(int n) {
level++;
return n < 2 ? n : n * fact(n - 1);
}
}
I think Microsoft guide for ASP.NET Identity is a good start.
Note:
If you do not use AccountController and wan't to reset your password, use Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
. If you dont have the same OwinContext you need to create a new DataProtectorTokenProvider
like the one OwinContext
uses. By default look at App_Start -> IdentityConfig.cs
. Should look something like new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
.
Could be created like this:
Without Owin:
[HttpGet]
[AllowAnonymous]
[Route("testReset")]
public IHttpActionResult TestReset()
{
var db = new ApplicationDbContext();
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
var provider = new DpapiDataProtectionProvider("SampleAppName");
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
provider.Create("SampleTokenName"));
var email = "[email protected]";
var user = new ApplicationUser() { UserName = email, Email = email };
var identityUser = manager.FindByEmail(email);
if (identityUser == null)
{
manager.Create(user);
identityUser = manager.FindByEmail(email);
}
var token = manager.GeneratePasswordResetToken(identityUser.Id);
return Ok(HttpUtility.UrlEncode(token));
}
[HttpGet]
[AllowAnonymous]
[Route("testReset")]
public IHttpActionResult TestReset(string token)
{
var db = new ApplicationDbContext();
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
var provider = new DpapiDataProtectionProvider("SampleAppName");
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
provider.Create("SampleTokenName"));
var email = "[email protected]";
var identityUser = manager.FindByEmail(email);
var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync("ResetPassword", token, manager, identityUser)).Result;
var result = manager.ResetPassword(identityUser.Id, token, "TestingTest1!");
return Ok(result);
}
With Owin:
[HttpGet]
[AllowAnonymous]
[Route("testResetWithOwin")]
public IHttpActionResult TestResetWithOwin()
{
var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var email = "[email protected]";
var user = new ApplicationUser() { UserName = email, Email = email };
var identityUser = manager.FindByEmail(email);
if (identityUser == null)
{
manager.Create(user);
identityUser = manager.FindByEmail(email);
}
var token = manager.GeneratePasswordResetToken(identityUser.Id);
return Ok(HttpUtility.UrlEncode(token));
}
[HttpGet]
[AllowAnonymous]
[Route("testResetWithOwin")]
public IHttpActionResult TestResetWithOwin(string token)
{
var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var email = "[email protected]";
var identityUser = manager.FindByEmail(email);
var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync("ResetPassword", token, manager, identityUser)).Result;
var result = manager.ResetPassword(identityUser.Id, token, "TestingTest1!");
return Ok(result);
}
The DpapiDataProtectionProvider
and DataProtectorTokenProvider
needs to be created with the same name for a password reset to work. Using Owin for creating the password reset token and then creating a new DpapiDataProtectionProvider
with another name won't work.
Code that I use for ASP.NET Identity:
Web.Config:
<add key="AllowedHosts" value="example.com,example2.com" />
AccountController.cs:
[Route("RequestResetPasswordToken/{email}/")]
[HttpGet]
[AllowAnonymous]
public async Task<IHttpActionResult> GetResetPasswordToken([FromUri]string email)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var user = await UserManager.FindByEmailAsync(email);
if (user == null)
{
Logger.Warn("Password reset token requested for non existing email");
// Don't reveal that the user does not exist
return NoContent();
}
//Prevent Host Header Attack -> Password Reset Poisoning.
//If the IIS has a binding to accept connections on 80/443 the host parameter can be changed.
//See https://security.stackexchange.com/a/170759/67046
if (!ConfigurationManager.AppSettings["AllowedHosts"].Split(',').Contains(Request.RequestUri.Host)) {
Logger.Warn($"Non allowed host detected for password reset {Request.RequestUri.Scheme}://{Request.Headers.Host}");
return BadRequest();
}
Logger.Info("Creating password reset token for user id {0}", user.Id);
var host = $"{Request.RequestUri.Scheme}://{Request.Headers.Host}";
var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = $"{host}/resetPassword/{HttpContext.Current.Server.UrlEncode(user.Email)}/{HttpContext.Current.Server.UrlEncode(token)}";
var subject = "Client - Password reset.";
var body = "<html><body>" +
"<h2>Password reset</h2>" +
$"<p>Hi {user.FullName}, <a href=\"{callbackUrl}\"> please click this link to reset your password </a></p>" +
"</body></html>";
var message = new IdentityMessage
{
Body = body,
Destination = user.Email,
Subject = subject
};
await UserManager.EmailService.SendAsync(message);
return NoContent();
}
[HttpPost]
[Route("ResetPassword/")]
[AllowAnonymous]
public async Task<IHttpActionResult> ResetPasswordAsync(ResetPasswordRequestModel model)
{
if (!ModelState.IsValid)
return NoContent();
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null)
{
Logger.Warn("Reset password request for non existing email");
return NoContent();
}
if (!await UserManager.UserTokenProvider.ValidateAsync("ResetPassword", model.Token, UserManager, user))
{
Logger.Warn("Reset password requested with wrong token");
return NoContent();
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Token, model.NewPassword);
if (result.Succeeded)
{
Logger.Info("Creating password reset token for user id {0}", user.Id);
const string subject = "Client - Password reset success.";
var body = "<html><body>" +
"<h1>Your password for Client was reset</h1>" +
$"<p>Hi {user.FullName}!</p>" +
"<p>Your password for Client was reset. Please inform us if you did not request this change.</p>" +
"</body></html>";
var message = new IdentityMessage
{
Body = body,
Destination = user.Email,
Subject = subject
};
await UserManager.EmailService.SendAsync(message);
}
return NoContent();
}
public class ResetPasswordRequestModel
{
[Required]
[Display(Name = "Token")]
public string Token { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 10)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
An application server is a machine (an executable process running on some machine, actually) that "listens" (on any channel, using any protocol), for requests from clients for whatever service it provides, and then does something based on those requests. (may or may not involve a respose to the client)
A Web server is process running on a machine that "listens" specifically on TCP/IP Channel using one of the "internet" protocols, (http, https, ftp, etc..) and does whatever it does based on those incoming requests... Generally, (as origianly defined), it fetched/generated and returned an html web page to the client, either fetched from a static html file on the server, or constructed dynamically based on parameters in the incoming client request.
Here's a way you can request info about the browser being used, you can use this to do your if statement
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform + "\n"
+ "Is Beta = " + browser.Beta + "\n"
+ "Is Crawler = " + browser.Crawler + "\n"
+ "Is AOL = " + browser.AOL + "\n"
+ "Is Win16 = " + browser.Win16 + "\n"
+ "Is Win32 = " + browser.Win32 + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n";
Since someone mentioned efficiency, I've benchmarked the functions given so far out of curiosity:
function startsWith1($str, $char) {
return strpos($str, $char) === 0;
}
function startsWith2($str, $char) {
return stripos($str, $char) === 0;
}
function startsWith3($str, $char) {
return substr($str, 0, 1) === $char;
}
function startsWith4($str, $char){
return $str[0] === $char;
}
function startsWith5($str, $char){
return (bool) preg_match('/^' . $char . '/', $str);
}
function startsWith6($str, $char) {
if (is_null($encoding)) $encoding = mb_internal_encoding();
return mb_substr($str, 0, mb_strlen($char, $encoding), $encoding) === $char;
}
Here are the results on my average DualCore machine with 100.000 runs each
// Testing '_string'
startsWith1 took 0.385906934738
startsWith2 took 0.457293987274
startsWith3 took 0.412894964218
startsWith4 took 0.366240024567 <-- fastest
startsWith5 took 0.642996072769
startsWith6 took 1.39859509468
// Tested "string"
startsWith1 took 0.384965896606
startsWith2 took 0.445554971695
startsWith3 took 0.42377281189
startsWith4 took 0.373164176941 <-- fastest
startsWith5 took 0.630424022675
startsWith6 took 1.40699005127
// Tested 1000 char random string [a-z0-9]
startsWith1 took 0.430691003799
startsWith2 took 4.447286129
startsWith3 took 0.413349866867
startsWith4 took 0.368592977524 <-- fastest
startsWith5 took 0.627470016479
startsWith6 took 1.40957403183
// Tested 1000 char random string [a-z0-9] with '_' prefix
startsWith1 took 0.384054899216
startsWith2 took 4.41522812843
startsWith3 took 0.408898115158
startsWith4 took 0.363884925842 <-- fastest
startsWith5 took 0.638479948044
startsWith6 took 1.41304707527
As you can see, treating the haystack as array to find out the char at the first position is always the fastest solution. It is also always performing at equal speed, regardless of string length. Using strpos
is faster than substr
for short strings but slower for long strings, when the string does not start with the prefix. The difference is irrelevant though. stripos
is incredibly slow with long strings. preg_match
performs mostly the same regardless of string length, but is only mediocre in speed. The mb_substr
solution performs worst, while probably being more reliable though.
Given that these numbers are for 100.000 runs, it should be obvious that we are talking about 0.0000x seconds per call. Picking one over the other for efficiency is a worthless micro-optimization, unless your app is doing startsWith
checking for a living.
"FetchType.LAZY
" will only fire for primary table. If in your code you call any other method that has a parent table dependency then it will fire query to get that table information. (FIRES MULTIPLE SELECT)
"FetchType.EAGER
" will create join of all table including relevant parent tables directly. (USES JOIN
)
When to Use:
Suppose you compulsorily need to use dependant parent table informartion then choose FetchType.EAGER
.
If you only need information for certain records then use FetchType.LAZY
.
Remember, FetchType.LAZY
needs an active db session factory at the place in your code where if you choose to retrieve parent table information.
E.g. for LAZY
:
.. Place fetched from db from your dao loayer
.. only place table information retrieved
.. some code
.. getCity() method called... Here db request will be fired to get city table info
The "string to long" (strtol
) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:
#include <stdlib.h>
long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)
Since we use the decimal system, base is 10. The endpointer
argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL
instead of passing a pointer, as shown.
If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0
is always the last character of a string in C:
#include <stdlib.h>
char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string
As the man page mentions, you can use errno
to check that no errors occurred (in this case overflows or underflows).
#include <stdlib.h>
#include <errno.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
// Everything went well, print it as 'long decimal'
printf("%ld", arg);
So now we are stuck with this long
, but we often want to work with integers. To convert a long
into an int
, we should first check that the number is within the limited capacity of an int
. To do this, we add a second if-statement, and if it matches, we can just cast it.
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number
printf("%d", arg_int);
To see what happens if you don't do this check, test the code without the INT_MIN
/MAX
if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.
#include <stdio.h> // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h> // for errno
#include <limits.h> // for INT_MIN and INT_MAX
int main(int argc, char** argv) {
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number plus a newline
printf("Your value was: %d\n", arg_int);
return 0;
}
In Bash, you can test this with:
cc code.c -o example # Compile, output to 'example'
./example $((2**31-1)) # Run it
echo "exit status: $?" # Show the return value, also called 'exit status'
Using 2**31-1
, it should print the number and 0
, because 231-1 is just in range. If you pass 2**31
instead (without -1
), it will not print the number and the exit status will be 1
.
Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc
), test whether the number is in the range that you want, etc.
For me an easier, practical and direct way to understand what is going on, is that the following enumeration:
enum colors { red, green, blue };
Will be converted essentially to this:
var colors = { red: 0, green: 1, blue: 2,
[0]: "red", [1]: "green", [2]: "blue" }
Because of this, the following will be true:
colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0
This creates a easy way to get the name of an enumerated as follows:
var color: colors = colors.red;
console.log("The color selected is " + colors[color]);
It also creates a nice way to convert a string to an enumerated value.
var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];
The two situations above are far more common situation, because usually you are far more interested in the name of a specific value and serializing values in a generic way.
Most examples are with one line of "html" that is rendered conditionally. This seems readable for me when I have multiple lines that needs to be rendered conditionally.
render: function() {
// This will be renered only if showContent prop is true
var content =
<div>
<p>something here</p>
<p>more here</p>
<p>and more here</p>
</div>;
return (
<div>
<h1>Some title</h1>
{this.props.showContent ? content : null}
</div>
);
}
First example is good because instead of null
we can conditionally render some other content like {this.props.showContent ? content : otherContent}
But if you just need to show/hide content this is even better since Booleans, Null, and Undefined Are Ignored
render: function() {
return (
<div>
<h1>Some title</h1>
// This will be renered only if showContent prop is true
{this.props.showContent &&
<div>
<p>something here</p>
<p>more here</p>
<p>and more here</p>
</div>
}
</div>
);
}
I had to copy my ssh keys to the root folder. Google Cloud Compute Engine running Ubuntu 18.04
sudo cp ~/.ssh/* /root/.ssh/
While not pure bash, the following script will convert timestamps of length 13 in a string to their equivalent date in your local timezone using perl
#!/usr/bin/env bash
IT=$(cat /dev/stdin)
re='(.*)([0-9]{13})(.*)'
while [[ $IT =~ $re ]]; do
TIMESTAMP=${BASH_REMATCH[2]}
AS_DATE=$(echo "$TIMESTAMP" | perl -pe 's/([\d]{10})([\d]{3})/localtime $1/eg;')
IT="${IT/$TIMESTAMP/$AS_DATE}"
done
echo "$IT"
{"timestamp":"1573121629939","level":"DEBUG","thread":"http-nio-15372-exec-3","logger":"org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor"}
$ cat input | timestamp_to_date.sh
{"timestamp":"Thu Nov 7 06:13:49 2019","level":"DEBUG","thread":"http-nio-15372-exec-3","logger":"org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor"}
Your classes should look like this
[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}
public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}
Here is my testcode.
string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";
XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}
If you want to read a text file you should load the file into a FileStream and deserialize this.
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open))
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}
If a <script>
has a src
then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
<script>
to load the external scripta <script>
to hold your inline code (with the call to the function in the external script)
why don't you use width: 100%
and height: 100%
.
There is no easy way to catch such exception unfortunately. What I do is either override the OnError method at the page level or the Application_Error in global.asax, then check if it was a Max Request failure and, if so, transfer to an error page.
protected override void OnError(EventArgs e) .....
private void Application_Error(object sender, EventArgs e)
{
if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))
{
this.Server.ClearError();
this.Server.Transfer("~/error/UploadTooLarge.aspx");
}
}
It's a hack but the code below works for me
const int TimedOutExceptionCode = -2147467259;
public static bool IsMaxRequestExceededException(Exception e)
{
// unhandled errors = caught at global.ascx level
// http exception = caught at page level
Exception main;
var unhandled = e as HttpUnhandledException;
if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)
{
main = unhandled.InnerException;
}
else
{
main = e;
}
var http = main as HttpException;
if (http != null && http.ErrorCode == TimedOutExceptionCode)
{
// hack: no real method of identifying if the error is max request exceeded as
// it is treated as a timeout exception
if (http.StackTrace.Contains("GetEntireRawContent"))
{
// MAX REQUEST HAS BEEN EXCEEDED
return true;
}
}
return false;
}
You can create an alias for it. I am using ZSH shell with Oh-my-Zsh and here is an handy alias:
# delete and re-init git
# usage: just type 'gdelinit' in a local repository
alias gdelinit="trash .git && git init"
I am using Trash to trash the .git
folder since using rm
is really dangerous:
trash .git
Then I am re-initializing the git repo:
git init
Iterate through it and count the elements which aren't null:
int counter = 0;
for (int i = 0; i < theArray.length; i ++)
if (theArray[i] != null)
counter ++;
This can be neatened up by using for:each loops and suchlike, but this is the jist.
Either that, or keep a counter and whenever you add an element, increment it.
Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...
CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;
CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid),
INDEX(tmpid))
SELECT * FROM tmpLivecheck;
... solved my problem.
Greetings...
Here is a simpler option that works when I encounter this.
After you create the connection, select the connection and open the Properties. In the Expressions category find Password. Re-enter the password and hit Enter. It will now be saved to the connection.
It’s just HTML with Server Side Includes.
<div id='element_123_wrapper_text'>My sample DIV</div>
The Operator ^ - Match elements that starts with given value
div[id^="element_123"] {
}
The Operator $ - Match elements that ends with given value
div[id$="wrapper_text"] {
}
The Operator * - Match elements that have an attribute containing a given value
div[id*="wrapper_text"] {
}
Clearer Steps
in terminal
cd /.git/refs/remotes/origin
do ls
, you will see some branches and HEAD
Remove the branch you think has the problem
rm branchname
If it did not work, delete all branches/HEAD
Hope it works now.
Use p{width} for your column specifiers instead of l/r/c.
\begin{tabular}{|p{1cm}|p{3cm}|}
This text will be wrapped & Some more text \\
\end{tabular}
EDIT: (based on the comments)
\begin{table}[ht]
\centering
\begin{tabular}{p{0.35\linewidth} | p{0.6\linewidth}}
Column 1 & Column2 \\ \hline
This text will be wrapped & Some more text \\
Some text here & This text maybe wrapped here if its tooooo long \\
\end{tabular}
\caption{Caption}
\label{tab:my_label}
\end{table}
we get:
This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.
No sizeToFit, preferredMaxLayoutWidth used
Below is how it will work.
Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:
Set the Label properties as below image:
Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton
Now set the priority of the trailing constraint of UILabel as 749
Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748
Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]
@IBAction func updateLabelText(sender: UIButton) {
if count > 3 {
count = 0
}
textLabel.text = items[count]
count = count + 1
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.textLabel.sizeToFit()
//self.textLabel.preferredMaxLayoutWidth = 500
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.
I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.
dangerouslySetInnerHtml
to embed the <video>
code. For example:<div dangerouslySetInnerHTML={{ __html: `
<video class="video-js" playsinline autoplay loop muted>
<source src="../video_path.mp4" type="video/mp4"/>
</video>`}}
/>
Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)
The original question is about Bootstrap 3 and that supports IE8 and 9 so Flexbox would be the best option but it's not part of my answer due the lack of support, see http://caniuse.com/#feat=flexbox and toggle the IE box. Pretty bad, eh?
1. Display-table: You can muck around with turning the row into a display:table and the col- into display:table-cell. It works buuuut the limitations of tables are there, among those limitations are the push and pull and offsets won't work. Plus, I don't know where you're using this -- at what breakpoint. You should make the image full width and wrap it inside another container to put the padding on there. Also, you need to figure out the design on mobile, this is for 768px and up. When I use this, I redeclare the sizes and sometimes I stick importants on them because tables take on the width of the content inside them so having the widths declared again helps this. You will need to play around. I also use a script but you have to change the less files to use it or it won't work responsively.
.row.table-row > [class*="col-"].custom {
background-color: lightgrey;
text-align: center;
}
@media (min-width: 768px) {
img.img-fluid {width:100%;}
.row.table-row {display:table;width:100%;margin:0 auto;}
.row.table-row > [class*="col-"] {
float:none;
float:none;
display:table-cell;
vertical-align:top;
}
.row.table-row > .col-sm-11 {
width: 91.66666666666666%;
}
.row.table-row > .col-sm-10 {
width: 83.33333333333334%;
}
.row.table-row > .col-sm-9 {
width: 75%;
}
.row.table-row > .col-sm-8 {
width: 66.66666666666666%;
}
.row.table-row > .col-sm-7 {
width: 58.333333333333336%;
}
.row.table-row > .col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666666666667%;
}
.col-sm-4 {
width: 33.33333333333333%;
}
.row.table-row > .col-sm-3 {
width: 25%;
}
.row.table-row > .col-sm-2 {
width: 16.666666666666664%;
}
.row.table-row > .col-sm-1 {
width: 8.333333333333332%;
}
}
HTML
<div class="container">
<div class="row table-row">
<div class="col-sm-4 custom">
100% height to make equal to ->
</div>
<div class="col-sm-8 image-col">
<img src="http://placehold.it/600x400/B7AF90/FFFFFF&text=image+1" class="img-fluid">
</div>
</div>
</div>
.content {
text-align: center;
padding: 10px;
background: #ccc;
}
@media (min-width:768px) {
.my-row {
position: relative;
height: 100%;
border: 1px solid red;
overflow: hidden;
}
.img-fluid {
width: 100%
}
.row.my-row > [class*="col-"] {
position: relative
}
.background {
position: absolute;
padding-top: 200%;
left: 0;
top: 0;
width: 100%;
background: #ccc;
}
.content {
position: relative;
z-index: 1;
width: 100%;
text-align: center;
padding: 10px;
}
}
HTML
<div class="container">
<div class="row my-row">
<div class="col-sm-6">
<div class="content">
This is inside a relative positioned z-index: 1 div
</div>
<div class="background"><!--empty bg-div--></div>
</div>
<div class="col-sm-6 image-col">
<img src="http://placehold.it/200x400/777777/FFFFFF&text=image+1" class="img-fluid">
</div>
</div>
</div>
There is this function scandir():
$dir = 'dir';
$files = scandir($dir, 0);
for($i = 2; $i < count($files); $i++)
print $files[$i]."<br>";
Though many have already answered the difference between Val and var. But one point to notice is that val is not exactly like final keyword.
We can change the value of val using recursion but we can never change value of final. Final is more constant than Val.
def factorial(num: Int): Int = {
if(num == 0) 1
else factorial(num - 1) * num
}
Method parameters are by default val and at every call value is being changed.
For the correct and efficient computation of the hash value of a file (in Python 3):
'b'
to the filemode) to avoid character encoding and line-ending conversion issues.readinto()
to avoid buffer churning.Example:
import hashlib
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
Try this to reload your current shell:
source ~/.profile
Besides the usages that JAiro mentioned, I like this one:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
If someone needs all connection properties, he can do:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
If you need just a host and a port, you can do:
val ( host, port, _, _ ) = getConnectionProps
<h1 style="display:inline-block;text-align: center;background : red;">The Last Will and Testament of Eric Jones</h1>
_x000D_
I used a switch statement, with the default as a 404:
var fs = require("fs");
var http = require("http");
function send404Response (response){
response.writeHead(404, {"Content-Type": "text/html"});
fs.createReadStream("./path/to/404.html").pipe(response);
}
function onRequest (request, response){
switch (request.url){
case "/page1":
//statements
break;
case "/page2":
//statements
break;
default:
//if no 'match' is found
send404Response(response);
break;
}
}
http.createServer(onRequest).listen(8080);
Entity Framework has one beautiful thing for it, like :
var users = context.Users;
This will select all rows in Table User
, then you can use your .ToList()
etc.
For newbies to Entity Framework, it is like :
PortalEntities context = new PortalEntities();
var users = context.Users;
This will select all rows in Table User
just place your fonts inside app/assets/fonts folder and set the autoload path when app start using writing the code in application.rb
config.assets.paths << Rails.root.join("app", "assets", "fonts") and
then use the following code in css.
@font-face {
font-family: 'icomoon';
src: asset-url('icomoon.eot');
src: asset-url('icomoon.eot') format('embedded-opentype'),
asset-url('icomoon.woff') format('woff'),
asset-url('icomoon.ttf') format('truetype'),
asset-url('icomoon.svg') format('svg');
font-weight: normal;
font-style: normal;
}
Give it a try.
Thanks
Even shorter
var foo = (user, pass) =>
new Promise((resolve, reject) => {
if (/* condition */) {
resolve("Fine");
} else {
reject("Error message");
}
});
foo(user, pass).then(result => {
/* process */
});
You could make two forms with 2 different actions
<form action="login.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<br />
<form action="register.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Register">
</form>
Or do this
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="login">
<input type="submit" value="Login">
</form>
<br />
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="register">
<input type="submit" value="Register">
</form>
Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.
Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure
I have also encountered this error . Just i opened the new window ie Window -> New Window in eclipse .Then , I closed my old window. This solved my problem.
DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
if (dr["Column_Name"] == DBNull.Value)
{
//Do something
}
else
{
//Do something
}
}
The source
builtin is a bashism. Write this simply as .
instead.
e.g.
. $FILE
# OR you may need to use a relative path (such as in an `npm` script):
. ./$FILE
There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
I find answer. Thanks all but right answer next:
$("#myModal").on("hidden", function () {
$('#result').html('yes,result');
});
Events here http://bootstrap-ru.com/javascript.php#modals
UPD
For Bootstrap 3.x need use hidden.bs.modal:
$("#myModal").on("hidden.bs.modal", function () {
$('#result').html('yes,result');
});
select * from tableName where columnName is null
When I ran taskkill to stop the javaw.exe process it would say it had terminated but remained running. The jqs process (java qucikstart) needs to be stopped also. Running this batch file took care of the issue.
taskkill /f /im jqs.exe
taskkill /f /im javaw.exe
taskkill /f /im java.exe
Maybe you can download zlib.h from https://dev.w3.org/Amaya/libpng/zlib/zlib.h, and put it in the directory to solve the problem.
Facing the same problem I found the quickest solution was to actually scan the rows of the cells I wished to sort, determine the last row with a non-blank element and then select and sort on that grouping.
Dim lastrow As Integer
lastrow = 0
For r = 3 To 120
If Cells(r, 2) = "" Then
Dim rng As Range
Set rng = Range(Cells(3, 2), Cells(r - 1, 2 + 6))
rng.Select
rng.Sort Key1:=Range("h3"), order1:=xlDescending, Header:=xlGuess, DataOption1:=xlSortNormal
r = 205
End If
Next r
For me this worked: (added into .ssh\config
)
Host *
HostkeyAlgorithms +ssh-dss
PubkeyAcceptedKeyTypes +ssh-dss
In my case I accidentally used SSL in the Virtualhost configuration for port 80, instead of 443.
Solution (not the best, but still working for some cases) for non-dinamic text with fixed width.Usefull for situations when there are a little space to "stretch" text to the end of the penultimate line. Make some symbols in the end of the paragraph (experiment with their length) and hide it; apply to the paragraph absolute position or just correct free space with padding/marging.
Good compabitity/crossbrowser way for center-justifying text.
Example (paragraph before):
.paragraph {_x000D_
width:455px;_x000D_
text-align:justify;_x000D_
}_x000D_
_x000D_
.center{_x000D_
display:block;_x000D_
text-align:center;_x000D_
margin-top:-17px;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna,<br><center>vel scelerisque nisl consectetur et.</center></div>
_x000D_
And after the fix:
.paragraph {_x000D_
width:455px;_x000D_
text-align:justify;_x000D_
position:relative;_x000D_
}_x000D_
.center{_x000D_
display:block;_x000D_
text-align:center;_x000D_
margin-top:-17px;_x000D_
}_x000D_
.paragraph b{_x000D_
opacity:0;_x000D_
_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
filter: alpha(opacity=0);_x000D_
-moz-opacity: 0;_x000D_
-khtml-opacity: 0;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, <b>__</b><br><div class="center">vel scelerisque nisl consectetur et.</div></div>
_x000D_
Not quite Centering but using example above you can make a left margin in select box.
<style>.UName { text-indent: 5px; }</style><br>
<select name="UserName" id="UserName" size="1">
<option class="UName" selected value="select">Select User</option>
<option class="UName" value="User1">User 1 Name</option>
<option class="UName" value="User2">User 2 Name </option>
<option class="UName" value="User3">User 3 Name</option>
</select>
I ran into a similar situation trying to convert a table with several 100k rows with a C++ program (MFC/ODBC).
Since this operation took a very long time, I figured bundling multiple inserts into one (up to 1000 due to MSSQL limitations). My guess that a lot of single insert statements would create an overhead similar to what is described here.
However, it turns out that the conversion took actually quite a bit longer:
Method 1 Method 2 Method 3
Single Insert Multi Insert Joined Inserts
Rows 1000 1000 1000
Insert 390 ms 765 ms 270 ms
per Row 0.390 ms 0.765 ms 0.27 ms
So, 1000 single calls to CDatabase::ExecuteSql each with a single INSERT statement (method 1) are roughly twice as fast as a single call to CDatabase::ExecuteSql with a multi-line INSERT statement with 1000 value tuples (method 2).
Update: So, the next thing I tried was to bundle 1000 separate INSERT statements into a single string and have the server execute that (method 3). It turns out this is even a bit faster than method 1.
Edit: I am using Microsoft SQL Server Express Edition (64-bit) v10.0.2531.0
The actual reason is that, in a new repo (git init), there is no branch (no master
, no branch at all, zero branches)
So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.
And:
matching
' (push all the branches of the same name, creating them if they don't exist), simple
' (push only the current branch, and only if it has a similarly named remote tracking branch on upstream, since git 1.7.11)In both cases, since the upstream empty repo has no branch:
That means your local first push has no idea:
So you need at least to do a:
git push origin master
But if you do only that, you:
master
branch on the upstream (now non-empty repo): good.master
' needs to be pushed to upstream (origin
) 'master
' (upstream branch): bad.That is why it is recommended, for the first push, to do a:
git push -u origin master
That will record origin/master
as a remote tracking branch, and will enable the next push to automatically push master
to origin/master
.
git checkout master
git push
And that will work too with push policies 'current
' or 'upstream
'.
In each case, after the initial git push -u origin master
, a simple git push will be enough to continue pushing master to the right upstream branch.
I eventually shut-down and restarted Microsoft SQL Server Management Studio; and that fixed it for me. But at other times, just starting a new query window was enough.
The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.
this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;
All the above methods will work fine if your content-type is "application/-www-form-urlencoded". But if your content-type is "application/json" then you will have to do the following:
$params = json_decode(file_get_contents('php://input'), true); print_r($params);
Reason : See #7 in https://www.toptal.com/php/10-most-common-mistakes-php-programmers-make
Something like:
find /path/ -type f -exec stat \{} --printf="%y\n" \; |
sort -n -r |
head -n 1
Explanation:
Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.
cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
sudo nano idlemain.py
, enter password if required.os.chdir(os.path.expanduser('~/Documents'))
this line, I added sys.path.append("/Users/admin/Downloads....")
NOTE: replace contents of the quotes with the directory where python module to be addedThe problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA
) values. Here's an example:
> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
In your example this means that in your line plot(costs,pseudor2,type="l")
, costs
is completely NA
. You have to figure out why this is, but that's the explanation of your error.
From comments:
Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.
stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x)
)
I'm a bit confused about Javascript undefined & null.
null
generally behaves similarly to other scripting languages' concepts of the out-of-band ‘null’, ‘nil’ or ‘None’ objects.
undefined
, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null
. It comes up:
When you call a function with fewer arguments than the arguments list in the function
statement lists, the unpassed arguments are set to undefined
. You can test for that with eg.:
function dosomething(arg1, arg2) {
if (arg2===undefined)
arg2= DEFAULT_VALUE_FOR_ARG2;
...
}
With this method you can't tell the difference between dosomething(1)
and dosomething(1, undefined)
; arg2
will be the same value in both. If you need to tell the difference you can look at arguments.length
, but doing optional arguments like that isn't generally very readable.
When a function has no return value;
, it returns undefined
. There's generally no need to use such a return result.
When you declare a variable by having a var a
statement in a block, but haven't yet assigned a value to it, it is undefined
. Again, you shouldn't really ever need to rely on that.
The spooky typeof
operator returns 'undefined'
when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either.
This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefined
object. (And then when you try to use that undefined
object later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)
This is often used to check for the existence of properties:
if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
...do something...
However, because you can assign undefined
like any other value:
o.prop= undefined;
that doesn't actually detect whether the property is there reliably. Better to use the in
operator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:
if ('prop' in o)
...
In summary, undefined
is a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefined
should be avoided. It should never have been part of the language; null
would have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.
what does
if (!testvar)
actually do? Does it test for undefined and null or just undefined?
Such a ‘truthiness’ test checks against false
, undefined
, null
, 0
, NaN
and empty strings. But in this case, yes, it is really undefined
it is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined)
.
once a variable is defined can I clear it back to undefined (therefore deleting the variable).
You can certainly assign undefined
to it, but that won't delete the variable. Only the delete object.property
operator really removes things.
delete
is really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable
, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null
.
can I pass undefined as a parameter?
Yes.
First go to Window -> Show View -> Error Logs in menu. It will display error logs if you have any. Then try to clean the project and build it again.
Not possible, but you should check to see if border-style
values like inset
, outset
or some other, accomplished the effect you want.. (i doubt it though..)
CSS3 has the border-image properties, but i do not know about support from browsers yet (more info at http://www.css3.info/preview/border-image/)..
You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.
If for some reason you have position absolute on the div, do this:
<div class="something"></div>
.something {
position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;
}
In your code:
while(fscanf(fp,"%s %c",item,&status) == 1)
why 1 and not 2? The scanf functions return the number of objects read.
Add this dependency:
implementation 'com.google.android.gms:play-services-auth:18.0.0'
To fetch phone number list use this:
val hintRequest = HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build()
val intent = Credentials.getClient(context).getHintPickerIntent(hintRequest)
startIntentSenderForResult(
intent.intentSender,
PHONE_NUMBER_FETCH_REQUEST_CODE,
null,
0,
0,
0,
null
)
After tap on play services dialog:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent? {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PHONE_NUMBER_FETCH_REQUEST_CODE) {
data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)?.id?.let {
useFetchedPhoneNumber(it)
}
}
}
<style type="text/css">
p {margin-bottom: -1em; margin-top: 0em;}
</style>
This completely worked for me. Paragraphs were right below each other. When I used 0em for both the margins, there was still some space left in between the lines. I went for Developer tools in my browser, tried with -1em and it worked.
It is worth adding that if you want to search for a method of a class, you can use a .
(dot) between the class and method name inside of either the search everywhere or search symbols dialog. This even works with IDEAs usual search benefits. For example, you can search for LDT.now
and LocalDateTime::now
will pop up as a result. (As long as you are searching All Files and not just Project Files).
while(rs.next())
{
if(f.exists() && !f.isDirectory())
continue; //then skip the iteration
else
{
//proceed
}
}
#change-avatar-file
is a file input
#change-avatar-file
is a img tag (the target of jcrop)
The "key" is FR.onloadend Event
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
$('#change-avatar-file').change(function(){
var currentImg;
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
$('#avatar-change-img').attr( "src", e.target.result );
currentImg = e.target.result;
};
FR.readAsDataURL( this.files[0] );
FR.onloadend = function(e){
//console.log( $('#avatar-change-img').attr( "src"));
var jcrop_api;
$('#avatar-change-img').Jcrop({
bgFade: true,
bgOpacity: .2,
setSelect: [ 60, 70, 540, 330 ]
},function(){
jcrop_api = this;
});
}
}
});
You were almost there:
You just need to append the li
to ul
and voila!
So just add
ul.appendChild(li);
to the end of your function so the end function will be like this:
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
ul.appendChild(li);
}
Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.
View.VISIBLE The view is visible.
View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"
View.GONE The view is gone, you can't see it and it doesn't take up the "spot".
So to answer your question, you're looking for:
if (myImageView.getVisibility() == View.VISIBLE) {
// Its visible
} else {
// Either gone or invisible
}
This only works on Windows, so if you are planning to use dotnet core cross-platform, you'll have to look elsewhere. See https://github.com/dotnet/corefx/blob/master/Documentation/architecture/cross-platform-cryptography.md
Note: Microsoft runtime libraries do not support line buffering, so printf("will print immediately to terminal")
:
https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setvbuf
The fetch API is not implemented in Node.
You need to use an external module for that, like node-fetch.
Install it in your Node application like this
npm i node-fetch --save
then put the line below at the top of the files where you are using the fetch API:
const fetch = require("node-fetch");
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
define a shape for your edittext and give it a padding For Example
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<padding
android:left="5dp"
android:right="5dp"
/>
<solid android:color="#F6F6F6" />
<stroke
android:width="1px"
android:color="#C3C3C3" />
<corners
android:bottomLeftRadius="1dp"
android:bottomRightRadius="1dp"
android:topLeftRadius="1dp"
android:topRightRadius="1dp" />
</shape>
The padding defined in this shape will help in give padding to drawableleft or right ---------------------- Apply this shape on EditView
<EditText
android:id="@+id/example"
android:layout_width="fill_parent"
android:layout_height="36dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/shape2"
android:drawableLeft="@drawable/icon1"
android:drawablePadding="@dimen/txtDrwblPadding"
android:ems="10"
/>
using that defined shape as background will give your EditText some style plus margin to drawableLeft.
Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.
ADDED: My latest favourite is JetBrains' dotPeek.
Great Start. Here's what I came up with:
$('img.resize').each(function(){
$(this).load(function(){
var maxWidth = $(this).width(); // Max width for the image
var maxHeight = $(this).height(); // Max height for the image
$(this).css("width", "auto").css("height", "auto"); // Remove existing CSS
$(this).removeAttr("width").removeAttr("height"); // Remove HTML attributes
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
if(width > height) {
// Check if the current width is larger than the max
if(width > maxWidth){
var ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
} else {
// Check if current height is larger than max
if(height > maxHeight){
var ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
}
});
});
This has the benefit of allowing you to specify both width and height while allowing the image to still scale proportionally.
NPS (Node Package Scripts) solved this problem for me. It lets you put your NPM scripts into a separate JavaScript file, where you can add comments galore and any other JavaScript logic you need to. https://www.npmjs.com/package/nps
Sample of the package-scripts.js
from one of my projects
module.exports = {
scripts: {
// makes sure e2e webdrivers are up to date
postinstall: 'nps webdriver-update',
// run the webpack dev server and open it in browser on port 7000
server: 'webpack-dev-server --inline --progress --port 7000 --open',
// start webpack dev server with full reload on each change
default: 'nps server',
// start webpack dev server with hot module replacement
hmr: 'nps server -- --hot',
// generates icon font via a gulp task
iconFont: 'gulp default --gulpfile src/deps/build-scripts/gulp-icon-font.js',
// No longer used
// copyFonts: 'copyfiles -f src/app/glb/font/webfonts/**/* dist/1-0-0/font'
}
}
I just did a local install npm install nps -save-dev
and put this in my package.json
scripts.
"scripts": {
"start": "nps",
"test": "nps test"
}
If you want to delete only several of the selected files: you can't. The File API Working Draft you linked to contains a note:
The
HTMLInputElement
interface [HTML5] has a readonlyFileList
attribute, […]
[emphasis mine]
Reading a bit of the HTML 5 Working Draft, I came across the Common input
element APIs. It appears you can delete the entire file list by setting the value
property of the input
object to an empty string, like:
document.getElementById('multifile').value = "";
BTW, the article Using files from web applications might also be of interest.
This way is comparatively more easy
SELECT doc_id,serial_number,status FROM date_time ORDER BY date_time DESC LIMIT 0,1;
To populate the drop-down select box in laravel we have to follow the below steps.
From controller we have to get the value like this:
public function addCustomerLoyaltyCardDetails(){
$loyalityCardMaster = DB::table('loyality_cards')->pluck('loyality_card_id', 'loyalityCardNumber');
return view('admin.AddCustomerLoyaltyCardScreen')->with('loyalityCardMaster',$loyalityCardMaster);
}
And the same we can display in view:
<select class="form-control" id="loyalityCardNumber" name="loyalityCardNumber" >
@foreach ($loyalityCardMaster as $id => $name)
<option value="{{$name}}">{{$id}}</option>
@endforeach
</select>
This key value in drop down you can use as per your requirement. Hope it may help someone.
If you are using Maven as a build tool you might want to:
Close eclipse
Delete dependency directories located in .m2/repository/ - in Linux it's located under Home directory and in Windows it should be in c:\Users<YourUsername>.m2 (replace '' with your username)
Start Eclipse and enjoy normal work :)
That helped me resolve this issue and I hope it helps you too. :)
Cheers!
P.S. I've edited my answer (as @howlger asked) where it was also suggested to delete .eclipse and .p2 folders as it can do harm (although it did NOT in my case + I had to reinstall some of plugins I'm using).
application/vnd.ms-excel
vnd class
/ vendor specificYou can use the built-in JavaScript debugger in Chrome Developer Tools under the "Scripts" tab (in later versions it's the "Sources" tab), but changes you apply to the code are expressed only at the time when execution passes through them. That means changes to the code that is not running after the page loads will not have an effect. Unlike e.g. changes to the code residing in the mouseover handlers, which you can test on the fly.
There is a video from Google I/O 2010 event introducing other capabilities of Chrome Developer Tools.
In my case after testing all this options and still having issues i tried sudo git rebase --abort
and it did the whole thing
I do believe that the correct answer has already been provided by @Alex V, yet the answer does require some modernization as it is over five years old now.
There are two main issues:
Never use object
as a parameter name. It is a reservered word. With this being said, @Alex V's provided function will not work in strict mode
.
The addEvent
function provided by @Alex V does not return the event object
if the addEventListener
method is used. Another parameter should be added to the addEvent
function to allow for this.
NOTE: The new parameter to addEvent
has been made optional so that migrating to this new function version will not break any previous calls to this function. All legacy uses will be supported.
Here is the updated addEvent
function with these changes:
/*
function: addEvent
@param: obj (Object)(Required)
- The object which you wish
to attach your event to.
@param: type (String)(Required)
- The type of event you
wish to establish.
@param: callback (Function)(Required)
- The method you wish
to be called by your
event listener.
@param: eventReturn (Boolean)(Optional)
- Whether you want the
event object returned
to your callback method.
*/
var addEvent = function(obj, type, callback, eventReturn)
{
if(obj == null || typeof obj === 'undefined')
return;
if(obj.addEventListener)
obj.addEventListener(type, callback, eventReturn ? true : false);
else if(obj.attachEvent)
obj.attachEvent("on" + type, callback);
else
obj["on" + type] = callback;
};
An example call to the new addEvent
function:
var watch = function(evt)
{
/*
Older browser versions may return evt.srcElement
Newer browser versions should return evt.currentTarget
*/
var dimensions = {
height: (evt.srcElement || evt.currentTarget).innerHeight,
width: (evt.srcElement || evt.currentTarget).innerWidth
};
};
addEvent(window, 'resize', watch, true);
Even without pop
the list we can do with set_index
pd.DataFrame(table).T.set_index(0).T
Out[11]:
0 Heading1 Heading2
1 1 2
2 3 4
Update from_records
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]:
Heading1 Heading2
0 1 2
1 3 4
Try this, you can create an extension method like this:
public static string ContentToString(this HttpContent httpContent)
{
var readAsStringAsync = httpContent.ReadAsStringAsync();
return readAsStringAsync.Result;
}
and then, simple call the extension method:
txtBlock.Text = response.Content.ContentToString();
I hope this help you ;-)
Using TempData
Represents a set of data that persists only from one request to the next
[HttpPost]
public ActionResult FillStudent(Student student1)
{
TempData["student"]= new Student();
return RedirectToAction("GetStudent","Student");
}
[HttpGet]
public ActionResult GetStudent(Student passedStd)
{
Student std=(Student)TempData["student"];
return View();
}
Alternative way Pass the data using Query string
return RedirectToAction("GetStudent","Student", new {Name="John", Class="clsz"});
This will generate a GET Request like Student/GetStudent?Name=John & Class=clsz
Ensure the method you want to redirect to is decorated with
[HttpGet]
as the above RedirectToAction will issue GET Request with http status code 302 Found (common way of performing url redirect)
You Also wanna put some text (placeholder) in the empty input box for the
.myClass {_x000D_
::-webkit-input-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
::-moz-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
/* firefox 19+ */_x000D_
:-ms-input-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
/* ie */_x000D_
input:-moz-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
}
_x000D_
<input type="text" class="myClass" id="fname" placeholder="Enter First Name Here!">
_x000D_
user to understand what to type.
Before connecting WIFI network you need to check security type of the WIFI network ScanResult class has a capabilities. This field gives you type of network
Refer: https://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities
There are three types of WIFI networks.
First, instantiate a WifiConfiguration object and fill in the network’s SSID (note that it has to be enclosed in double quotes), set the initial state to disabled, and specify the network’s priority (numbers around 40 seem to work well).
WifiConfiguration wfc = new WifiConfiguration();
wfc.SSID = "\"".concat(ssid).concat("\"");
wfc.status = WifiConfiguration.Status.DISABLED;
wfc.priority = 40;
Now for the more complicated part: we need to fill several members of WifiConfiguration to specify the network’s security mode. For open networks.
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.clear();
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
For networks using WEP; note that the WEP key is also enclosed in double quotes.
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
if (isHexString(password)) wfc.wepKeys[0] = password;
else wfc.wepKeys[0] = "\"".concat(password).concat("\"");
wfc.wepTxKeyIndex = 0;
For networks using WPA and WPA2, we can set the same values for either.
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wfc.preSharedKey = "\"".concat(password).concat("\"");
Finally, we can add the network to the WifiManager’s known list
WifiManager wfMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int networkId = wfMgr.addNetwork(wfc);
if (networkId != -1) {
// success, can call wfMgr.enableNetwork(networkId, true) to connect
}
Same issue for me. Was stumped. After I removed "Dell PC Suite" the problem went away.
Starting with the HTML fragment:
<div class='helpTop ...
use the javaScript fragment:
$(...).toggleClass('helpTop').toggleClass('helpBottom');
n = eval(input('Num books: '))
books = {}
for i in range(n):
titlez = input("Enter Title: ")
copy = eval(input("Num of copies: "))
books[titlez] = copy
prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
choice = input('Enter book title: ')
if choice in books:
init_num = books[choice]
init_num -= 1
books[choice] = init_num
print(books)
This error happens when you have a ViewBag Non-Existent in your razor code calling a method.
Controller
public ActionResult Accept(int id)
{
return View();
}
razor:
<div class="form-group">
@Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Flag(Model.from)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@
</div>
</div>
For some reason, the .net aren't able to show the error in the correct line.
Normally this causes a lot of wasted time.
There is a Win32 (C++) function in shlwapi.dll that does exactly what you want: PathRelativePathTo()
I'm not aware of any way to access this from .NET other than to P/Invoke it, though.
fatal: unable to auto-detect email address (got 'jsiddharth@TheDEN.(none)')
I ran the following,
git config --global user.email "[email protected]"
git config --global user.name "my name"
repo init -u https://<domainname>/platform/manifest
Regarding “thought leaders”: Linus emphatically advocates line wrapping for the full commit message:
[…] we use 72-character columns for word-wrapping, except for quoted material that has a specific line format.
The exceptions refers mainly to “non-prose” text, that is, text that was not typed by a human for the commit — for example, compiler error messages.
I've uploaded a Nuget Package that can make it so simple, you can have it from here ActionScheduler
It supports .NET Standard 2.0
And here how to start using it
using ActionScheduler;
var jobScheduler = new JobScheduler(TimeSpan.FromMinutes(8), new Action(() => {
//What you want to execute
}));
jobScheduler.Start(); // To Start up the Scheduler
jobScheduler.Stop(); // To Stop Scheduler from Running.
Another way to specify ANDROID_SDK_HOME without messing around with environment variables (especially when using ec2) is simply create a shortcut of eclipse and add the following as target
C:\Windows\System32\cmd.exe /C "setx ANDROID_SDK_HOME YOUR AVD PATH /M & YOUR ECLIPSE.EXE PATH"
This will set ANDROID_SDK_HOME as system variable whenever you launch eclipse.
HTH Paul
I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):
/^([a-z0-9]\s*){5,8}$/i
This allows the shortest possible postcodes like "L1 8JQ" as well as the longest ones like "OL14 5ET".
Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: "OL145ETX". But again, this is a simplistic regex, for when that's good enough.
element.style.height = null;
output:
<div style="height:100px;">
// results:
<div style="">
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}
For me, the following did the trick:
git config --global receive.denyCurrentBranch updateInstead
I set up drive F:, almost in its entirety, to sync between my Windows 10 desktop and my Windows 10 laptop, using Git. I ended up running the above command on both machines.
First I shared the desktop's F drive on the network. Then I was able to clone it on my laptop by running:
F:
git clone 'file://///DESKTOP-PC/f'
Unfortunately, all the files ended up under "F:\f" on my laptop, not under F:\ directly. But I was able to cut and paste them manually. Git still worked from the new location afterwards.
Then I tried making some changes to files on the laptop, committing them, and pushing them back to the desktop. That didn't work until I ran the git config command mentioned above.
Note that I ran all these commands from within Windows PowerShell, on both machines.
UPDATE: I still had issues pushing changes, in some cases. I finally just started pulling changes instead, by running the following on the computer I want to pull the latest commit(s) to:
git pull --all --prune
The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, numbers, or Booleans are read.For example :
var name = "foo";
var firstChar = name.charAt(0);
console.log(firstChar);
This is what happens behind the scenes:
// what the JavaScript engine does
var name = "foo";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar);
Because the second line uses a string (a primitive) like an object, the JavaScript engine creates an instance of String so that charAt(0) will work.The String object exists only for one statement before it’s destroyed check this
The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and it tells us the values aren’t instances of primitive wrapper types. You can create primitive wrapper types manually
With Mac OS X and the more recent versions of Acrobat Pro, the PDF printer option does not work. What does work is doing basically the same thing in Preview App. Open the multi page file in Preview, select File>Print. In the Print dialog set your sheet size as if you are using a printer. You may want to select "Auto Rotate", "Scale to Fit" and "Print Entire Image". Then in the lower left corner is the drop button "PDF" and in that menu select "Save as PDF". Give it a new file name, click Save and then you can open the resulting file in whatever PDF app you want and the sheet sizes are the same.
Perhaps divider
or dividerHeight
property of the ListView
can solve your problem.
The best way to do this is to set display: inline;
. Note, however, that in inline display, you lose access to some layout properties, such as manual height and vertical margins, but this doesn't appear to be a problem for your page.
pip
is designed to upgrade python packages and not to upgrade python itself. pip
shouldn't try to upgrade python when you ask it to do so.
Don't type pip install python
but use an installer instead.
I use the ManagementObjectSearcher
of namespace System.Management
Example:
string r = "";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"))
{
ManagementObjectCollection information = searcher.Get();
if (information != null)
{
foreach (ManagementObject obj in information)
{
r = obj["Caption"].ToString() + " - " + obj["OSArchitecture"].ToString();
}
}
r = r.Replace("NT 5.1.2600", "XP");
r = r.Replace("NT 5.2.3790", "Server 2003");
MessageBox.Show(r);
}
Do not forget to add the reference to the Assembly
System.Management.dll
and put the using:using System.Management;
Result:
As others have correctly pointed out, the first part of the ternary needs to return true
or false
and in your question the return value is a jQuery object.
The problem that you may have in the comparison is that the web color will be converted to RGB so you have to text for that in the ternary condition.
So with the CSS:
#blackbox {
background:pink;
width:10px;
height:10px;
}
The following jQuery will flip the colour:
var b = $('#blackbox');
b.css('background', (b.css('backgroundColor') === 'rgb(255, 192, 203)' ? 'black' : 'pink'));
It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.
However, given that within if/else statements it is best practice to do the following:
var foo = "bar";
if(foo == "bar") {
return 0;
}
else {
return 100;
}
Based on this, the argument could be made that option one is better practice.
In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.
It seems jQuery's :visible
selector does not work for some inline elements in Chrome. The solution is to add a display style, like "block"
or "inline-block"
to make it work.
Also note that jQuery has a somewhat different definition of what is visible than many developers:
Elements are considered visible if they consume space in the document.
Visible elements have a width or height that is greater than zero.
In other words, an element must have a non-zero width and height to consume space and be visible.
Elements with
visibility: hidden
oropacity: 0
are considered visible, since they still consume space in the layout.
On the other hand, even if its visibility
is set to hidden
or the opacity is zero, it's still :visible
to jQuery as it consumes space, which can be confusing when the CSS explicitly says its visibility is hidden.
Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.
All option elements are considered hidden, regardless of their selected state.
During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.
The easy way to look at it, is that if you can see the element on the screen, even if you can't see its content, it's transparent etc., it's visible, i.e. it takes up space.
I cleaned up your markup a little and added a display style (i.e. setting the elements display to "block" etc), and this works for me:
Official API reference for :visible
As of jQuery 3, the definition of :visible
has changed slightly
jQuery 3 slightly modifies the meaning of
:visible
(and therefore of:hidden
).
Starting with this version, elements will be considered:visible
if they have any layout boxes, including those of zero width and/or height. For example,br
elements and inline elements with no content will be selected by the:visible
selector.
@{
viewbag.title="index"
Layout = null;
}
A normal math answer.
Understanding that a floating point number is implemented as some bits representing the exponent and the rest, most for the digits (in the binary system), one has the following situation:
With a high exponent, say 10²³ if the least significant bit is changed, a large difference between two adjacent distinghuishable numbers appear. Furthermore the base 2 decimal point makes that many base 10 numbers can only be approximated; 1/5, 1/10 being endless numbers.
So in general: floating point numbers should not be used if you care about significant digits. For monetary amounts with calculation, e,a, best use BigDecimal.
For physics floating point doubles are adequate, floats almost never. Furthermore the floating point part of processors, the FPU, can even use a bit more precission internally.
Yes surely you can add one, as already mentioned for initialization of Abstract class variables. BUT if you dont explicitly declare one, it anyways has an implicit constructor for "Constructor Chaining" to work.
As others pointed out, 'not possible directly'. I am guessing that you want some kind of index key for Song? Just create another field (a member variable) in Element. Increment it when you add Song to the collection.
"abc"
is a literal String.
In Java, these literal strings are pooled internally and the same String instance of "abc"
is used where ever you have that string literal declared in your code. So "abc" == "abc"
will always be true as they are both the same String instance.
Using the String.intern()
method you can add any string you like to the internally pooled strings, these will be kept in memory until java exits.
On the other hand, using new String("abc")
will create a new string object in memory, which is logically the same as the "abc"
literal.
"abc" == new String("abc")
will always be false, as although they are logically equal they refer to different instances.
Wrapping a String constructor around a string literal is of no value, it just needlessly uses more memory than it needs to.
There is one fatal flaw in this otherwise great and helpful test: As memset is the first instruction, there seems to be some "memory overhead" or so which makes it extremely slow. Moving the timing of memset to second place and something else to first place or simply timing memset twice makes memset the fastest with all compile switches!!!
It is easy to check for removable devices. However, there's no guarantee that it is a USB device:
var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
This will return a list of all removable devices that are currently accessible. More information:
DriveInfo
class (msdn documentation)DriveType
enumeration (msdn documentation)This is what I do on Android with Proguard:
public enum SomeStatus {
UNINITIALIZED, STATUS_1, RESERVED_1, STATUS_2, RESERVED_2, STATUS_3;//do not change order
private static SomeStatus[] values = null;
public static SomeStatus fromInteger(int i) {
if(SomeStatus.values == null) {
SomeStatus.values = SomeStatus.values();
}
if (i < 0) return SomeStatus.values[0];
if (i >= SomeStatus.values.length) return SomeStatus.values[0];
return SomeStatus.values[i];
}
}
it's short and I don't need to worry about having an exception in Proguard
Ultimately figured out the root of the problem.
When I create the security context manually no session object is created. Only when the request finishes processing does the Spring Security mechanism realize that the session object is null (when it tries to store the security context to the session after the request has been processed).
At the end of the request Spring Security creates a new session object and session ID. However this new session ID never makes it to the browser because it occurs at the end of the request, after the response to the browser has been made. This causes the new session ID (and hence the Security context containing my manually logged on user) to be lost when the next request contains the previous session ID.
Just add 'change' listener on your input whose type is file. i.e
<input type="file" id="file_to_upload" name="file_to_upload" />
I have done using jQuery and obviously anyone can use valina JS (as per the requirement).
$("#file_to_upload").change(function() {
if (this.files.length) {
alert('file choosen');
} else {
alert('file NOT choosen');
}
});
I was trying to run it on a network drive. So I increased the client_timeout
in cqlsh and it worked.
A quick look through the documentation on regular expression sytanx should bring up ways to tell if it contains a lower/upper case character at some point.
A more hacky way is to add eg., in boot.tsx the line
import './path/declare_modules.d.ts';
with
declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';
in declare_modules.d.ts
It works but other solutions are better IMO.
This is about nine years late, but randojs.com makes this a simple one-liner:
rando(1, 6)
You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
One more way to select between dates in SQLite is to use the powerful strftime function:
SELECT * FROM test WHERE strftime('%Y-%m-%d', date) BETWEEN "11-01-2011" AND "11-08-2011"
These are equivalent according to https://sqlite.org/lang_datefunc.html:
date(...)
strftime('%Y-%m-%d', ...)
but if you want more choice, you have it.
You need to use an iframe
.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content" src="about:blank"></iframe>
</body>
</html
you can do so by using the :before
or :after
pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/
change your code to this
.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
text-decoration: none;
}
.lb-prev:before {
font-family: FontAwesome;
content: "\f053";
font-size: 30px;
}
do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
resp.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resp.write(data);
resp.end();
});
}
This is a really old question, but I came across this on a search and I think I know the source of your problem.
JSON does not allow "real" newlines in its data; it can only have escaped newlines. See the answer from @YOU. According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ("\"
) or by using "\n"
as an escape.
But keep in mind: if you are using a string in python, special escaped characters ("\t"
, "\n"
) are translated into REAL control characters! The "\n"
will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. (As for the line continuation character, it simply takes the newline out.)
So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put r
in front of the string, as in r"abc\ndef"
, or by including an extra slash in front of the newline ("abc\\ndef"
).
Both of the above will, instead of replacing "\n"
with the real newline ASCII control character, will leave "\n"
as two literal characters, which then JSON can interpret as a newline escape.
You probably want something like this overload of String.Join:
String.Join<T> Method (String, IEnumerable<T>)
Docs:
http://msdn.microsoft.com/en-us/library/dd992421.aspx
In your example, you'd use
String.Join("", Client);
Since this thread is a popular result in google search, here is the way to do it for sublime text 3 build 3059+: in user preferences, add the line:
"show_encoding": true
Technically it's undefined, but in reality most (all?) compilers treat it exactly the same as using a reinterpret_cast
from one type to the other, the result of which is implementation defined. I wouldn't lose sleep over your current code.
#include <boost/foreach.hpp>
const char* list[] = {"abc", "xyz"};
BOOST_FOREACH(const char* str, list)
{
cout << str << endl;
}
To resolve this issue you have to do two things :
You will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates.
Change few settings of Internet Explorer browser on that machine (where you desire to run automation).
1 . Setting Registry Key / Entry :
To set registry key or entry, you need to open "Registry Editor".
To open "Registry Editor" press windows button key + r alphabet key which will open "Run Window" and then type "regedit" and press enter.
Or Press Windows button key and enter "regedit" at start menu and press enter. Now depending upon your OS type whether 32/64 bit follow the corresponding steps.
Windows 32 bit : go to this location - "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl" and check for "FEATURE_BFCACHE" key.
Windows 64 bit : go to this location - HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl and check for "FEATURE_BFCACHE" key. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present.
Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0.
2 . Change Settings of Internet Explorer Browser :
Click on setting button and select "Internet options".
On "Internet options" window go to "Security" tab
Now select "Internet" option and unchecked the "Enable Protected Mode" check box and change the "Security level" to low.
Now select "Local Intranet" Option and change the "Security level" to low.
Now select "Trusted Sites" Option and change the "Security level" to low.
Here is a happy little list to put in your .jshintrc
I will add to this list at time passes.
{
// other settings...
// ENVIRONMENTS
// "browser": true, // Is in most configs by default
"node": true,
// others (e.g. yui, mootools, rhino, worker, etc.)
"globals": {
"$":false,
"jquery":false,
"angular":false
// other explicit global names to exclude
},
}
It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of .
or ..
is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments .
and ..
”, without clarifying whether they match .
and ..
before or after pct-encoding.
Personally I find Firefox's interpretation that %2E
does not mean .
most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only .
or ..
.
I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F
, %00
and %5C
sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.
I also searched this answer. Equivalent of command+N on Mac OS for Windows is ctr + alt + insert which @manyways already answered. If you searching this in settings it is in Settings > IDE Settings > Keymap, Other > New ...
Unlike jQuery
in order to read raw JSON
you will need to decode it in PHP.
print_r(json_decode(file_get_contents("php://input"), true));
php://input
is a read-only stream that allows you to read raw data from the request body.
$_POST
is form variables, you will need to switch to form
radiobutton in postman
then use:
foo=bar&foo2=bar2
To post raw json
with jquery
:
$.ajax({
"url": "/rest/index.php",
'data': JSON.stringify({foo:'bar'}),
'type': 'POST',
'contentType': 'application/json'
});
There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.
String a = "...";
String b = "...";
int compare = a.compareTo(b);
if (compare < 0) {
//a is smaller
}
else if (compare > 0) {
//a is larger
}
else {
//a is equal to b
}
The problem appears to be that the global symbol clear
is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah
), it works just fine:
Live: Version using clear
which fails | Version using blah
which works
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.
A corollary to that is to not use old-style onxyz=...
attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
// Scoping function makes the declarations within
// it *not* globals
(function(){
var header = document.getElementById("the-header");
header.onmouseover = function() {
go('The dog is in its shed');
};
header.onmouseout = clear;
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
})();
</script>
</body>
</html>
...and even better, use DOM2's addEventListener
(or attachEvent
on IE8 and earlier) so you can have multiple handlers for an event on an element.
actually, I found this in the code of a php based cms.
redirect('?module=blog', 0);
so it is possible. In this case, you are logged in at the admin level, so no harm no foul (I suppose). the first part is the url, and the second? I can't find any documentation for what the integer is for, but I guess it's either time, or data since it is attached to a form.
I, too, wanted to refresh a page after an event, and placing this in a better spot worked out well.
Looking at http.Request you can find the following member variables:
// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string
You can use RemoteAddr
to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).
This is all you have for sure.
Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:
req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter
This is because internally http.Header.Get
will normalise the key for you. (If you want to access header map directly, and not through Get
, you would need to use http.CanonicalHeaderKey first.)
Finally, "X-Forwarded-For"
is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:
// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
fmt.Println(ip)
}
will produce:
10.0.0.1
10.0.0.2
10.0.0.3
simple add and div atribute to each meta tag example
<meta id="mtlink" name="url" content="">
<meta id="mtdesc" name="description" content="" />
<meta id="mtkwrds" name="keywords" content="" />
now like normal div change for ex. n click
<a href="#" onClick="changeTags(); return false;">Change Meta Tags</a>
function change tags with jQuery
function changeTags(){
$("#mtlink").attr("content","http://albup.com");
$("#mtdesc").attr("content","music all the time");
$("#mtkwrds").attr("content","mp3, download music, ");
}