I had the same problem with my chromedriver using Python and options.add_argument("headless") did not work for me, but then I realized how to fix it so I bring it in the code below:
opt = webdriver.ChromeOptions()
opt.arguments.append("headless")
I have also face same issue on Windows 10-64 bit OS.
When I am installed firefox on my PC its installed location is "C:\Program Files\Mozilla Firefox\firefox.exe" instead of "C:\Program Files (x86)\Mozilla Firefox", because OS is 64 bit,
So I just copy & paste "Mozilla Firefox" folder in "C:\Program Files (x86)" folder and execute selenium scripts, its work for me.
They are used in the linking stage. .a
files are statically linked, and .so
files are sort-of linked, so that the library is needed whenever you run the exe.
You can find where they are stored by looking at any of the lib directories... /usr/lib
and /lib
have most of them, and there is also the LIBRARY_PATH
environment variable.
NumPy does not provide general functionality to compute derivatives. It can handles the simple special case of polynomials however:
>>> p = numpy.poly1d([1, 0, 1])
>>> print p
2
1 x + 1
>>> q = p.deriv()
>>> print q
2 x
>>> q(5)
10
If you want to compute the derivative numerically, you can get away with using central difference quotients for the vast majority of applications. For the derivative in a single point, the formula would be something like
x = 5.0
eps = numpy.sqrt(numpy.finfo(float).eps) * (1.0 + x)
print (p(x + eps) - p(x - eps)) / (2.0 * eps * x)
if you have an array x
of abscissae with a corresponding array y
of function values, you can comput approximations of derivatives with
numpy.diff(y) / numpy.diff(x)
you can add a condition to the after_update
like so:
class SomeModel < ActiveRecord::Base
after_update :send_notification, if: :published_changed?
...
end
there's no need to add a condition within the send_notification
method itself.
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
Method 1
One simple way to confirm is to use the native browser confirm alert. The template can have a button or link.
<button type=button class="btn btn-primary" (click)="clickMethod('name')">Delete me</button>
And the component method can be something like below.
clickMethod(name: string) {
if(confirm("Are you sure to delete "+name)) {
console.log("Implement delete functionality here");
}
}
Method 2
Another way to get a simple confirmation dialog is to use the angular bootstrap components like ng-bootstrap or ngx-bootstrap. You can simply install the component and use the modal component.
Method 3
Provided below is another way to implement a simple confirmation popup using angular2/material
that I implemented in my project.
app.module.ts
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';
@NgModule({
imports: [
...
FormsModule,
ReactiveFormsModule
],
declarations: [
...
ConfirmationDialog
],
providers: [ ... ],
bootstrap: [ AppComponent ],
entryComponents: [ConfirmationDialog]
})
export class AppModule { }
confirmation-dialog.ts
import { Component, Input } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';
@Component({
selector: 'confirm-dialog',
templateUrl: '/app/confirm-dialog/confirmation-dialog.html',
})
export class ConfirmationDialog {
constructor(public dialogRef: MdDialogRef<ConfirmationDialog>) {}
public confirmMessage:string;
}
confirmation-dialog.html
<h1 md-dialog-title>Confirm</h1>
<div md-dialog-content>{{confirmMessage}}</div>
<div md-dialog-actions>
<button md-button style="color: #fff;background-color: #153961;" (click)="dialogRef.close(true)">Confirm</button>
<button md-button (click)="dialogRef.close(false)">Cancel</button>
</div>
app.component.html
<button (click)="openConfirmationDialog()">Delete me</button>
app.component.ts
import { MdDialog, MdDialogRef } from '@angular/material';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';
@Component({
moduleId: module.id,
templateUrl: '/app/app.component.html',
styleUrls: ['/app/main.css']
})
export class AppComponent implements AfterViewInit {
dialogRef: MdDialogRef<ConfirmationDialog>;
constructor(public dialog: MdDialog) {}
openConfirmationDialog() {
this.dialogRef = this.dialog.open(ConfirmationDialog, {
disableClose: false
});
this.dialogRef.componentInstance.confirmMessage = "Are you sure you want to delete?"
this.dialogRef.afterClosed().subscribe(result => {
if(result) {
// do confirmation actions
}
this.dialogRef = null;
});
}
}
index.html => added following stylesheet
<link rel="stylesheet" href="node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css">
In Python 3 this can be done in 2 steps:
datetime
objectdatetime
object by 1000 to convert it to milliseconds.For example like this:
from datetime import datetime
dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output:
1482223122760.0
strptime
accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime
object. The format string (second argument) specifies the actual format of the string that you have passed.
Here is the explanation of the format specifiers from the official documentation:
%d
- Day of the month as a zero-padded decimal number.%m
- Month as a zero-padded decimal number.%Y
- Year with century as a decimal number%H
- Hour (24-hour clock) as a zero-padded decimal number.%M
- Minute as a zero-padded decimal number.%S
- Second as a zero-padded decimal number.%f
- Microsecond as a decimal number, zero-padded on the left.Instead of a batch file, you can create a shortcut on the desktop.
Set the target to:
"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch
and you're all set. Since you're not starting up a command prompt to launch it, there will be no DOS Box.
Are you using ARC? The problem here is that you don't have a reference to the UIColor
object that you're trying to apply; the CGColor
is backed by that UIColor
, but ARC will deallocate the UIColor
before you have a chance to use the CGColor
.
The clearest solution is to have a local variable pointing to your UIColor
with the objc_precise_lifetime
attribute.
You can read more about this exact case on this article about UIColor and short ARC lifetimes or get more details about the objc_precise_lifetime
attribute.
There's no reason to overthink this, all you are doing is accessing and setting a property. That's it.
Okay, so some basic dom: If you were doing this in straight JavaScript, it you would this:
window.document.getElementById('my_stuff').selectedIndex = 4;
But you're not doing it with straight JavaScript, you're doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:
$("#my_stuff").prop('selectedIndex', 4);
Anyway, just make sure your id is unique. Otherwise, you'll be banging your head on the wall wondering why this didn't work.
Or you can do this without using Delay.
set /a "counter=0"
-> your for loop here
do (
statement1
statement2
call :increaseby1
)
:increaseby1
set /a "counter+=1"
Encountered similar issue, my server is behind nginx. There's no error in web server's (Python flask) log, but some error messsage in nginx log.
[crit] 31054#31054: *269464 open() "/var/cache/nginx/proxy_temp/3/45/0000000453" failed (13: Permission denied) while reading upstream
I fixed this issue by correcting the permission of directory:
/var/cache/nginx
Mine was a bit different for php7 on centos7.
In /etc/php.ini
; extension=mysqli
to
extension=mysqli
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
You are sending a array of string
var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
So change model type accordingly
public ActionResult AddUser(List<string> model)
{
}
How about
...
C() : arr{ {1,2,3} }
{}
...
?
Compiles fine on g++ 4.8
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
I recently encountered this problem while working on a contract project(deemed classified). The system in which I had to run the code did not have internet access, for security purposes of course, and so installing dependencies, using composer and npm, was becoming huge pain.
After much deliberation with my colleague, we decided to just wing it and copy paste our dependencies rather than doing composer install or npm install.
This led us to NOT add vendors and npm_modules in gitignore. This is when I encountered this problem.
Changed but not updated:
modified: vendor/plugins/open_flash_chart_2 (modified content, untracked content)
I googled this a bit and found this helpful thread on SO. Not being too much of a pro in Git, and being a little intoxicated while working on it, I just searched for all the submodules in the vendors folder
find . -name ".git"
This gave me some 4-5 dependencies that had git on them. I removed all these .git folders and voila, it worked. I knows it's hack, and not a very geeky one anyways. O Gods of SO, please forgive me! Next time I promise to read up on gitlinks and obey O mighty Linus Tovalds.
This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)
window.onbeforeunload = function () {
return "Are you sure?";
}
$(function () {
$('input[type="checkbox"]').click(function () {
window.onbeforeunload = function () { };
});
});
You can use a window MAX() like this:
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
to get max dates per group
alongside other data:
group date cash checks max_date
----- -------- ---- ------ --------
1 1/1/2013 0 0 1/3/2013
2 1/1/2013 0 800 1/1/2013
1 1/3/2013 0 700 1/3/2013
3 1/1/2013 0 600 1/5/2013
1 1/2/2013 0 400 1/3/2013
3 1/5/2013 0 200 1/5/2013
Using the above output as a derived table, you can then get only rows where date
matches max_date
:
SELECT
group,
date,
checks
FROM (
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
) AS s
WHERE date = max_date
;
to get the desired result.
Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.
You can try the method at SQL Fiddle.
your markup was a bit messed up. Here's the styles you need and proper html
CSS:
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
HTML:
<nav class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</nav>
Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/
From the links the others have posted, I'm not seeing an option. -- I just use powershell to kill it -- you can save this to a Stop-IisExpress.ps1 file:
get-process | where { $_.ProcessName -like "IISExpress" } | stop-process
There's no harm in it -- Visual Studio will just pop a new one up when it wants one.
If you want to just shift everything down you can use:
Rows(1).Insert shift:=xlShiftDown
Similarly to shift everything over:
Columns(1).Insert shift:=xlShiftRight
In MySQL Workbench 6.1
.
I had to click on the Apply changes
button in the insertion panel (only once, because twice and MWB crashes...).
You have to do it for each of your table.
Generate INSERT statements for table
Please correct me if I'm wrong.`
public static void main(String[] args) {
Scanner na = new Scanner(System.in);
System.out.println("Please enter the number of contacts: ");
int num = na.nextInt();
String[] contactName = new String[num];
String[] contactPhone = new String[num];
String[] contactAdd1 = new String[num];
String[] contactAdd2 = new String[num];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num; i++) {
System.out.println("Enter contacts name: " + (i+1));
contactName[i] = input.nextLine();
System.out.println("Enter contacts addressline1: " + (i+1));
contactAdd1[i] = input.nextLine();
System.out.println("Enter contacts addressline2: " + (i+1));
contactAdd2[i] = input.nextLine();
System.out.println("Enter contact phone number: " + (i+1));
contactPhone[i] = input.nextLine();
}
for (int i = 0; i < num; i++) {
System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
}
}
`
Python lists
translate to JSON arrays
. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict
:
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
it looks like you need a rule very similar to your checked rule
#ck-button input:hover + span {
background-color:#191;
color:#fff;
}
and for hover and clicked state:
#ck-button input:checked:hover + span {
background-color:#c11;
color:#fff;
}
the order is important though.
I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.
I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:
def myfunc(a,b):
if (a>b): return a
else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)
Output:
[[7 4 5]
[7 6 9]]
Example fetch with authorization header:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': 'Basic '+btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: 'A=1&B=2'
});
The response itself seems to have the size of the records. You can use that to check if records exist. Something like:
if($response->size > 0){
$role_arr = getRole($response->records);
}
Based on all the info on the post, I created a little script to make the whole process easy.
@ECHO OFF
netstat -aon |find /i "listening"
SET killport=
SET /P killport=Enter port:
IF "%killport%"=="" GOTO Kill
netstat -aon |find /i "listening" | find "%killport%"
:Kill
SET killpid=
SET /P killpid=Enter PID to kill:
IF "%killpid%"=="" GOTO Error
ECHO Killing %killpid%!
taskkill /F /PID %killpid%
GOTO End
:Error
ECHO Nothing to kill! Bye bye!!
:End
pause
Whenever the Python interpreter reads a source file, it does two things:
it sets a few special variables like __name__
, and then
it executes all of the code found in the file.
Let's see how this works and how it relates to your question about the __name__
checks we always see in Python scripts.
Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py
.
# Suppose this is foo.py.
print("before import")
import math
print("before functionA")
def functionA():
print("Function A")
print("before functionB")
def functionB():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
functionA()
functionB()
print("after __name__ guard")
When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the __name__
variable.
When Your Module Is the Main Program
If you are running your module (the source file) as the main program, e.g.
python foo.py
the interpreter will assign the hard-coded string "__main__"
to the __name__
variable, i.e.
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"
When Your Module Is Imported By Another
On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:
# Suppose this is in some other main program.
import foo
The interpreter will search for your foo.py
file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo"
from the import statement to the __name__
variable, i.e.
# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.
Always
It prints the string "before import"
(without quotes).
It loads the math
module and assigns it to a variable called math
. This is equivalent to replacing import math
with the following (note that __import__
is a low-level function in Python that takes a string and triggers the actual import):
# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
It prints the string "before functionA"
.
It executes the def
block, creating a function object, then assigning that function object to a variable called functionA
.
It prints the string "before functionB"
.
It executes the second def
block, creating another function object, then assigning it to a variable called functionB
.
It prints the string "before __name__ guard"
.
Only When Your Module Is the Main Program
__name__
was indeed set to "__main__"
and it calls the two functions, printing the strings "Function A"
and "Function B 10.0"
.Only When Your Module Is Imported by Another
__name__
will be "foo"
, not "__main__"
, and it'll skip the body of the if
statement.Always
"after __name__ guard"
in both situations.Summary
In summary, here's what'd be printed in the two cases:
# What gets printed if foo is the main program
before import
before functionA
before functionB
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before functionA
before functionB
before __name__ guard
after __name__ guard
You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py
file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:
Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.
Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py
files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.
Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.
Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module.
Question: Can I have multiple __name__
checking blocks? Answer: it's strange to do so, but the language won't stop you.
Suppose the following is in foo2.py
. What happens if you say python foo2.py
on the command-line? Why?
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
def functionA():
print("a1")
from foo2 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
if __name__ == "__main__":
print("m1")
functionA()
print("m2")
print("t2")
__name__
check in foo3.py
:# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
def functionA():
print("a1")
from foo3 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
print("m1")
functionA()
print("m2")
print("t2")
# Suppose this is in foo4.py
__name__ = "__main__"
def bar():
print("bar")
print("before __name__ guard")
if __name__ == "__main__":
bar()
print("after __name__ guard")
I'm sitting at a computer with none of the relevant bits of software, but from memory that code looks wrong. You're executing the command but discarding the RecordSet
that objMyCommand.Execute
returns.
I'd do:
Set objMyRecordset = objMyCommand.Execute
...and then lose the "open recordset" part.
look at Comparing Inline and Multi-Statement Table-Valued Functions you can find good descriptions and performance benchmarks
It sounds like you want an image
button:
<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />
Alternatively, you can use CSS to make the existing submit
button use your image as its background.
In any case, you don't want a separate <img />
element on the page.
You can use "Gena" library. It closely resembles stl::vector
in pure C89.
From the README, it features:
vec[k][j]
;You can check it out here:
This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570
I guess the counter-intuitive part of the question is: if this is correct C:
if (a == 1) {
int b = 10;
}
then why is this not also correct C?
if (a == 1)
int b = 10;
I mean, a one-line conditional if
statement should be fine either with or without braces, right?
The answer lies in the grammar of the if
statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10
line is a declaration, not a statement, and the grammar for the if
statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.
And just for the sake of answering the question completely -- this has nothing to do with scope. The b
variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror
anyways ;-)
(6.7) declaration: declaration-speci?ers init-declarator-listopt ; static_assert-declaration (6.7) init-declarator-list: init-declarator init-declarator-list , init-declarator (6.7) init-declarator: declarator declarator = initializer (6.8) statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement (6.8.2) compound-statement: { block-item-listopt } (6.8.4) selection-statement: if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement
Your result is currently in string format, you need to parse it as json.
var obj = $.parseJSON(result);
alert(obj[0].category);
Additionally, if you set the dataType of the ajax call you are making to json
, you can skip the $.parseJSON()
step.
char **orderIds;
orderIds = malloc(variableNumberOfElements * sizeof(char*));
for(int i = 0; i < variableNumberOfElements; i++) {
orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
strcpy(orderIds[i], your_string[i]);
}
Another answer to the OP's exact question is to set the consumes
content type to "text/plain"
and then declare a @RequestBody String
input parameter. This will pass the text of the POST data in as the declared String
variable (postPayload
in the following example).
Of course, this presumes your POST payload is text data (as the OP stated was the case).
Example:
@RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
public ModelAndView someMethod(@RequestBody String postPayload) {
// ...
}
I know there is an accepted answer already, but I wanted to show one cool way to do it in single command with the help of magrittr package.
PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18) %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text
This code will produce a boxplot with means printed as points and values:
I split the command on multiple lines so I can comment on what each part does, but it can also be entered as a oneliner. You can learn more about this in my gist.
I suspect that this occurs after an attempt to undeploy your app. Do you ever kill off that thread that you've initialised during the init()
process ? I would do this in the corresponding destroy()
method.
PSFTP -b path/file_name.sftp user@IP_server -hostkey 1e:52:b1... -pw password
the file content is:
lcd "path_file for send"
cd path_destination
mput file_name_to_send
quit
to have the hostkey run:
psftp user@IP_SERVER
Following @Aravind's answer with more details
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
myServiceMethodSettingCookie(request, response); //Do service call passing the response
return new ModelAndView("CustomerAddView");
}
// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
final String cookieName = "my_cool_cookie";
final String cookieValue = "my cool value here !"; // you could assign it some encoded value
final Boolean useSecureCookie = false;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
response.addCookie(cookie);
}
Related docs:
http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
From Bootstrap 4
.carousel-item{
height: 200px;
}
.carousel-item img{
height: 200px;
}
if anybody wants to clear out only a particular form control one can use
formSubmit(){
this.formName.patchValue({
formControlName:''
//or if one wants to change formControl to a different value on submit
formControlName:'form value after submission'
});
}
I had the same issue because I had 2 .git
folders in the working directory.
Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git
folders, and, if so, deleting one of them.
That allowed me to upload the project successfully.
For me, the problem was I was using a package that isn't included in package.json
nor installed.
import { ToastrService } from 'ngx-toastr';
So when the compiler tried to compile this, it threw an error.
(I installed it locally, and when running a build on an external server the error was thrown)
I can imagine following advantages of having a class method defined as static one:
remaining advantages are probably marginal if present at all:
I'm assuming you're using jquery to make the AJAX call so you can do this pretty easily by putting the redirect in the success like so:
$.ajax({
url: 'ajax_location.html',
success: function(data) {
//this is the redirect
document.location.href='/newpage/';
}
});
Windows 10 Home for me:
I'm studying maven through a udemy course. First time environment variables were ok. I had on JAVA_HOME on SYSTEM VARIABLE like this:
D:\Install\Java\jdk-12.0.1;D:\Install\apache-maven-3.5.4-bin\apache-maven-3.5.4
After some days, don't know what's happened, I began to receive:
C:\Users\Franco>mvn -version
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE
After trying all above, I tried to delete jdk the entry on SYSTEM VARIABLES, and putting it on USER VARIABLES, so now I have:
JAVA_HOME on USER VARIABLES: D:\Install\Java\jdk-12.0.1
JAVA_HOME on SYSTEM VARIABLES: D:\Install\apache-maven-3.5.4-bin\apache-maven-3.5.4
now restarting CMD I have:
C:\Users\Franco>mvn -version
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T20:33:14+02:00)
Maven home: D:\Install\apache-maven-3.5.4-bin\apache-maven-3.5.4\bin\..
Java version: 12.0.1, vendor: Oracle Corporation, runtime: D:\Install\Java\jdk-12.0.1
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
Here's a comparison of four different algorithms for accomplishing this: https://jsperf.com/sorted-array-insert-comparison/1
Algorithms
Naive is always horrible. It seems for small array sizes, the other three dont differ too much, but for larger arrays, the last 2 outperform the simple linear approach.
You can also use the drop_duplicates() instead of unique()
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a
Just putting this here in case it helps someone, my case was different and a bit of an odd mix. I was getting this on a request that was accessed via superagent - the problem had nothing to do with certificates (which were setup properly) and all to do with the fact that I was then passing the superagent result through the async module's waterfall callback. To fix: Instead of passing the entire result, just pass result.body
through the waterfall's callback.
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
The problem with all these solutions is that the height of the iframe
never really changes.
This means you won't be able to center elements inside the iframe
using Javascript, position:fixed;
, or position:absolute;
since the iframe
itself never scrolls.
My solution detailed here is to wrap all the content of the iframe inside a div
using this CSS:
#wrap {
position: fixed;
top: 0;
right:0;
bottom:0;
left: 0;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
This way Safari believes the content has no height and lets you assign the height of the iframe
properly. This also allows you to position elements in any way you wish.
I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True
in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).
It is greatly frustrating that CakePHP does not have a $this->Model->lastQuery();. Here are two solutions including a modified version of Handsofaten's:
To print the last query run, in your /app_model.php file add:
function lastQuery(){
$dbo = $this->getDatasource();
$logs = $dbo->_queriesLog;
// return the first element of the last array (i.e. the last query)
return current(end($logs));
}
Then to print output you can run:
debug($this->lastQuery()); // in model
OR
debug($this->Model->lastQuery()); // in controller
To print out all queries run in a given page request, in your controller (or component, etc) run:
$this->render('sql');
It will likely throw a missing view error, but this is better than no access to recent queries!
(As Handsofaten said, there is the /elements/sql_dump.ctp in cake/libs/view/elements/, but I was able to do the above without creating the sql.ctp view. Can anyone explain that?)
What you can do is set your default database using the sp_defaultdb system stored procedure. Log in as you have done and then click the New Query button. After that simply run the sp_defaultdb command as follows:
Exec sp_defaultdb @loginame='login', @defdb='master'
My solution:
$url_string = http_build_query($your_arr);
$res = urldecode($url_string);
Use == operator instead of isEqual
Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.
String Equality
Two String values are considered equal if they contain exactly the same characters in the same order:
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.
For more read official documentation of Swift (search Comparing Strings).
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
Open a terminal and type: java -version
, or javac -version
.
If you have all the latest updates for Snow Leopard, you should be running JDK 1.6.0_20 at this moment (the same as Oracle's current JDK version).
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
And let's say that you have the following model:
public class PageModel
{
public int MyColorId { get; set; }
}
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
In your view, you can create a drop down list like so:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
i use return statement instead of throw as throw gives error in console. the best way to do it is to check the condition
if(condition){
return //whatever you want to return
}
this simply stops the execution of the program from that line, instead of giving any errors in the console.
For C++
If you are referring to ie an AbstractFactory I think that a registerCreatorFunc(..) method usually is better than requiring to add a case for each and every "new" statement that is needed. Then letting all classes create and register a creatorFunction(..) which can be easy implemented with a macro (if I dare to mention). I believe this is a common approach many framework do. I first saw it in ET++ and I think many frameworks that require a DECL and IMPL macro uses it.
My stab at this based on other answers.
function timeSince(date) {
let minute = 60;
let hour = minute * 60;
let day = hour * 24;
let month = day * 30;
let year = day * 365;
let suffix = ' ago';
let elapsed = Math.floor((Date.now() - date) / 1000);
if (elapsed < minute) {
return 'just now';
}
// get an array in the form of [number, string]
let a = elapsed < hour && [Math.floor(elapsed / minute), 'minute'] ||
elapsed < day && [Math.floor(elapsed / hour), 'hour'] ||
elapsed < month && [Math.floor(elapsed / day), 'day'] ||
elapsed < year && [Math.floor(elapsed / month), 'month'] ||
[Math.floor(elapsed / year), 'year'];
// pluralise and append suffix
return a[0] + ' ' + a[1] + (a[0] === 1 ? '' : 's') + suffix;
}
It's close! Try this:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Update:
If your result is truly is an array of one object, then you might have to do this:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
Or if you want to loop through each result in the array if there are more, try:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}
POJO : It is a java file(class) which doesn't extend or implement any other java file(class).
Bean: It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.
Normal class: It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).
First, reset any changes
This will undo any changes you've made to tracked files and restore deleted files:
git reset HEAD --hard
Second, remove new files
This will delete any new files that were added since the last commit:
git clean -fd
Files that are not tracked due to .gitignore
are preserved; they will not be removed
Warning: using -x
instead of -fd
would delete ignored files. You probably don't want to do this.
From MSDN Documentation
nvarchar [ ( n | max ) ]
Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes
You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" />
control doesn't handle that.
If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change
event then strip the filename portion and save the path somewhere--but that's about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.
This is what i have created for Material Design. May it will helpful you.
Have a look for MultipleThemeMaterialDesign
Try this one..
// Browser with version Detection
navigator.sayswho= (function(){
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
return M;
})();
var browser_version = navigator.sayswho;
alert("Welcome to " + browser_version);
check out the working fiddle ( here )
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
Use this class.
public static class Extensions
{
public static void CopyTo(this DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)
{
if (!source.Exists) return;
if (!target.Exists) target.Create();
Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) =>
CopyTo(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));
foreach (var sourceFile in source.GetFiles())
sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles);
}
public static void CopyTo(this DirectoryInfo source, string target, bool overwiteFiles = true)
{
CopyTo(source, new DirectoryInfo(target), overwiteFiles);
}
}
In my case, it was because I had accidentally set a breakpoint on a method. Once I cleared it, the message went away and performance improved a lot.
Collections.sort( new ArrayList( coll ) );
Although Pascal MARTIN is correct that PDO doesn't send the complete query to the database all at once, ryeguy's suggestion to use the DB's logging function actually allowed me to see the complete query as assembled and executed by the database.
Here's how: (These instructions are for MySQL on a Windows machine - your mileage may vary)
my.ini
, under the [mysqld]
section, add a log
command, like log="C:\Program Files\MySQL\MySQL Server 5.1\data\mysql.log"
That file will grow quickly, so be sure to delete it and turn off logging when you're done testing.
small script i wrote to replace all files with .txt extension to .cpp extension under /tmp and sub directories recursively
#!/bin/bash
for file in $(find /tmp -name '*.txt')
do
mv $file $(echo "$file" | sed -r 's|.txt|.cpp|g')
done
The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.
Derived from the code viixii.com uses I ended up using this:
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top)
$('#sticky-element').addClass('sticky');
else
$('#sticky-element').removeClass('sticky');
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.
Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.
Just place an empty div with a class acting like an anchor just above the element you want to have fixed.
Like so:
<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>
All credit for the code goes to viixii.com
I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.
My solution looks like this:
string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });
This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.
EDIT: I found this useful as well.
Use Ctrl+H for opening Eclipse search dialog, select appropriate search tab and select "Replace..." to get you to the "Search and replace" dialog
I have a stored procedure that I have put together, that deals not only with locks and blocking, but also to see what is running in a server. I have put it in master. I will share it with you, the code is below:
USE [master]
go
CREATE PROCEDURE [dbo].[sp_radhe]
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
-- the current_processes
-- marcelo miorelli
-- CCHQ
-- 04 MAR 2013 Wednesday
SELECT es.session_id AS session_id
,COALESCE(es.original_login_name, '') AS login_name
,COALESCE(es.host_name,'') AS hostname
,COALESCE(es.last_request_end_time,es.last_request_start_time) AS last_batch
,es.status
,COALESCE(er.blocking_session_id,0) AS blocked_by
,COALESCE(er.wait_type,'MISCELLANEOUS') AS waittype
,COALESCE(er.wait_time,0) AS waittime
,COALESCE(er.last_wait_type,'MISCELLANEOUS') AS lastwaittype
,COALESCE(er.wait_resource,'') AS waitresource
,coalesce(db_name(er.database_id),'No Info') as dbid
,COALESCE(er.command,'AWAITING COMMAND') AS cmd
,sql_text=st.text
,transaction_isolation =
CASE es.transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'Read Uncommitted'
WHEN 2 THEN 'Read Committed'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot'
END
,COALESCE(es.cpu_time,0)
+ COALESCE(er.cpu_time,0) AS cpu
,COALESCE(es.reads,0)
+ COALESCE(es.writes,0)
+ COALESCE(er.reads,0)
+ COALESCE(er.writes,0) AS physical_io
,COALESCE(er.open_transaction_count,-1) AS open_tran
,COALESCE(es.program_name,'') AS program_name
,es.login_time
FROM sys.dm_exec_sessions es
LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
LEFT OUTER JOIN sys.server_principals sp ON es.security_id = sp.sid
LEFT OUTER JOIN sys.dm_os_tasks ota ON es.session_id = ota.session_id
LEFT OUTER JOIN sys.dm_os_threads oth ON ota.worker_address = oth.worker_address
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS st
where es.is_user_process = 1
and es.session_id <> @@spid
and es.status = 'running'
ORDER BY es.session_id
end
GO
this procedure has done very good for me in the last couple of years. to run it just type sp_radhe
Regarding putting sp_radhe in the master database
I use the following code and make it a system stored procedure
exec sys.sp_MS_marksystemobject 'sp_radhe'
as you can see on the link below
Creating Your Own SQL Server System Stored Procedures
Regarding the transaction isolation level
Questions About T-SQL Transaction Isolation Levels You Were Too Shy to Ask
Once you change the transaction isolation level it only changes when the scope exits at the end of the procedure or a return call, or if you change it explicitly again using SET TRANSACTION ISOLATION LEVEL.
In addition the TRANSACTION ISOLATION LEVEL is only scoped to the stored procedure, so you can have multiple nested stored procedures that execute at their own specific isolation levels.
select CONVERT((column_name) USING utf8) FROM table;
In my case, Workbench does not work. so i used the above solution to show blob data as text.
Trying to cover the whole world with one regular expression is not completely possible, and certainly not feasible or recommended.
Not to toot my own horn, but I've written some pretty thorough regular expressions which you may find helpful.
Basic validation:
^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$
Extended validation:
^(A(0[ABCEGHJ-NPR]|1[ABCEGHK-NSV-Y]|2[ABHNV]|5[A]|8[A])|B(0[CEHJ-NPRSTVW]|1[ABCEGHJ-NPRSTV-Y]|2[ABCEGHJNRSTV-Z]|3[ABEGHJ-NPRSTVZ]|4[ABCEGHNPRV]|5[A]|6[L]|9[A])|C(0[AB]|1[ABCEN])|E(1[ABCEGHJNVWX]|2[AEGHJ-NPRSV]|3[ABCELNVYZ]|4[ABCEGHJ-NPRSTV-Z]|5[ABCEGHJ-NPRSTV]|6[ABCEGHJKL]|7[ABCEGHJ-NP]|8[ABCEGJ-NPRST]|9[ABCEGH])|G(0[ACEGHJ-NPRSTV-Z]|1[ABCEGHJ-NPRSTV-Y]|2[ABCEGJ-N]|3[ABCEGHJ-NZ]|4[ARSTVWXZ]|5[ABCHJLMNRTVXYZ]|6[ABCEGHJKLPRSTVWXZ]|7[ABGHJKNPSTXYZ]|8[ABCEGHJ-NPTVWYZ]|9[ABCHNPRTX])|H(0[HM]|1[ABCEGHJ-NPRSTV-Z]|2[ABCEGHJ-NPRSTV-Z]|3[ABCEGHJ-NPRSTV-Z]|4[ABCEGHJ-NPRSTV-Z]|5[AB]|7[ABCEGHJ-NPRSTV-Y]|8[NPRSTYZ]|9[ABCEGHJKPRSWX])|J(0[ABCEGHJ-NPRSTV-Z]|1[ACEGHJ-NRSTXZ]|2[ABCEGHJ-NRSTWXY]|3[ABEGHLMNPRTVXYZ]|4[BGHJ-NPRSTV-Z]|5[ABCJ-MRTV-Z]|6[AEJKNRSTVWYXZ]|7[ABCEGHJ-NPRTV-Z]|8[ABCEGHLMNPRTVXYZ]|9[ABEHJLNTVXYZ])|K(0[ABCEGHJ-M]|1[ABCEGHJ-NPRSTV-Z]|2[ABCEGHJ-MPRSTVW]|4[ABCKMPR]|6[AHJKTV]|7[ACGHK-NPRSV]|8[ABHNPRV]|9[AHJKLV])|L(0[[ABCEGHJ-NPRS]]|1[ABCEGHJ-NPRSTV-Z]|2[AEGHJMNPRSTVW]|3[BCKMPRSTVXYZ]|4[ABCEGHJ-NPRSTV-Z]|5[ABCEGHJ-NPRSTVW]|6[ABCEGHJ-MPRSTV-Z]|7[ABCEGJ-NPRST]|8[EGHJ-NPRSTVW]|9[ABCGHK-NPRSTVWYZ])|M(1[BCEGHJ-NPRSTVWX]|2[HJ-NPR]|3[ABCHJ-N]|4[ABCEGHJ-NPRSTV-Y]|5[ABCEGHJ-NPRSTVWX]|6[ABCEGHJ-NPRS]|7[AY]|8[V-Z]|9[ABCLMNPRVW])|N(0[ABCEGHJ-NPR]|1[ACEGHKLMPRST]|2[ABCEGHJ-NPRTVZ]|3[ABCEHLPRSTVWY]|4[BGKLNSTVWXZ]|5[ACHLPRV-Z]|6[ABCEGHJ-NP]|7[AGLMSTVWX]|8[AHMNPRSTV-Y]|9[ABCEGHJKVY])|P(0[ABCEGHJ-NPRSTV-Y]|1[ABCHLP]|2[ABN]|3[ABCEGLNPY]|4[NPR]|5[AEN]|6[ABC]|7[ABCEGJKL]|8[NT]|9[AN])|R(0[ABCEGHJ-M]|1[ABN]|2[CEGHJ-NPRV-Y]|3[ABCEGHJ-NPRSTV-Y]|4[AHJKL]|5[AGH]|6[MW]|7[ABCN]|8[AN]|9[A])|S(0[ACEGHJ-NP]|2[V]|3[N]|4[AHLNPRSTV-Z]|6[HJKVWX]|7[HJ-NPRSTVW]|9[AHVX])|T(0[ABCEGHJ-MPV]|1[ABCGHJ-MPRSV-Y]|2[ABCEGHJ-NPRSTV-Z]|3[ABCEGHJ-NPRZ]|4[ABCEGHJLNPRSTVX]|5[ABCEGHJ-NPRSTV-Z]|6[ABCEGHJ-NPRSTVWX]|7[AENPSVXYZ]|8[ABCEGHLNRSVWX]|9[ACEGHJKMNSVWX])|V(0[ABCEGHJ-NPRSTVWX]|1[ABCEGHJ-NPRSTV-Z]|2[ABCEGHJ-NPRSTV-Z]|3[ABCEGHJ-NRSTV-Y]|4[ABCEGK-NPRSTVWXZ]|5[ABCEGHJ-NPRSTV-Z]|6[ABCEGHJ-NPRSTV-Z]|7[ABCEGHJ-NPRSTV-Y]|8[ABCGJ-NPRSTV-Z]|9[ABCEGHJ-NPRSTV-Z])|X(0[ABCGX]|1[A])|Y(0[AB]|1[A]))[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$
^[0-9]{5}(-[0-9]{4})?$
^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$
It is not possible to guarantee accuracy without actually mailing something to an address and having the person let you know when they receive it, but we can narrow things by down by eliminating cases that we know are bad.
For me it was much more simple but it took me a while to figure it out. We basically had in our .jslib
some_array.forEach(item => {
do_stuff(item);
});
Turns out Unity (emscripten?) just doesn't like that syntax. We replaced it with a good old for-loop and it stoped complaining right away. I really hate it that it doesn't show the line it is complaining about, but anyway, fool me twice shame on me.
Use preg_replace()
and instead of [ \t\n\r]
use \s
:
$output = preg_replace('!\s+!', ' ', $input);
From Regular Expression Basic Syntax Reference:
\d, \w and \s
Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.
Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.
repeat
functionality is supportedYou can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr)
, you have to write (1fr)[4]
. That's it.
See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/
Grid gaps are supported in all browsers except IE. So you can use the @supports
at-rule to set the grid-gaps conditionally for all new browsers:
Example:
.grid {
display: grid;
}
.item {
margin-right: 1rem;
margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
.grid {
grid-gap: 1rem;
}
.item {
margin-right: 0;
margin-bottom: 0;
}
}
It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.
I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.
int size = (&arr)[1] - arr;
Check out this link for explanation
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
I'm guessing your using mod_proxy_http (or proxy balancer).
Look in your tomcat logs (localhost.log, or catalina.log) I suspect your seeing an exception in your web stack bubbling up and closing the socket that the tomcat worker is connected to.
Forward declaration should have complete template arguments list specified.
What about this solution?
div.commentList > article.comment:not(:last-child):last-of-type
{
color:red; /*or whatever...*/
}
Try this :
//i have a
List<string> g_list = new List<string>();
//i put manually the values... (for this example)
g_list.Add("aaa");
g_list.Add("bbb");
g_list.Add("ccc");
//for each string add a row in dataGridView and put the l_str value...
foreach (string l_str in g_list)
{
dataGridView1.Rows.Add(l_str);
}
Sure, here is an example (standard HTML boilerplate omitted):
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">_x000D_
<circle id="circle1" r="30" cx="34" cy="34" _x000D_
style="fill: red; stroke: blue; stroke-width: 2"/>_x000D_
</svg>_x000D_
<button onclick="circle1.style.fill='yellow';">Click to change to yellow</button>
_x000D_
EDIT: better yet, do it like that:
var filteredProjects =
projects.Where(p => filteredTags.All(tag => p.Tags.Contains(tag)));
EDIT2: Honestly, I don't know which one is better, so if performance is not critical, choose the one you think is more readable. If it is, you'll have to benchmark it somehow.
Probably Intersect
is the way to go:
void Main()
{
var projects = new List<Project>();
projects.Add(new Project { Name = "Project1", Tags = new int[] { 2, 5, 3, 1 } });
projects.Add(new Project { Name = "Project2", Tags = new int[] { 1, 4, 7 } });
projects.Add(new Project { Name = "Project3", Tags = new int[] { 1, 7, 12, 3 } });
var filteredTags = new int []{ 1, 3 };
var filteredProjects = projects.Where(p => p.Tags.Intersect(filteredTags).Count() == filteredTags.Length);
}
class Project {
public string Name;
public int[] Tags;
}
Although that seems a little ugly at first. You may first apply Distinct
to filteredTags
if you aren't sure whether they are all unique in the list, otherwise the counts comparison won't work as expected.
Create a lookup table first:
morse = [None] * (ord('z') - ord('a') + 1)
for line in moreCodeFile:
morse[ord(line[0].lower()) - ord('a')] = line[2:]
Then convert using the table:
for ch in userInput:
print morse[ord(ch.lower()) - ord('a')]
After excluding arm64 I always got ARCHS[@]: unbound variable. For me the only solution was to add x86_64 to the target build setting as mentioned here Problems after upgrading to Xcode 12:ld: building for iOS Simulator, but linking in dylib built for iOS, architecture arm64 You also might remove the exclude arm64 you added before.
Target sdk is the version you want to target, and min sdk is the minimum one.
I was getting the same error message when I tried to change the domain for iframe.src.
For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.
Worked like a charm.:)
A smart pointer is like a regular (typed) pointer, like "char*", except when the pointer itself goes out of scope then what it points to is deleted as well. You can use it like you would a regular pointer, by using "->", but not if you need an actual pointer to the data. For that, you can use "&*ptr".
It is useful for:
Objects that must be allocated with new, but that you'd like to have the same lifetime as something on that stack. If the object is assigned to a smart pointer, then they will be deleted when the program exits that function/block.
Data members of classes, so that when the object is deleted all the owned data is deleted as well, without any special code in the destructor (you will need to be sure the destructor is virtual, which is almost always a good thing to do).
You may not want to use a smart pointer when:
See also:
Well You can remove datepicker by simply remove hasDatepicker
class from input.
Code
$( "#from" ).removeClass('hasDatepicker')
As others have said, it is not possible to out of using post/redirect/get. But at the same time it is quite easy to do what you want to do server side.
In your POST page you simply validate the user input but do not act on it, instead you copy it into a SESSION array. You then redirect back to the main submission page again. Your main submission page starts by checking to see if the SESSION array that you are using exists, and if so copy it into a local array and unset it. From there you can act on it.
This way you only do all your main work once, achieving what you want to do.
I think I know what the problem is here - if you are trying to have it select an option that doesn't exist, it won't work. You need to ADD the option first. Like so:
var option=document.createElement("option");
option.text=document.getElementById('other_referee').value
document.getElementById('referee_new').add(option,null);
document.getElementById('referee_new').value = document.getElementById('other_referee').value;
Not elegant, but you get the idea.
CSS solutions not working properly on touch device
I found that any CSS solutions made the menu stay open on touch devices, they didn't collapse anymore.
So I read the article: https://www.brianshim.com/webtricks/drop-down-menus-on-ios-and-android/ (by Brian Shim)
Very useful! It states that a touch device always first checks the existence of a hover class on an element.
But: by using jQuery .show() you introduce a style attribute (display:block;) that makes the menu open up on first touch. Now the menu has opened without the bootstrap 'show' class. If a user chooses a link from the dropdown menu it works perfectly. But if a user decides to close the menu without using it he has to tap twice to close the menu: At the first tap the original bootstrap 'show' class gets attached so the menu opens up again, at the second tap the menu closes due to normal bootstrap behaviour (removal of 'show' class).
To prevent this I used the article: https://codeburst.io/the-only-way-to-detect-touch-with-javascript-7791a3346685 (by David Gilbertson)
He has some very handy ways of detecting touch or hover devices.
So, combined the two authors with a bit jQuery of my own:
$(window).one('mouseover', function(){
window.USER_CAN_HOVER = true;
if(USER_CAN_HOVER){
jQuery('#navbarNavDropdown ul li.dropdown').on("mouseover", function() {
var $parent = jQuery(this);
var $dropdown = $parent.children('ul');
$dropdown.show(200,function() {
$parent.mouseleave(function() {
var $this = jQuery(this);
$this.children('ul').fadeOut(200);
});
});
});
};
}); Check once if a device allows a hover event. If it does, introduce the possibility to hover using .show(). If the device doesn't allow a hover event, the .show() never gets introduced so you get natural bootstrap behaviour on touch device.
Be sure to remove any CSS regarding menu hover classes.
Took me three days :) so I hope it helps some of you.
you can use
<Image source={{uri: 'imagename'}} style={{width: 40, height: 40}} />
to show image.
from:
https://facebook.github.io/react-native/docs/images.html#images-from-hybrid-app-s-resources
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
In Chrome Canary now you can limit the network throughput. This can be done in the "Network" options of the "Emulation" tab of the Console in the Dev Tools.
You might need to activate the Chrome flag "Enable Developer Tools experiments" (chrome://flags/#enable-devtools-experiments) (chrome://flags) to see this new feature. You can simulate some low bandwidth (GSM, GPRS, EDGE, 3G) for mobile connections.
Step by step explanation how to make it work :
1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : "c:\PythonFiles\AppServerSvc.py"
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
# Your business logic or call to any class should be here
# this time it creates a text.txt and writes Test Service in a daily manner
f = open('C:\\test.txt', 'a')
rc = None
while rc != win32event.WAIT_OBJECT_0:
f.write('Test Service \n')
f.flush()
# block for 24*60*60 seconds and wait for a stop event
# it is used for a one-day loop
rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
f.write('shut down \n')
f.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
2 - On this step we should register our service.
Run command prompt as administrator and type as:
sc create TestService binpath= "C:\Python36\Python.exe c:\PythonFiles\AppServerSvc.py" DisplayName= "TestService" start= auto
the first argument of binpath is the path of python.exe
second argument of binpath is the path of your python file that we created already
Don't miss that you should put one space after every "=" sign.
Then if everything is ok, you should see
[SC] CreateService SUCCESS
Now your python service is installed as windows service now. You can see it in Service Manager and registry under :
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TestService
3- Ok now. You can start your service on service manager.
You can execute every python file that provides this service skeleton.
Databases are isolated in PostgreSQL; when you connect to a PostgreSQL server you connect to just one database, you can't copy data from one database to another using a SQL query.
If you come from MySQL: what MySQL calls (loosely) "databases" are "schemas" in PostgreSQL - sort of namespaces. A PostgreSQL database can have many schemas, each one with its tables and views, and you can copy from one schema to another with the schema.table
syntax.
If you really have two distinct PostgreSQL databases, the common way of transferring data from one to another would be to export your tables (with pg_dump -t
) to a file, and import them into the other database (with psql
).
If you really need to get data from a distinct PostgreSQL database, another option - mentioned in Grant Johnson's answer - is dblink, which is an additional module (in contrib/
).
Update:
Postgres introduced "foreign data wrapper" in 9.1 (which was released after the question was asked). Foreign data wrappers allow the creation of foreign tables through the Postgres FDW which makes it possible to access a remote table (on a different server and database) as if it was a local table.
If you use Spring framework in your project, then you can use StringUtils
import org.springframework.util.StringUtils;
StringUtils.getFilenameExtension("YourFileName")
I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.
File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");
sending tag <img src="c:\images\mypic.jpg">
would cause user browser to access image from his filesystem.
if you have to store images in folder located in c:\images
i would suggest to create an servlet like images.jsp, that as a parameter takes name of a file, then sets servlet response content to an image/jpg and then loads bytes of image from server location and put it to a response.
But what you use to create your application? is it pure servlet? Spring? JSF?
Here you can find some info about, how to do it.
If you don't wish to mess with IFS (perhaps for the code within the loop) this might help.
If know that your string will not have whitespace, you can substitute the ';' with a space and use the for/in construct:
#local str
for str in ${STR//;/ } ; do
echo "+ \"$str\""
done
But if you might have whitespace, then for this approach you will need to use a temp variable to hold the "rest" like this:
#local str rest
rest=$STR
while [ -n "$rest" ] ; do
str=${rest%%;*} # Everything up to the first ';'
# Trim up to the first ';' -- and handle final case, too.
[ "$rest" = "${rest/;/}" ] && rest= || rest=${rest#*;}
echo "+ \"$str\""
done
Why can't you do it? Because the language doesn't allow you to initializa a base class' members in the derived class' initializer list.
How can you get this done? Like this:
class A
{
public:
A(int a, int b) : a_(a), b_(b) {};
int a_, b_;
};
class B : public A
{
public:
B() : A(0,0)
{
}
};
If you don't give any position to parent then by default it takes static
. If you want to understand that difference refer to this example
Example 1::
#mainall
{
background-color:red;
height:150px;
overflow:scroll
}
Here parent class has no position so element is placed according to body.
Example 2::
#mainall
{
position:relative;
background-color:red;
height:150px;
overflow:scroll
}
In this example parent has relative position hence element are positioned absolute inside relative parent.
Firstly, I'd recommend breaking the module up into the useful things you need. But you can always create a class extending that for your invocation:
module UsefulThings
def a
puts "aaay"
end
def b
puts "beee"
end
end
def test
ob = Class.new.send(:include, UsefulThings).new
ob.a
end
test
Another way to work this around is to add this into your module package.json
scripts section
"preinstall": "npm install {Packages You depend on}"
what this will does is, it will install all packages needed by the module and you won't get that error.
If you use pandas, you can append your dataframes to an existing CSV file this way:
df.to_csv('log.csv', mode='a', index=False, header=False)
With mode='a' we ensure that we append, rather than overwrite, and with header=False we ensure that we append only the values of df rows, rather than header + values.
Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.
class demo
{private int hour,min,sec;
void input(int hour,int min,int sec)
{this.hour=hour;
this.min=min;
this.sec=sec;
}
demo add(demo d2)//demo because we are returning object
{ demo obj=new demo();
obj.hour=hour+d2.hour;
obj.min=min+d2.min;
obj.sec=sec+d2.sec;
return obj;//Returning object and later on it gets allocated to demo d3
}
void display()
{
System.out.println(hour+":"+min+":"+sec);
}
public static void main(String args[])
{
demo d1=new demo();
demo d2=new demo();
d1.input(2, 5, 10);
d2.input(3, 3, 3);
demo d3=d1.add(d2);//Note another object is created
d3.display();
}
}
Modified Time Addition Program
class demo
{private int hour,min,sec;
void input(int hour,int min,int sec)
{this.hour=(hour>12&&hour<24)?(hour-12):hour;
this.min=(min>60)?0:min;
this.sec=(sec>60)?0:sec;
}
demo add(demo d2)
{ demo obj=new demo();
obj.hour=hour+d2.hour;
obj.min=min+d2.min;
obj.sec=sec+d2.sec;
if(obj.sec>60)
{obj.sec-=60;
obj.min++;
}
if(obj.min>60)
{ obj.min-=60;
obj.hour++;
}
return obj;
}
void display()
{
System.out.println(hour+":"+min+":"+sec);
}
public static void main(String args[])
{
demo d1=new demo();
demo d2=new demo();
d1.input(12, 55, 55);
d2.input(12, 7, 6);
demo d3=d1.add(d2);
d3.display();
}
}
An example indicating the namespace:
String TheDocumentContent =
@"
<TheNamespace:root xmlns:TheNamespace = 'http://www.w3.org/2001/XMLSchema' >
<TheNamespace:GrandParent>
<TheNamespace:Parent>
<TheNamespace:Child theName = 'Fred' />
<TheNamespace:Child theName = 'Gabi' />
<TheNamespace:Child theName = 'George'/>
<TheNamespace:Child theName = 'Grace' />
<TheNamespace:Child theName = 'Sam' />
</TheNamespace:Parent>
</TheNamespace:GrandParent>
</TheNamespace:root>
";
XDocument TheDocument = XDocument.Parse( TheDocumentContent );
//Example 1:
var TheElements1 =
from
AnyElement
in
TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
select
AnyElement;
ResultsTxt.AppendText( TheElements1.Count().ToString() );
//Example 2:
var TheElements2 =
from
AnyElement
in
TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
where
AnyElement.Attribute( "theName" ).Value.StartsWith( "G" )
select
AnyElement;
foreach ( XElement CurrentElement in TheElements2 )
{
ResultsTxt.AppendText( "\r\n" + CurrentElement.Attribute( "theName" ).Value );
}
The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.
class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}
Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.
// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}
// .cpp file
//...
template <typename T> void Foo::some_method(T t)
{//...}
//...
template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);
You could use the submitHandler
option. Basically put the $.ajax
call inside this handler, i.e. invert it with the validation setup logic.
$('#form').validate({
... your validation rules come here,
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
});
The jQuery.validate
plugin will invoke the submit handler if the validation has passed.
Adding disply:flex
property to the label will get the job done!
The above solutions must work. However you can try this one:
OnClientClick="return SomeMethod();return false;"
and remove return statement from the method.
Bar
is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.
If you want to convert from char to int, why not think about unicode number?
SELECT UNICODE(';') -- 59
This way you can convert any char to int without any error. Cheers.
For those, who use 'copy' command in Build Events (Pre-build event command line or/and Post-build event command line) from Project -> Properties: target folder should exist
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
If you set up the code as a plain Java module in Gradle, then it's really easy to have Gradle give you a jar file with the contents. That jar file will have only your code, not the other Apache libraries it depends on. I'd recommend distributing it this way; it's a little weird to bundle dependencies inside your library, and it's more normal for users of those libraries to have to include those dependencies on their own (because otherwise there are collisions of those projects are already linking copies of the library, perhaps of different versions). What's more, you avoid potential licensing problems around redistributing other people's code if you were to publish your library.
Take the code that also needs to be compiled to a jar, and move it to a separate plain Java module in Android Studio:
Hopefully your project should be building normally now. After you do a build, a jar file for your Java library will be placed in the build/libs directory in your module's directory. If you want to build the jar file by hand, you can run its jar build file task from the Gradle window:
The only solution that really works :
Change:
<item name="android:windowIsTranslucent">true</item>
to:
<item name="android:windowIsTranslucent">false</item>
in styles.xml
But this might induce a problem with your splashscreen (white screen at startup)... In this case, add the following line to your styles.xml:
<item name="android:windowDisablePreview">true</item>
just below the windowIsTranslucent line.
Last chance if the previous tips do not work : target SDK 26 instead o 27.
you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.
You can call another fragment by writing the code below:
FragmentTransaction t = this.getFragmentManager().beginTransaction();
Fragment mFrag = new MyFragment();
t.replace(R.id.content_frame, mFrag);
t.commit();
here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.
you can also add the other fragment incase of replace.
I use macOS and used to have the same problem.
Running the following command in the terminal saved me:
conda install -c conda-forge keras tensorflow
Hope it helps.
You've got no SMTPSecure setting to define the type of authentication being used, and you're running the Host setting with the unnecessary 'ssl://' (PS -- ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here's the lines to add/change:
+ $mail->SMTPSecure = 'tls';
- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";
Remove the characters ^
(start of string) and $
(end of string) from the regular expression.
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
Both Python dict
(before Python 3.7) and JSON object are unordered collections. You could pass sort_keys
parameter, to sort the keys:
>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'
If you need a particular order; you could use collections.OrderedDict
:
>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'
Since Python 3.6, the keyword argument order is preserved and the above can be rewritten using a nicer syntax:
>>> json.dumps(OrderedDict(a=1, b=2))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict(b=2, a=1))
'{"b": 2, "a": 1}'
See PEP 468 – Preserving Keyword Argument Order.
If your input is given as JSON then to preserve the order (to get OrderedDict
), you could pass object_pair_hook
, as suggested by @Fred Yankowski:
>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)
OrderedDict([('a', 1), ('b', 2)])
>>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)
OrderedDict([('b', 2), ('a', 1)])
If you are using ASP.NET Web API then you should just pass data: JSON.stringify(things)
.
And your controller should look something like this:
public class PassThingsController : ApiController
{
public HttpResponseMessage Post(List<Thing> things)
{
// code
}
}
Starting with MongoDB v3.4 (released in 2016), the $lookup
aggregation pipeline stage can also work directly with an array. There is no need for $unwind
any more.
This was tracked in SERVER-22881.
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
The del
statement removes an element:
del d[key]
Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary:
def removekey(d, key):
r = dict(d)
del r[key]
return r
The dict()
constructor makes a shallow copy. To make a deep copy, see the copy
module.
Note that making a copy for every dict del
/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in this answer).
You have to change the ID of the button to be different from the function name JSFiddle
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
counter++;_x000D_
var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
newFields.id = '';_x000D_
newFields.style.display = 'block';_x000D_
var newField = newFields.childNodes;_x000D_
for (var i = 0; i < newField.length; i++) {_x000D_
var theName = newField[i].name_x000D_
if (theName) newField[i].name = theName + counter;_x000D_
}_x000D_
var insertHere = document.getElementById('writeroot');_x000D_
insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
<input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
<br />_x000D_
<br />_x000D_
<input name="cd" value="title" />_x000D_
<select name="rankingsel">_x000D_
<option>Rating</option>_x000D_
<option value="excellent">Excellent</option>_x000D_
<option value="good">Good</option>_x000D_
<option value="ok">OK</option>_x000D_
<option value="poor">Poor</option>_x000D_
<option value="bad">Bad</option>_x000D_
</select>_x000D_
<br />_x000D_
<br />_x000D_
<textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
<br />Radio buttons included to test them in Explorer:_x000D_
<br />_x000D_
<input type="radio" name="something" value="test1" />Test 1_x000D_
<br />_x000D_
<input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
<input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
<input type="submit" value="Send form" />_x000D_
</form>
_x000D_
In Angular 2, change detection is automatic... $scope.$watch()
and $scope.$digest()
R.I.P.
Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section "The Other Stuff").
Here's my understanding of how change detection works:
setTimeout()
inside our components rather than something like $timeout
... because setTimeout()
is monkey patched.ChangeDetectorRef
.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches()
that Angular 1 would set up for {{}}
template bindings.onPush
change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
ngOnChanges()
to be notified of changes. ngDoCheck()
(see this SO answer for more on this). Other references to learn more:
onPush
.As pointed above, BFS can only be used to find shortest path in a graph if:
There are no loops
All edges have same weight or no weight.
To find the shortest path, all you have to do is start from the source and perform a breadth first search and stop when you find your destination Node. The only additional thing you need to do is have an array previous[n] which will store the previous node for every node visited. The previous of source can be null.
To print the path, simple loop through the previous[] array from source till you reach destination and print the nodes. DFS can also be used to find the shortest path in a graph under similar conditions.
However, if the graph is more complex, containing weighted edges and loops, then we need a more sophisticated version of BFS, i.e. Dijkstra's algorithm.
Not sure as cant see it in steps you mentioned.
Please try FLUSH PRIVILEGES [Reloads the privileges from the grant tables in the mysql database]:
flush privileges;
You need to execute it after GRANT
Hope this help!
If your host is using suPHP, you can try creating a php.ini
file in the same folder as the script and adding:
allow_url_fopen = On
(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script
<?php
echo `id`;
?>
To give the same information, assuming shell_exec
is not a disabled function)
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren't there anymore. So needed a check statement.
if type(author) == type(None):
my if body
else:
my else body
Author can be any variable in this case, and None
can be any type that you are checking for.
I ended up with a scripts
like that:
"scripts": {
"//-1a": "---------------------------------------------------------------",
"//-1b": "---------------------- from node_modules ----------------------",
"//-1c": "---------------------------------------------------------------",
"ng": "ng",
"prettier": "prettier",
"tslint": "tslint",
"//-2a": "---------------------------------------------------------------",
"//-2b": "--------------------------- backend ---------------------------",
"//-2c": "---------------------------------------------------------------",
"back:start": "node backend/index.js",
"back:start:watch": "nodemon",
"back:build:prod": "tsc -p backend/tsconfig.json",
"back:serve:prod": "NODE_ENV=production node backend/dist/main.js",
"back:lint:check": "tslint -c ./backend/tslint.json './backend/src/**/*.ts'",
"back:lint:fix": "yarn run back:lint:check --fix",
"back:check": "yarn run back:lint:check && yarn run back:prettier:check",
"back:check:fix": "yarn run back:lint:fix; yarn run back:prettier:fix",
"back:prettier:base-files": "yarn run prettier './backend/**/*.ts'",
"back:prettier:fix": "yarn run back:prettier:base-files --write",
"back:prettier:check": "yarn run back:prettier:base-files -l",
"back:test": "ts-node --project backend/tsconfig.json node_modules/jasmine/bin/jasmine ./backend/**/*spec.ts",
"back:test:watch": "watch 'yarn run back:test' backend",
"back:test:coverage": "echo TODO",
"//-3a": "---------------------------------------------------------------",
"//-3b": "-------------------------- frontend ---------------------------",
"//-3c": "---------------------------------------------------------------",
"front:start": "yarn run ng serve",
"front:test": "yarn run ng test",
"front:test:ci": "yarn run front:test --single-run --progress=false",
"front:e2e": "yarn run ng e2e",
"front:e2e:ci": "yarn run ng e2e --prod --progress=false",
"front:build:prod": "yarn run ng build --prod --e=prod --no-sourcemap --build-optimizer",
"front:lint:check": "yarn run ng lint --type-check",
"front:lint:fix": "yarn run front:lint:check --fix",
"front:check": "yarn run front:lint:check && yarn run front:prettier:check",
"front:check:fix": "yarn run front:lint:fix; yarn run front:prettier:fix",
"front:prettier:base-files": "yarn run prettier \"./frontend/{e2e,src}/**/*.{scss,ts}\"",
"front:prettier:fix": "yarn run front:prettier:base-files --write",
"front:prettier:check": "yarn run front:prettier:base-files -l",
"front:postbuild": "gulp compress",
"//-4a": "---------------------------------------------------------------",
"//-4b": "--------------------------- cypress ---------------------------",
"//-4c": "---------------------------------------------------------------",
"cy:open": "cypress open",
"cy:headless": "cypress run",
"cy:prettier:base-files": "yarn run prettier \"./cypress/**/*.{js,ts}\"",
"cy:prettier:fix": "yarn run front:prettier:base-files --write",
"cy:prettier:check": "yarn run front:prettier:base-files -l",
"//-5a": "---------------------------------------------------------------",
"//-5b": "--------------------------- common ----------------------------",
"//-5c": "---------------------------------------------------------------",
"all:check": "yarn run back:check && yarn run front:check && yarn run cy:prettier:check",
"all:check:fix": "yarn run back:check:fix && yarn run front:check:fix && yarn run cy:prettier:fix",
"//-6a": "---------------------------------------------------------------",
"//-6b": "--------------------------- hooks -----------------------------",
"//-6c": "---------------------------------------------------------------",
"precommit": "lint-staged",
"prepush": "yarn run back:lint:check && yarn run front:lint:check"
},
My intent here is not to clarify one line, just to have some sort of delimiters between my scripts for backend, frontend, all, etc.
I'm not a huge fan of 1a, 1b, 1c, 2a, ... but the keys are different and I do not have any problem at all like that.
If you are using Visual Studio Community 2015 and trying to Install GLUT you should place the header file glut.h
in
C:\Program Files (x86)\Windows Kits\8.1\Include\um\gl
I understand that this error can occur because of many different reasons. In my case it was because I uninstalled WSUS service from Server Roles and the whole IIS went down. After doing a bit of research I found that uninstalling WSUS removes a few dlls which are used to do http compression. Since those dlls were missing and the IIS was still looking for them I did a reset using the following command in CMD:
appcmd set config -section:system.webServer/httpCompression /-[name='xpress']
Bingo! The problem is sorted now. Dont forget to run it as an administrator. You might also need to do "iisreset" as well. Just in case.
Hope it helps others. Cheers
This is often misunderstood so let me clear it up.
Static typing is where the type is bound to the variable. Types are checked at compile time.
Dynamic typing is where the type is bound to the value. Types are checked at run time.
So in Java for example:
String s = "abcd";
s
will "forever" be a String
. During its life it may point to different String
s (since s
is a reference in Java). It may have a null
value but it will never refer to an Integer
or a List
. That's static typing.
In PHP:
$s = "abcd"; // $s is a string
$s = 123; // $s is now an integer
$s = array(1, 2, 3); // $s is now an array
$s = new DOMDocument; // $s is an instance of the DOMDocument class
That's dynamic typing.
(Edit alert!)
Strong typing is a phrase with no widely agreed upon meaning. Most programmers who use this term to mean something other than static typing use it to imply that there is a type discipline that is enforced by the compiler. For example, CLU has a strong type system that does not allow client code to create a value of abstract type except by using the constructors provided by the type. C has a somewhat strong type system, but it can be "subverted" to a degree because a program can always cast a value of one pointer type to a value of another pointer type. So for example, in C you can take a value returned by malloc()
and cheerfully cast it to FILE*
, and the compiler won't try to stop you—or even warn you that you are doing anything dodgy.
(The original answer said something about a value "not changing type at run time". I have known many language designers and compiler writers and have not known one that talked about values changing type at run time, except possibly some very advanced research in type systems, where this is known as the "strong update problem".)
Weak typing implies that the compiler does not enforce a typing discpline, or perhaps that enforcement can easily be subverted.
The original of this answer conflated weak typing with implicit conversion (sometimes also called "implicit promotion"). For example, in Java:
String s = "abc" + 123; // "abc123";
This is code is an example of implicit promotion: 123 is implicitly converted to a string before being concatenated with "abc"
. It can be argued the Java compiler rewrites that code as:
String s = "abc" + new Integer(123).toString();
Consider a classic PHP "starts with" problem:
if (strpos('abcdef', 'abc') == false) {
// not found
}
The error here is that strpos()
returns the index of the match, being 0. 0 is coerced into boolean false
and thus the condition is actually true. The solution is to use ===
instead of ==
to avoid implicit conversion.
This example illustrates how a combination of implicit conversion and dynamic typing can lead programmers astray.
Compare that to Ruby:
val = "abc" + 123
which is a runtime error because in Ruby the object 123 is not implicitly converted just because it happens to be passed to a +
method. In Ruby the programmer must make the conversion explicit:
val = "abc" + 123.to_s
Comparing PHP and Ruby is a good illustration here. Both are dynamically typed languages but PHP has lots of implicit conversions and Ruby (perhaps surprisingly if you're unfamiliar with it) doesn't.
The point here is that the static/dynamic axis is independent of the strong/weak axis. People confuse them probably in part because strong vs weak typing is not only less clearly defined, there is no real consensus on exactly what is meant by strong and weak. For this reason strong/weak typing is far more of a shade of grey rather than black or white.
So to answer your question: another way to look at this that's mostly correct is to say that static typing is compile-time type safety and strong typing is runtime type safety.
The reason for this is that variables in a statically typed language have a type that must be declared and can be checked at compile time. A strongly-typed language has values that have a type at run time, and it's difficult for the programmer to subvert the type system without a dynamic check.
But it's important to understand that a language can be Static/Strong, Static/Weak, Dynamic/Strong or Dynamic/Weak.
As Martin indicated, there is more information in the DbEntityValidationResult
. I found it useful to get both my POCO class name and property name in each message, and wanted to avoid having to write custom ErrorMessage
attributes on all my [Required]
tags just for this.
The following tweak to Martin's code took care of these details for me:
// Retrieve the error messages as a list of strings.
List<string> errorMessages = new List<string>();
foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors)
{
string entityName = validationResult.Entry.Entity.GetType().Name;
foreach (DbValidationError error in validationResult.ValidationErrors)
{
errorMessages.Add(entityName + "." + error.PropertyName + ": " + error.ErrorMessage);
}
}
Lots of answers above! here is my take:
Sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set ws = Sheets("name")
Set wb = ThisWorkbook
With ws
.Select
End With
End Sub
your first (perhaps accidental) mistake as we have all mentioned is "Sheet"... should be "Sheets"
The with block is useful because if you set wb to anything other than the current workbook, it will ececute properly
After doing some research and development for this problem, I came across this solution which will hide warnings/Errors/Logs as per your choice.
(function () {
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
console.warn = function () { };
window['console']['warn'] = function () { };
this.addEventListener('load', function () {
console.warn('Something bad happened.');
window['console']['warn'] = function () { };
});
};
})();
Add this code before JQuery plugin (e.g /../jquery.min.js) even as this is JavaScript code that does not require JQuery. Because some warnings are in JQuery itself.
Thanks!!
For Java 7 you can simply omit the Class.forName()
statement as it is not really required.
For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}
Press "F4" on windows which will open up "Project Structure" and then click "+" icon or "Alt + Insert" to select a new project to be imported; then click OK button...
Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:
GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
and here is a more complete example.
char* charP = createStr();
Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.
If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded
set to true by doing the following...
$("a[aria-expanded='true']").css("background-color", "#42DCA3");
Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.
<?php
error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","4000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);
$filename = "images/1-". $_FILES['file']['name']=time();
$filename1 = "images/2-". $_FILES['file']['name']=time();
$filename2 = "images/3-". $_FILES['file']['name']=time();
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename2,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<title>picture demo</title>
<link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>
<style type="text/css">
.help
{
font-size:11px; color:#006600;
}
body {
color: #000000;
background-color:#999999 ;
background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}
.msgdiv{
width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>
</head><body>
<div align="center" id="err">
<?php echo $change; ?> </div>
<div id="space"></div>
<div id="container" >
<div id="con">
<table width="502" cellpadding="0" cellspacing="0" id="main">
<tbody>
<tr>
<td width="500" height="238" valign="top" id="main_right">
<div id="posts">
<img src="<?php// echo $filename; ?>" /> <img src="<?php// echo $filename1; ?>" />
<form method="post" action="" enctype="multipart/form-data" name="form1">
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><Td style="height:25px"> </Td></tr>
<tr>
<td width="150"><div align="right" class="titles">Picture
: </div></td>
<td width="350" align="left">
<div align="left">
<input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
</div></td>
</tr>
<tr><Td></Td>
<Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
</tr>
<tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr>
<tr>
<td width="200"> </td>
<td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="200" align="center"><div align="left"></div></td>
<td width="100"> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body></html>
Generally don't use any of these answers, they often won't scale (there's exceptions here and there, sure)
These approaches are incompatible with how GCD is intended to work and will end up either causing deadlocks and/or killing the battery by nonstop polling.
In other words, rearrange your code so that there is no synchronous waiting for a result, but instead deal with a result being notified of change of state (eg callbacks/delegate protocols, being available, going away, errors, etc.). (These can be refactored into blocks if you don't like callback hell.) Because this is how to expose real behavior to the rest of the app than hide it behind a false façade.
Instead, use NSNotificationCenter, define a custom delegate protocol with callbacks for your class. And if you don't like mucking with delegate callbacks all over, wrap them into a concrete proxy class that implements the custom protocol and saves the various block in properties. Probably also provide convenience constructors as well.
The initial work is slightly more but it will reduce the number of awful race-conditions and battery-murdering polling in the long-run.
(Don't ask for an example, because it's trivial and we had to invest the time to learn objective-c basics too.)
As mentioned, one way is to use
new Integer(my_int_value)
But you should not call the constructor for wrapper classes directly
So, modify the code accordingly:
mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);
Why are you making server side stuff when all you need is to redirect browser to different window.location.href?
Here is code that parses ?file= QueryString (taken from this question) and redirects user to that address in 1 second (works for me even on Android browsers):
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
(window.onload = function() {
var path = urlParams["file"];
setTimeout(function() { document.location.href = path; }, 1000);
});
</script>
If you have jQuery in your project definitely remove those window.onpopstate & window.onload handlers and do everything in $(document).ready(function () { } );
If you want to feel especially sly, you can write it as this:
(firstWord, rest) = yourLine.split(maxsplit=1)
This is supposed to bring the best from both worlds:
maxsplit
while splitting with any whitespaceI kind of fell in love with this solution and it's general unpacking capability, so I had to share it.
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection
, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection
to HttpURLConnection
, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
The exponential function is e^x
where e
is a mathematical constant called Euler's number, approximately 2.718281
. This value has a close mathematical relationship with pi
and the slope of the curve e^x
is equal to its value at every point. np.exp()
calculates e^x
for each value of x
in your input array.
As @0x499602d2 already pointed out, const
only ensures that a value cannot be changed after initialization where as constexpr
(introduced in C++11) guarantees the variable is a compile time constant.
Consider the following example(from LearnCpp.com):
cout << "Enter your age: ";
int age;
cin >> age;
const int myAge{age}; // works
constexpr int someAge{age}; // error: age can only be resolved at runtime
All I'm really interested in is the ownership and permissions information for the first level subdirectories.
I found a easy solution while playing my fish, which fits your need perfectly.
ll `ls`
or
ls -l $(ls)
Double quotes not worked for me, it worked for me \"
. If you want to place a double quotes as example you can set \"\"
.
You can build formulas, as example:
fprintf(strout, "\"=if(C3=1,\"\"\"\",B3)\"\n");
will write in csv:
=IF(C3=1,"",B3)
You can use:
for await (let resolvedPromise of arrayOfPromises) {
console.log(resolvedPromise)
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
If you wish to use Promise.all()
instead you can go for Promise.allSettled()
So you can have better control over rejected promises.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
It's Working
Call this method where you use
SntpClient client = new SntpClient();
if (client.requestTime("ntp.ubuntu.com", 30000)) {
long now = client.getNtpTime();
Date current = new Date(now);
date2 = sdf.parse(new Date(current.getTime()).toString());
// System.out.println(current.toString());
Log.e(TAG, "testing SntpClient time current.toString() "+current.toString()+" , date2 = "+date2);
}
=====================================================
import android.os.SystemClock;
import android.util.Log;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* {@hide}
*
* Simple SNTP client class for retrieving network time.
*
* Sample usage:
* <pre>SntpClient client = new SntpClient();
* if (client.requestTime("time.foo.com")) {
* long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
* }
* </pre>
*/
public class SntpClient
{
private static final String TAG = "SntpClient";
private static final int REFERENCE_TIME_OFFSET = 16;
private static final int ORIGINATE_TIME_OFFSET = 24;
private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;
private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;
// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
// system time computed from NTP server response
private long mNtpTime;
// value of SystemClock.elapsedRealtime() corresponding to mNtpTime
private long mNtpTimeReference;
// round trip time in milliseconds
private long mRoundTripTime;
/**
* Sends an SNTP request to the given host and processes the response.
*
* @param host host name of the server.
* @param timeout network timeout in milliseconds.
* @return true if the transaction was successful.
*/
public boolean requestTime(String host, int timeout) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
socket.setSoTimeout(timeout);
InetAddress address = InetAddress.getByName(host);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
// set mode = 3 (client) and version = 3
// mode is in low 3 bits of first byte
// version is in bits 3-5 of first byte
buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
// get current time and write it to the request packet
long requestTime = System.currentTimeMillis();
long requestTicks = SystemClock.elapsedRealtime();
writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
socket.send(request);
// read the response
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
long responseTicks = SystemClock.elapsedRealtime();
long responseTime = requestTime + (responseTicks - requestTicks);
// extract the results
long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
// receiveTime = originateTime + transit + skew
// responseTime = transmitTime + transit - skew
// clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
// = ((originateTime + transit + skew - originateTime) +
// (transmitTime - (transmitTime + transit - skew)))/2
// = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
// = (transit + skew - transit + skew)/2
// = (2 * skew)/2 = skew
long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
// if (false) Log.d(TAG, "round trip: " + roundTripTime + " ms");
// if (false) Log.d(TAG, "clock offset: " + clockOffset + " ms");
// save our results - use the times on this side of the network latency
// (response rather than request time)
mNtpTime = responseTime + clockOffset;
mNtpTimeReference = responseTicks;
mRoundTripTime = roundTripTime;
} catch (Exception e) {
if (false) Log.d(TAG, "request time failed: " + e);
return false;
} finally {
if (socket != null) {
socket.close();
}
}
return true;
}
/**
* Returns the time computed from the NTP transaction.
*
* @return time value computed from NTP server response.
*/
public long getNtpTime() {
return mNtpTime;
}
/**
* Returns the reference clock value (value of SystemClock.elapsedRealtime())
* corresponding to the NTP time.
*
* @return reference clock corresponding to the NTP time.
*/
public long getNtpTimeReference() {
return mNtpTimeReference;
}
/**
* Returns the round trip time of the NTP transaction
*
* @return round trip time in milliseconds.
*/
public long getRoundTripTime() {
return mRoundTripTime;
}
/**
* Reads an unsigned 32 bit big endian number from the given offset in the buffer.
*/
private long read32(byte[] buffer, int offset) {
byte b0 = buffer[offset];
byte b1 = buffer[offset+1];
byte b2 = buffer[offset+2];
byte b3 = buffer[offset+3];
// convert signed bytes to unsigned values
int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}
/**
* Reads the NTP time stamp at the given offset in the buffer and returns
* it as a system time (milliseconds since January 1, 1970).
*/
private long readTimeStamp(byte[] buffer, int offset) {
long seconds = read32(buffer, offset);
long fraction = read32(buffer, offset + 4);
return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
}
/**
* Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
* at the given offset in the buffer.
*/
private void writeTimeStamp(byte[] buffer, int offset, long time) {
long seconds = time / 1000L;
long milliseconds = time - seconds * 1000L;
seconds += OFFSET_1900_TO_1970;
// write seconds in big endian format
buffer[offset++] = (byte)(seconds >> 24);
buffer[offset++] = (byte)(seconds >> 16);
buffer[offset++] = (byte)(seconds >> 8);
buffer[offset++] = (byte)(seconds >> 0);
long fraction = milliseconds * 0x100000000L / 1000L;
// write fraction in big endian format
buffer[offset++] = (byte)(fraction >> 24);
buffer[offset++] = (byte)(fraction >> 16);
buffer[offset++] = (byte)(fraction >> 8);
// low order bits should be random data
buffer[offset++] = (byte)(Math.random() * 255.0);
}
}
I know this is an old post, but for the newbies like myself who still hit this page this might be useful. when you hover on a method you get a non clickable info-box whereas if you just write a comma in the method parenthesis the IntelliSense will offer you the beloved info-box with the clickable arrows.
The columns in the result set of a select
query with group by
clause must be:
group by
criteria , or ...So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:
I want to find the individual claim row bearing the most recent creation date within each group in my claims table
Given
create table dbo.some_claims_table
(
claim_id int not null ,
group_id int not null ,
date_created datetime not null ,
constraint some_table_PK primary key ( claim_id ) ,
constraint some_table_AK01 unique ( group_id , claim_id ) ,
constraint some_Table_AK02 unique ( group_id , date_created ) ,
)
The first thing to do is identify the most recent creation date for each group:
select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select
query:
select *
from dbo.claims_table t
join ( select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
) x on x.group_id = t.group_id
and x.date_created = t.date_created
If the table is not unique by date_created
within group_id
(AK02), you you can get duplicate rows for a given group.
If you want to have bare run
command in gdb
to execute your program with redirections and arguments, you can use set args
:
% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run
I was unable to achieve the same behaviour with --args
parameter, gdb
fiercely escapes the redirections, i.e.
% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...
This one actually redirects the input of gdb itself, not what we really want here
% gdb --args echo 1 2 <file
zsh: no such file or directory: file
Another potential "solution" is to use the window
object. It avoids the reference error problem when in a browser.
if (window.x) {
alert('x exists and is truthy');
} else {
alert('x does not exist, or exists and is falsy');
}
You can use pandas
, by transforming the list
to a pd.Series
then simply use .value_counts()
import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()
Input >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)
Jquery:
var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}
vanilla JS
function clearListCookies()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var spcook = cookies[i].split("=");
deleteCookie(spcook[0]);
}
function deleteCookie(cookiename)
{
var d = new Date();
d.setDate(d.getDate() - 1);
var expires = ";expires="+d;
var name=cookiename;
//alert(name);
var value="";
document.cookie = name + "=" + value + expires + "; path=/acc/html";
}
window.location = ""; // TO REFRESH THE PAGE
}
Use INDIRECT()
=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))
You can use "netstat" to check whether a port is available or not.
Use the netstat -anp | find "port number"
command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.
You have to put : before port number to get the actual output
Ex
netstat -anp | find ":8080"
Add brackets
divID = "question-" + (i+1);
You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.
Something like this:
Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);
This is the best way for me:
cat filename.tsv |
while read FILENAME
do
sudo find /PATH_FROM/ -name "$FILENAME" -maxdepth 4 -exec cp '{}' /PATH_TO/ \; ;
done
For a 64-bit OS, the path would be:
HKEY_LOCAL_MACHINE\SOFTWARE\wow6432Node\Microsoft\NET Framework Setup\NDP\
Non-numpy functions like math.abs()
or math.log10()
don't play nicely with numpy arrays. Just replace the line raising an error with:
m = np.log10(np.abs(x))
Apart from that the np.polyfit()
call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).
That's probably useful for someone, who uses unittest, if imported modules use request library. To suppress warnings in requests' vendored urllib3, add
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
to setUp method in your testclass, i.e:
import unittest, warnings
class MyTests(unittest.TestCase):
def setUp(self):
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
(all test methods here)
If you need to extract an element key based on index, this function can be used:
public string getCard(int random)
{
return Karta._dict.ElementAt(random).Key;
}
If you need to extract the Key where the element value is equal to the integer generated randomly, you can used the following function:
public string getCard(int random)
{
return Karta._dict.FirstOrDefault(x => x.Value == random).Key;
}
Side Note: The first element of the dictionary is The Key and the second is the Value
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
You'll want to add a Symbolic Breakpoint
. Apple provides an excellent guide on how to do this.
cmd+7
(cmd+8
in Xcode 9)Add
button in the lower leftAdd Symbolic Breakpoint...
Symbol
just type in UIViewAlertForUnsatisfiableConstraints
You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.
Here is an iterative solution using object-scan. The advantage is that you can easily do other processing in the filter function and specify the paths in a more readable format. There is a trade-off in introducing a dependency though, so it really depends on your use case.
// const objectScan = require('object-scan');
const search = (haystack, k, v) => objectScan([`list[*].${k}`], {
rtn: 'parent',
filterFn: ({ value }) => value === v
})(haystack);
const obj = { list: [ { name: 'my Name', id: 12, type: 'car owner' }, { name: 'my Name2', id: 13, type: 'car owner2' }, { name: 'my Name4', id: 14, type: 'car owner3' }, { name: 'my Name4', id: 15, type: 'car owner5' } ] };
console.log(search(obj, 'name', 'my Name'));
// => [ { name: 'my Name', id: 12, type: 'car owner' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
Example:
perfdb-# \df information_schema.*;
List of functions
Schema | Name | Result data type | Argument data types | Type
information_schema | _pg_char_max_length | integer | typid oid, typmod integer | normal
information_schema | _pg_char_octet_length | integer | typid oid, typmod integer | normal
information_schema | _pg_datetime_precision| integer | typid oid, typmod integer | normal
.....
information_schema | _pg_numeric_scale | integer | typid oid, typmod integer | normal
information_schema | _pg_truetypid | oid | pg_attribute, pg_type | normal
information_schema | _pg_truetypmod | integer | pg_attribute, pg_type | normal
(11 rows)
Compatibility Supports Says that
Under compatibility level 110, the default style for CAST and CONVERT
operations on time
and datetime2
data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.
That means by default datetime2
is CAST as varchar
to 121 format
. For ex; col1
and col2
formats (below) are same (other than the 0s at the end)
SELECT CONVERT(varchar, GETDATE(), 121) col1,
CAST(convert(datetime2,GETDATE()) as varchar) col2,
CAST(GETDATE() as varchar) col3
--Results
COL1 | COL2 | COL3
2013-02-08 09:53:56.223 | 2013-02-08 09:53:56.2230000 | Feb 8 2013 9:53AM
FYI, if you use CONVERT
instead of CAST
you can use a third parameter to specify certain formats as listed here on MSDN
Try using the following code snippet. This should solve your issue.
body, html {
overflow-x: hidden;
overflow-y: auto;
}
Typescript: following should work,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};
[INFO] BUILD SUCCESS
Anyway, it works for me:)
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
if(isset($_POST['submit']))
{
if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
{
$uname = $_POST['login_username'];
$pass = $_POST['login_password'];
$res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and password='$pass' ";
$query=mysql_query($res)or die (mysql_error());
list($result,$uname,$role) = mysql_fetch_row($query);
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
{
if($result>0)
{
header ('Location:Dashboard.php');
}
else
{
header ('Location:loginform.php');
}
}
I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
/**
* It is the parameter is to show arguments in the method or the class.
*/
boolean showArguments() default false;
}
@Aspect
@Component
public class AnnotationLoggerAspect {
@Autowired
private Logger logger;
private static final String METHOD_NAME = "METHOD NAME: {} ";
private static final String ARGUMENTS = "ARGS: {} ";
@Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
public void logAdviceExecutionBefore(JoinPoint joinPoint){
CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
if(annotationLogger!= null) {
StringBuilder annotationLoggerFormat = new StringBuilder();
List<Object> annotationLoggerArguments = new ArrayList<>();
annotationLoggerFormat.append(METHOD_NAME);
annotationLoggerArguments.add(codeSignature.getName());
if (annotationLogger.showArguments()) {
annotationLoggerFormat.append(ARGUMENTS);
List<?> argumentList = Arrays.asList(joinPoint.getArgs());
annotationLoggerArguments.add(argumentList.toString());
}
logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
}
}
private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
AnnotationLogger annotationLogger = null;
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = joinPoint.getTarget().getClass().
getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
if (method.isAnnotationPresent(AnnotationLogger.class)){
annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
}else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
}
return annotationLogger;
}catch(Exception e) {
return annotationLogger;
}
}
}