One-liner:
$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"
I like Hrishikesh's answer, to which I only have this to add...because we saw a comma-delimited string coming across when multiple proxies along the way were used, we found it necessary to add an explode and grab the final value, like this:
$IParray=array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));
return end($IParray);
the array_filter is in there to remove empty entries.
While my original answer below is still valid and might be helpful to understand the cause for DNS based URL forwarding not being available via Amazon Route 53 out of the box, I highly recommend checking out Vivek M. Chawla's utterly smart indirect solution via the meanwhile introduced Amazon S3 Support for Website Redirects and achieving a self contained server less and thus free solution within AWS only like so.
Nettica must be running a custom redirection solution for this, here is the problem:
You could create a CNAME alias like aws.example.com
for myaccount.signin.aws.amazon.com
, however, DNS provides no official support for aliasing a subdirectory like console
in this example.
https://myaccount.signin.aws.amazon.com/
(I just tried), because it would solve you problem right away and make a lot of sense in the first place; besides, it should be pretty easy to configure on their end.For that reason a few DNS providers have apparently implemented a custom solution to allow redirects to subdirectories; I venture the guess that they are basically facilitating a CNAME alias for a domain of their own and are redirecting again from there to the final destination via an immediate HTTP 3xx Redirection.
So to achieve the same result, you'd need to have a HTTP service running performing these redirects, which is not the simple solution one would hope for of course. Maybe/Hopefully someone can come up with a smarter approach still though.
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
How about set the Collision Detection of rigidbody to Continuous or Continuous Dynamic?
http://unity3d.com/support/documentation/Components/class-Rigidbody.html
Another solution is to add a delay functionality to model update. The simple directive seems to do a trick:
app.directive('delayedModel', function() {
return {
scope: {
model: '=delayedModel'
},
link: function(scope, element, attrs) {
element.val(scope.model);
scope.$watch('model', function(newVal, oldVal) {
if (newVal !== oldVal) {
element.val(scope.model);
}
});
var timeout;
element.on('keyup paste search', function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
scope.model = element[0].value;
element.val(scope.model);
scope.$apply();
}, attrs.delay || 500);
});
}
};
});
Usage:
<input delayed-model="searchText" data-delay="500" id="searchText" type="search" placeholder="live search..." />
So you just use delayed-model
in place of ng-model
and define desired data-delay
.
Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.
In PHP use shell_exec function:
Execute command via shell and return the complete output as a string.
It returns the output from the executed command or NULL if an error occurred or the command produces no output.
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
In Python file test.py
, verify this text in first line: (see shebang explain):
#!/usr/bin/env python
Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be "executable". Also all commands into .py
file must have correct privileges:
Taken from php manual:
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
To make executable a file on unix-type platforms:
chmod +x myscript.py
If you want to replace any node value you can do like this
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
xml.replace("old value", "new value");
Try gcc -c -I/home/me/development/skia sample.c
.
Manager humour...
http://img261.imageshack.us/img261/7469/1517stripsundayiu1.gif
Laravel ^5.7 includes new middleware to handle and redirect unauthenticated users.
It works well with "web" guard... of course the "login" route (or whatever you name your login route) should be defined in web.php.
the problem is when your are using custom guard. Different guard would redirect unauthenticated users to different route.
here's a quick workaround based on John's response (it works for me).
app/Http/Middleware/Authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* @var array
*/
protected $guards = [];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$this->guards = $guards;
return parent::handle($request, $next, ...$guards);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
if (in_array('admin', $this->guards)) {
return route('admin.login');
}
return route('login');
}
}
}
Source : Issue #26292
If the number of elements in the array is not given, you can alternatively make use of list comprehension like:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.
To create a new branch with a copy of your current state
git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server
Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.
If you don't want any dependency on Spring's HATEOAS or javax.*
namespace, use ServletUriComponentsBuilder
to get URI of current request:
import org.springframework.web.util.UriComponentsBuilder;
ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();
You can get at the data values like this:
string json = @"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
Fiddle: https://dotnetfiddle.net/uox4Vt
Sounds like you need moment.js
e.g.
moment().subtract('days', 6).calendar();
=> last Sunday at 8:23 PM
moment().startOf('hour').fromNow();
=> 26 minutes ago
Edit:
Pure JS date diff calculation:
var date1 = new Date("7/Nov/2012 20:30:00");_x000D_
var date2 = new Date("20/Nov/2012 19:15:00");_x000D_
_x000D_
var diff = date2.getTime() - date1.getTime();_x000D_
_x000D_
var days = Math.floor(diff / (1000 * 60 * 60 * 24));_x000D_
diff -= days * (1000 * 60 * 60 * 24);_x000D_
_x000D_
var hours = Math.floor(diff / (1000 * 60 * 60));_x000D_
diff -= hours * (1000 * 60 * 60);_x000D_
_x000D_
var mins = Math.floor(diff / (1000 * 60));_x000D_
diff -= mins * (1000 * 60);_x000D_
_x000D_
var seconds = Math.floor(diff / (1000));_x000D_
diff -= seconds * (1000);_x000D_
_x000D_
document.write(days + " days, " + hours + " hours, " + mins + " minutes, " + seconds + " seconds");
_x000D_
set -x
is fine, but if you do something like:
set -x;
command;
set +x;
it would result in printing
+ command
+ set +x;
You can use a subshell to prevent that such as:
(set -x; command)
which would just print the command.
Swift 4, Swift 3
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MySegueId" {
if let nextViewController = segue.destination as? NextViewController {
nextViewController.valueOfxyz = "XYZ" //Or pass any values
nextViewController.valueOf123 = 123
}
}
}
To center the table in the middle of the email use
<table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
Your Content
</td>
</tr>
</table>
To align the content in the middle use:
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center">
Your Content
</td>
</tr>
</table>
Running scripts can be terminated from the Task Manager.
However, scripts that perpetually focus program windows using .AppActivate may make it very difficult to get to the task manager -i.e you and the script will be fighting for control. Hence i recommend writing a script (which i call self destruct for obvious reasons) and make a keyboard shortcut key to activate the script.
Self destruct script:
Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True
WshShell.Run "taskkill /f /im wscript.exe", , True
Keyboard shortcut: rightclick on the script icon, select create shortcut, rightclick on script shortcut icon, select properties, click in shortcutkey and make your own.
type your shortcut key and all scripts end. Cheers
Add Regular to syntax and use gfn
:
set gfn= Monospace\ Regular:h13
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.
These are the possible errors and their solutions:
There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.
You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)
If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.
// Code snippet
$column_names = array();
$stmt->bindParam(':'.$i, $column_names[$i], $param_type);
$stmt->bindValue(':'.$i, $values[$i], $param_type);
$i++;
//.....
When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.
Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.
download java-json.jar from Java2s then use the JSONArray constructor
List myList = new ArrayList<>();
JSONArray jsonArray = new JSONArray(myList);
System.out.println(jsonArray);
ok guys you are not going to believe me how easy it is, so i putted a video on YouTube to show you that [ click here ]
now , steps :
DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">
those 2 lines || C:/xampp/htdocs == current location for root || change C:/xampp/htdocs with any location you want
If you are using IntelliJ IDEA, and deploy application on Tomcat Server, it says: Under File menu -> select project Structure -> click artifact -> select your jars and right click -> put in WEB\lib -> restart server
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
You can replace nan
with None
in your numpy array:
>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>
I use inline css all the time BECAUSE.... I want absolute control of the design and place different things aligned differently from cell to cell.
It is not hard to understand...
Anyway, I just put something like this inside my tag:
style='padding:5px 10px 5px 5px'
Where the order represents top, right, bottom and left.
val() is more like a shortcut for attr('value'). For your usage use text() or html() instead
Localhost is the computer you're using right now. You run things by typing commands at the command prompt and pressing Enter. If you're asking how to run things from your programming environment, then the answer depends on which environment you're using. Most languages have commands with names like system
or exec
for running external programs. You need to be more specific about what you're actually looking to do, and what obstacles you've encountered while trying to achieve it.
Go offline
USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO
Go online
USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO
If any of you looking for Bootstrap-4. Here it is
<div class="row no-gutters">
<div class="col-10">
<img class="img-fluid" src="/resources/img1.jpg" alt="">
</div>
</div>
All string functions as lower
, upper
, strip
are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable
, it will fail.
x = 'hello'
x[0] = 'i' #'str' object does not support item assignment
There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them
I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.
On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.
I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.
print("code sample");
select top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18 union
select 19 union
select 20 union
select 21
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");
I built my answer thanks to previous contributors.
Not having time for a custom counter.exe, I downloaded sed for FREEDOS.
And then the batch code could be, emulating "wc -l" with the utility sed, something like this according to your loop (I just use it to increment through executions starting from "1" to n+1):
Just remember to manually create a file "test.txt" with written on the first row
0
sed -n '$=' test.txt > counter.txt
set /P Var=< counter.txt
echo 0 >> test.txt
SELECT e.*,
cnt.colCount
FROM eventsTable e
INNER JOIN (
select columnName,count(columnName) as colCount
from eventsTable e2
group by columnName
) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'
-- Added space
A server socket listens on a single port. All established client connections on that server are associated with that same listening port on the server side of the connection. An established connection is uniquely identified by the combination of client-side and server-side IP/Port pairs. Multiple connections on the same server can share the same server-side IP/Port pair as long as they are associated with different client-side IP/Port pairs, and the server would be able to handle as many clients as available system resources allow it to.
On the client-side, it is common practice for new outbound connections to use a random client-side port, in which case it is possible to run out of available ports if you make a lot of connections in a short amount of time.
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.
If you have an app built for iPhone 4S or earlier, it'll run letterboxed on iPhone 5.
To adapt your app to the new taller screen, the first thing you do is to change the launch image to: [email protected]. Its size should be 1136x640 (HxW). Yep, having the default image in the new screen size is the key to let your app take the whole of new iPhone 5's screen.
(Note that the naming convention works only for the default image. Naming another image "[email protected]" will not cause it to be loaded in place of "[email protected]". If you need to load different images for different screen sizes, you'll have to do it programmatically.)
If you're very very lucky, that might be it... but in all likelihood, you'll have to take a few more steps.
In the extreme case (when none of the above suffices), design the two Xibs and load the appropriate one in the view controller.
To detect screen size:
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
CGSize result = [[UIScreen mainScreen] bounds].size;
if(result.height == 480)
{
// iPhone Classic
}
if(result.height == 568)
{
// iPhone 5
}
}
span
element is display:inline;
by default you need to make it inline-block
or block
Change your CSS to be like this
span.first_title {
margin-top: 20px;
margin-left: 12px;
font-weight: bold;
font-size:24px;
color: #221461;
/*The change*/
display:inline-block; /*or display:block;*/
}
Okay ... so these posts are old as compared to now, but insertion order is needed depending on your need or application requirements, so just use the right type of collection. For most part, it is not needed, but in a situation where you need to utilize objects in the order they were stored, I see a definite need. I think order matters when you are creating for instance a wizard or a flow engine or something of that nature where you need to go from state to state or something. In that sense you can read off stuff from the list without having it keep track of what you need next or traverse a list to find what you want. It does help with performance in that sense. It does matter or else these collections would not make much sense.
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
Drop in the image in /res/drawable folder. Then in Eclipse Menu, do ->Project -> Clean. This will do a clean build if set to build automatically.
You can set the default value of your Id in your db to newsequentialid() or newid(). Then the identity configuration of EF should work.
error_reporting(E_ALL ^ E_WARNING);
:)
You should change subject to "How to fix warning from date() in PHP"...
If you are using a SpringBoot application it's as simple as
ScheduledProcess
@Log
@Component
public class ScheduledProcess {
@Scheduled(fixedRate = 5000)
public void run() {
log.info("this runs every 5 seconds..");
}
}
Application.class
@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
A. If you use maven, an useful way to debug clashing jars is:
mvn dependency:tree
For example, for an exception:
java.lang.SecurityException: class "javax.servlet.HttpConstraintElement"'s signer information does not match signer information of other classes in the same package
we do:
mvn dependency:tree|grep servlet
Its output:
[INFO] +- javax.servlet:servlet-api:jar:2.5:compile
[INFO] +- javax.servlet:jstl:jar:1.2:compile
[INFO] | +- org.eclipse.jetty.orbit:javax.servlet.jsp:jar:2.2.0.v201112011158:compile
[INFO] | +- org.eclipse.jetty.orbit:javax.servlet.jsp.jstl:jar:1.2.0.v201105211821:compile
[INFO] | +- org.eclipse.jetty.orbit:javax.servlet:jar:3.0.0.v201112011016:compile
[INFO] +- org.eclipse.jetty:jetty-servlet:jar:9.0.0.RC2:compile
shows clashing servlet-api 2.5 and javax.servlet 3.0.0.x.
B. Other useful hints (how to debug the security exception and how to exclude maven deps) are at the question at Signer information does not match.
Here is a solution for spark in Java. To select data rows containing nulls. When you have Dataset data, you do:
Dataset<Row> containingNulls = data.where(data.col("COLUMN_NAME").isNull())
To filter out data without nulls you do:
Dataset<Row> withoutNulls = data.where(data.col("COLUMN_NAME").isNotNull())
Often dataframes contain columns of type String where instead of nulls we have empty strings like "". To filter out such data as well we do:
Dataset<Row> withoutNullsAndEmpty = data.where(data.col("COLUMN_NAME").isNotNull().and(data.col("COLUMN_NAME").notEqual("")))
One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():
In UI thread also known as the JavaFX Application thread:
...
listView.itemsProperty().bind(myListService.resultProperty());
...
in Service implementation (background worker):
...
Platform.runLater(() -> result.add("Element " + finalI));
...
if(strcmp(aString, bString) == 0){
//strings are the same
}
godspeed
Note that if you rely on sleep taking exactly 50 ms, you won't get that. It will just be about it.
Using Script Console.
In case the jobs are grouped it's possible to either give it a full name with forward slashes:
getItemByFullName("folder_name/job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
or traverse the hierarchy like this:
def folder = Jenkins.instance.getItem("folder_name")
def job = folder.getItem("job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
Search for EnableOptimizations
keyword in your project
So if you find
BundleTable.EnableOptimizations = true;
turn it false
.
This does disable minification, And it also disables bundling entirely
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA
.COLUMNS
WHERE TABLE_SCHEMA
='bodb'
AND TABLE_NAME
='abc';
works for getting all column names
A couple of things:
(?:
not (:?
If you address the first problem, you won't need groups at all.
*That is, a blank or beginning/end of string.
We're having a lot of race conditions with elementToBeClickable
. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force
Awaitility.await()
.atMost(timeout)
.ignoreException(NoSuchElementException.class)
.ignoreExceptionsMatching(
Matchers.allOf(
Matchers.instanceOf(WebDriverException.class),
Matchers.hasProperty(
"message",
Matchers.containsString("is not clickable at point")
)
)
).until(
() -> {
this.driver.findElement(locator).click();
return true;
},
Matchers.is(true)
);
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
OSError: [Errno 8] Exec format error
can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:
>>> with open('a','w') as f: f.write('exit 0') # create the script
...
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable
>>> os.execl('./a', './a') # execute it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/os.py", line 312, in execl
execv(file, args)
OSError: [Errno 8] Exec format error
To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh
at the top of your script:
>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
...
>>> os.execl('./a', './a')
It executes exit 0
without any errors.
On POSIX systems, shell parses the command line i.e., your script won't see spaces around =
e.g., if script
is:
#!/usr/bin/env python
import sys
print(sys.argv)
then running it in the shell:
$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST
produces:
['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
Note: no spaces around '='
. I've added quotes around <hostname>
to escape the redirection metacharacters <>
.
To emulate the shell command in Python, run:
from subprocess import check_call
cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)
Note: no shell=True
. And you don't need to escape <>
because no shell is run.
"Exec format error"
might indicate that your script
has invalid format, run:
$ file /usr/local/bin/script
to find out what it is. Compare the architecture with the output of:
$ uname -m
You can use .bind() to pass the param(this) to the function.
var someFunction =function(resolve, reject) {
/* get username, password*/
var username=this.username;
var password=this.password;
if ( /* everything turned out fine */ ) {
resolve("Stuff worked!");
} else {
reject(Error("It broke"));
}
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));
with a
as a numpy array, use:
if a.size:
print('array is not empty')
(in Python, objects like [1,2,3]
are called lists, not arrays.)
I built this script. It is in Yosemite and it is bash script using AppleScript to choose a list of users for SSH servers. Basically you define an IP and then the user names.. when the application launches it asks who you want to login in as.. the SSH terminal is launched and logged in prompting a password...
(***
* --- --- --- --- ---
* JD Sports Fashion plc
* Apple Script
* Khaleel Mughal
* --- --- --- --- ---
* #SHELLSTAGINGSSHBASH
* --- --- --- --- ---
***)
set stagingIP to "192.162.999.999"
set faciaName to (choose from list {"admin", "marketing", "photography_cdn"})
if faciaName is false then
display dialog "No facia was selected." with icon stop buttons {"Exit"} default button {"Exit"}
else
set faciaName to (item 1 of faciaName)
tell application "Terminal"
activate
do script "ssh " & faciaName & "@" & stagingIP & ""
end tell
end if
I highly recommend though; Nathan Pickmans post above about Shuttle (http://fitztrev.github.io/shuttle/).. a very smart and simple application.
A very simple example is that if you have a UserService
that has @Autowired
jpa resposiroty UserRepository
...
class UserService{
@Autowired
UserRepository userRepository;
...
}
then in the test class for UserService
you will do
...
class TestUserService{
@Mock
UserRepository userRepository;
@InjectMocks
UserService userService;
...
}
@InjectMocks
tells the framework that take the @Mock UserRepository userRespository;
and inject that into userService
so rather than auto wiring a real instance of UserRepository
a Mock of UserRepository
will be injected in userService
.
What about this:
import urllib, os
def from_url( url, filename = None ):
'''Store the url content to filename'''
if not filename:
filename = os.path.basename( os.path.realpath(url) )
req = urllib.request.Request( url )
try:
response = urllib.request.urlopen( req )
except urllib.error.URLError as e:
if hasattr( e, 'reason' ):
print( 'Fail in reaching the server -> ', e.reason )
return False
elif hasattr( e, 'code' ):
print( 'The server couldn\'t fulfill the request -> ', e.code )
return False
else:
with open( filename, 'wb' ) as fo:
fo.write( response.read() )
print( 'Url saved as %s' % filename )
return True
##
def main():
test_url = 'http://cdn.sstatic.net/stackoverflow/img/favicon.ico'
from_url( test_url )
if __name__ == '__main__':
main()
# list of plugins in sorted order
# Copy this into your Jenkins script console
def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
List<String> list = new ArrayList<String>()
i = 0
plugins.each {
++i
//println " ${i} ${it.getShortName()}: ${it.getVersion()}"
list.add("${it.getShortName()}: ${it.getVersion()}")
}
list.sort{it}
i = 0
for (String item : list) {
i++
println(" ${i} ${item}")
}
This could help, by the way:
The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.
http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing
If you are on mac try this :
cd Users/<Your name>
Make sure that you are on the right path by looking for .gradle with
ls -la
then run that to delete .gradle
rm -rf .gradle
This will remove everything. Then launch your commande again and it will work !
The important difference between constructors and methods is that constructors initialize objects that are being created with the new
operator, while methods perform operations on objects that already exist.
Constructors can't be called directly; they are called implicitly when the new
keyword creates an object. Methods can be called directly on an object that has already been created with new
.
The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public
), and they have method bodies in braces.
Constructors must be named with the same name as the class name. They can't return anything, even void
(the object itself is the implicit return).
Methods must be declared to return something, although it can be void
.
I've been using this amazing nuget that does dynamic annotations ExpressiveAnnotations
You could validate any logic you can dream of:
public string Email { get; set; }
public string Phone { get; set; }
[RequiredIf("Email != null")]
[RequiredIf("Phone != null")]
[AssertThat("AgreeToContact == true")]
public bool? AgreeToContact { get; set; }
If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:
INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;
If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
Just wanted to put an update. page-break-after
is a legacy property now.
Official page states
This property has been replaced by the break-after property.
It is SO ridiculous that this is not super-easy... let alone next to impossible. Hands up, I defer to Apple/Spotlight...
mdfind 'kMDItemContentType=public.unix-executable'
At least it works!
This worked for me :
Try deleting old listener using NETCA and then add new listener with same name.
If you are using android studio use simple step
Tasks
treeandroid
-> signingReport
and see the magic Result Under Run Tab If Android Studio < 2.2
From android studio 2.2
Result will be available under Run console but use highlighted toggle button
Or
Second Way is
Create new project in android studio New -> Google Maps Activity
then open google_maps_api.xml xml file as shown in pics you will see your SHA key
List<string> myList Str = myList.Select(x=>x.Value).OfType<string>().ToList();
Use "Select" to select a particular column
You can do this:
$("#elem").css("cssText", "width: 100px !important;");
Using "cssText" as the property name and whatever you want added to the CSS as its value.
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
Here is what worked in my case. Might be less performance intensive.
$('#myelement').siblings('input').first().focus();
To create setup projects in Visual Studio 2012 with InstallShield Limited Edition, watch this video.
The InstallShield limited edition that cannot install services.
"ISLE is by far the worst installer option and the upgraded, read - paid for, version is cumbersome to use at best and impossible in most situations. InnoSetup, Nullsoft, Advanced, WiX, or just about any other installer is better. If you did a survey you would see that nobody is using ISLE. I don't know why you guys continue to associate with InstallShield. It damages your credibility. Any developer worth half his weight in salt knows ISLE is worthless and when you stand behind it we have to question Microsoft's judgment."
By Edward Miller (comments in Visual Studio Installer Projects Extension).
The WiX Toolset, which, while powerful is exceeding user-unfriendly and has a steep learning curve. There is even a downloadable template for installing Windows services (ref. VS2012: Installer for Windows services?).
For Visual Studio 2013, see blog post Creating installers with Visual Studio.
You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
string connectionString= ServerName + DatabaseName + SecurityType;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
connection.Open();
bulkCopy.DestinationTableName = "TableName";
try {
bulkCopy.WriteToServer(dataTableName);
} catch (Exception e) {
Console.Write(e.Message);
}
}
Please note that the structure of the database table and the table name should be the same or it will throw an exception.
<table id="table_id" class="table table-hover">
<thead>
<tr>
...
...
</tr>
</thead>
</table>
use this command to clear the body of that table: $("#table_id tbody").empty()
I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.
hope this helps you.
Another way,
for i, v in enumerate(numbers): numbers[i] = int(v)
Probably the project you are running is not compatible (API version/Hardware requirements) with the emulator settings. Check in your build.gradle
file if the targetSDK and minimumSdk version is lower or equal to the sdk version of your Emulator.
You should also uncheck Tools > Android > Enable ADB Integration
If your case is different then restart your Android Studio and run the emulator again.
When my root view controller is embedded in a navigation controller:
UINavigationController * navigationController = (UINavigationController *)[[[[UIApplication sharedApplication] windows] firstObject] rootViewController];
RootViewController * rootVC = (RootViewController *)[[navigationController viewControllers] firstObject];
Remember that keyWindow
is deprecated.
The single most important difference between the two is that you should start using JupyterLab straight away, and that you should not worry about Jupyter Notebook at all. Because:
JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab
Other posts have suggested that Jupyter Notebook (JN) could potentially be easier to use than JupyterLab (JL) for beginners. But I would have to disagree.
A great advantage with JL, and arguably one of the most important differences between JL and JN, is that you can more easily run a single line and even highlighted text. I prefer using a keyboard shortcut for this, and assigning shortcuts is pretty straight-forward.
And the fact that you can execute code in a Python console makes JL much more fun to work with. Other answers have already mentioned this, but JL can in some ways be considered a tool to run Notebooks and more. So the way I use JupyterLab is by having it set up with an .ipynb file, a file browser and a python console like this:
And now you have these tools at your disposal:
Ctrl+Enter
Shift+Enter
Try this:
num = input("Please input your number: ")
num = float("%0.2f" % (num))
print(num)
I believe this is a lot simpler. For 1 decimal place use %0.1f
. For 2 decimal places use %0.2f
and so on.
Or, if you want to reduce it all to 2 lines:
num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)
For multiline text the left and the right margin can be set by using NSAttributedString.
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentJustified;
style.firstLineHeadIndent = 10.0f;
style.headIndent = 10.0f;
style.tailIndent = -10.0f;
NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:title attributes:@{ NSParagraphStyleAttributeName : style}];
UILabel * label = [[UILabel alloc] initWithFrame:someFrame];
label.numberOfLines = 0;
label.attributedText = attrText;
Here is the above example adopted to Swift 5:
extension UILabel {
func setMargins(margin: CGFloat = 10) {
if let textString = self.text {
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = margin
paragraphStyle.headIndent = margin
paragraphStyle.tailIndent = -margin
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
attributedText = attributedString
}
}
}
One could use the queryParam method, passing it parameter name and an array of values:
public WebTarget queryParam(String name, Object... values);
Example (jersey-client 2.23.2):
WebTarget target = ClientBuilder.newClient().target(URI.create("http://localhost"));
target.path("path")
.queryParam("param_name", Arrays.asList("paramVal1", "paramVal2").toArray())
.request().get();
This will issue request to following URL:
http://localhost/path?param_name=paramVal1¶m_name=paramVal2
Starting with API15, you can use also callOnClick()
that directly call attached view OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.
First initialize permission request code
public static final int PERMISSIONS_MULTIPLE_REQUEST = 123;
Check android version
private void checkAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission();
} else {
// write your logic here
}
}
check multiple permission code
private void checkPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.CAMERA)) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
// write your logic code if permission already granted
}
}
call back method after grant permission by user
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile)
{
// write your logic here
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
You are thinking in the function ABS
, that gives you the absolute value of numeric data.
SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable
It should be this way:
h2.myClass
looks for h2 with class myClass
. But you actually want to apply style for h2 inside .myClass
so you can use descendant selector .myClass h2
.
h2 {
color: red;
}
.myClass {
color: green;
}
.myClass h2 {
color: blue;
}
This ref will give you some basic idea about the selectors and have a look at descendant selectors
You can try this too:
public class Match
{
[Key]
public int MatchId { get; set; }
[ForeignKey("HomeTeam"), Column(Order = 0)]
public int? HomeTeamId { get; set; }
[ForeignKey("GuestTeam"), Column(Order = 1)]
public int? GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.
In my case, this simple modification solve the problem.
For CentOS 6, PHP 5.3.3 is the latest version of PHP available through the official CentOS package repository. Keep in mind, even though PHP 5.3.3 was released July 22, 2010, the official CentOS 6 PHP package was updated November 24, 2013. Why? Critical bug fixes are backported. See this question for more information: "Why are outdated packages installed by yum on CentOS? (specifically PHP 5.1) How to fix?"
If you'd like to use a more recent version of PHP, Les RPM de Remi offers CentOS PHP packages via a repository that you can add to the yum package manager. To add it as a yum repository, follow the site's instructions.
Note: Questions of this variety are probably better suited for Server Fault.
For me when i try to restore from remote host i used
psql -U username -p 5432 -h 10.10.10.1 -d database < db.dump
worked fine. And if not remote just following command worked.
psql -d database < db.dump
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
Anyway, here is how to fix it:
Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New:
Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M
taken from this link
Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.
The Windows console normaly uses CP850 encoding and not utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters -¦
instead of a degree °
.
Demonstration (using python 2.7 in a windows console):
deg = u'\xb0` # utf code for degree
print deg.encode('utf8')
effectively outputs -¦
.
Fix: just force the correct encoding (or better use unicode):
local_encoding = 'cp850' # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg
or if you use a source file that explicitely defines an encoding:
# -*- coding: utf-8 -*-
local_encoding = 'cp850' # adapt for other encodings
print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)
This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:
xdebug.max_nesting_level = 200
or in your PHP code:
ini_set('xdebug.max_nesting_level', 200);
As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.
The other answers have pointed out the solution for the majority of cases involving PropertySources
, but none have mentioned that certain property sources are unable to be casted into useful types.
One such example is the property source for command line arguments. The class that is used is SimpleCommandLinePropertySource
. This private class is returned by a public method, thus making it extremely tricky to access the data inside the object. I had to use reflection in order to read the data and eventually replace the property source.
If anyone out there has a better solution, I would really like to see it; however, this is the only hack I have gotten to work.
Setting the -fx-text-fill
works for me.
See below:
if (passed) {
resultInfo.setText("Passed!");
resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
resultInfo.setText("Failed!");
resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}
You can use the ToString overload. Have a look at this page for more info
So just Use myDate.ToString("yyyy-MM-dd HH:mm:ss")
or something equivalent
Let me try to make it simple, suppose URL of the site is www.example.com and you need to sign up by filling username and password, so we go to the login page say http://www.example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy())
finalLoc = net_loc;
else
finalLoc = gps_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
Definitely the second one. In the first one, you use a constant empty List<?>
and then convert it to a File[]
, which requires to create an empty File[0]
array. And that is what you do in the second one in one single step.
Try following these steps:
As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....
The ?
and the OR
needs to be seperated by a space character. Do it wherever needed in the query string.
No there is no built-in support for this.
You have to make your own "INIFileReader". Maybe something like this?
var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));
Console.WriteLine(data["ServerName"]);
Edit: Updated to reflect Paul's comment.
Logical OR is ||
, logical AND is &&
.
If you need the negation NOT, prefix your expression with !
.
Example:
X = (A && B) || C || !D;
Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).
If you wanted bit-wise AND/OR/NOT, you would use &
, |
and ~
. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.
Open access, go to the database tools tab, select compact and repair database. You can choose the database from there.
The Solution on top won't work because a submit redirects the page to the endpoint of form and wait for response to redirect. I see that this is an old Question but Most Asked and even i came to know the answer.Still here is my solution what i am implementing. I tried to keep it secure with Nonce but if you don't care then not required.
Method 1: You need to Pop up the form.
document.getElementById('edit_info_button').addEventListener('click',function(){
window.open('{% url "updateuserinfo" %}','newwindow', 'width=400,height=600,scrollbars=no');
});
Then you have the form open.
Submit the form normally.
Then return an HTTPResponse in render to a template(HTML file) With a STRICT Content Security Policy. A Variable that contains the following script. Nonce contains a Base64 128bits or larger randomly generated string for every request made to server.
<script nonce="{{nonce}}">window.close()</script>
Method 2:
Or you can redirect to another Page which is suppose to close ...
Which already Contains the window.close()
script.
This will close the pop up window.
Method 3:
Otherwise the simplest will be Use a Ajax call if you are comfortable with one.Use then() and check your condition to the httpresponse from the server.Close the window when success.
strtotime()
, as in date("F j, Y", strtotime("yesterday"));
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException
) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)
UNION ALL
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC
LIMIT 10)
Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV
directive, but the subsequent instruction RUN export $PATH
There's no need to export the environment variables, once you have declared them via ENV
in your Dockerfile.
As soon as the RUN export ...
lines were removed, my image was built successfully
First, add a textView in the XML file
<TextView
android:id="@+id/rate_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/what_U_want_to_display_in_first_time"
/>
then add a button in xml file with id btn_change_textView and write this two line of code in onCreate()
method of activity
Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);
then use clickListener()
on button object like this
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
textView.setText("write here what u want to display after button click in string");
}
});
fmod(x, y)
is the function you use.
You could do this:
if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
// it was an input
}
or this, which is slower, but shorter and cleaner:
if( ctrl.is('input') ) {
// it was an input
}
If you want to be more specific, you can test the type:
if( ctrl.is('input:text') ) {
// it was an input
}
They are completely different. is
checks for object identity, while ==
checks for equality (a notion that depends on the two operands' types).
It is only a lucky coincidence that "is
" seems to work correctly with small integers (e.g. 5 == 4+1). That is because CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons. This behavior is totally implementation-dependent and not guaranteed to be preserved under all manner of minor transformative operations.
For example, Python 3.5 also makes short strings singletons, but slicing them disrupts this behavior:
>>> "foo" + "bar" == "foobar"
True
>>> "foo" + "bar" is "foobar"
True
>>> "foo"[:] + "bar" == "foobar"
True
>>> "foo"[:] + "bar" is "foobar"
False
If you don't have another time interval bigger than days:
int days = (int) (milliseconds / (1000*60*60*24));
If you have weeks too:
int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));
It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.
Worked for me:
Download package (see links below), name it lp.cab and place it to your C:
drive
Run the following commands as Administrator:
2.1 installing new language
dism /Online /Add-Package /PackagePath:C:\lp.cab
2.2 get installed packages
dism /Online /Get-Packages
2.3 remove original package
dism /Online /Remove-Package /PackageName:Microsoft-Windows-Client-LanguagePack-Package~31bf3856ad364e35~amd64~ru-RU~10.0.10240.16384
If you don't know which is your original package you can check your installed packages with this line
dism /Online /Get-Packages | findstr /c:"LanguagePack"
List of MUI for Windows 10:
For LPs for Windows 10 version 1607 build 14393, follow this link.
Windows 10 x64 (Build 10240):
zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9949b0581789e2fc205f0eb005606ad1df12745b.cab
hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_c3bde55e2405874ec8eeaf6dc15a295c183b071f.cab
cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d0b2a69faa33d1ea1edc0789fdbb581f5a35ce2d.cab
da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_15e50641cef50330959c89c2629de30ef8fd2ef6.cab
nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_8658b909525f49ab9f3ea9386a0914563ffc762d.cab
en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_75d67444a5fc444dbef8ace5fed4cfa4fb3602f0.cab
fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_206d29867210e84c4ea1ff4d2a2c3851b91b7274.cab
de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_3bb20dd5abc8df218b4146db73f21da05678cf44.cab
hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e9deaa6a8d8f9dfab3cb90986d320ff24ab7431f.cab
it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_42c622dc6957875eab4be9d57f25e20e297227d1.cab
ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_adc2ec900dd1c5e94fc0dbd8e010f9baabae665f.cab
kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a03ed475983edadd3eb73069c4873966c6b65daf.cab
ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_24411100afa82ede1521337a07485c65d1a14c1d.cab
pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_894199ed72fdf98e4564833f117380e45b31d19f.cab
ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d85bb9f00b5ee0b1ea3256b6e05c9ec4029398f0.cab
es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_7b21648a1df6476b39e02476c2319d21fb708c7d.cab
uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_131991188afe0ef668d77c8a9a568cb71b57f09f.cab
Windows 10 x86 (Build 10240):
zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e7d13432345bcf589877cd3f0b0dad4479785f60.cab
hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_60856d8b4d643835b30d8524f467d4d352395204.cab
cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_dfa71b93a76b4500578b67fd3bf6b9f10bf5beaa.cab
da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_af0ea4318f43d9cb30bcfa5ce7279647f10bc3b3.cab
nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_cbcdf4818eac2a15cfda81e37595f8ffeb037fd7.cab
en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41877260829bb5f57a52d3310e326c6828d8ce8f.cab
fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_80fa697f051a3a949258797a0635a4313a448c29.cab
de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_7ea2648033099f99f87642e47e6d959172c6cab8.cab
hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_78a11997f4e4bf73bbdb1da8011ebfb218bd1bac.cab
it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9e62d9a8b141e0eb6434af5a44c4f9468b60a075.cab
ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_79bd099ac811cb1771e6d9b03d640e5eca636b23.cab
kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_59e690df497799cacb96ab579a706250e5a0c8b6.cab
ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a88379b0461479ab8b5b47f65c4c3241ef048c04.cab
pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_bb9f192068fe42fde8787591197a53c174dce880.cab
ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_280bf97bbe34cec1b0da620fa1b2dfe5bdb3ea07.cab
es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_31400c38ffea2f0a44bb2dfbd80086aa3cad54a9.cab
uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41cd48aa22d21f09fbcedc69197609c1f05f433d.cab
Look at the documentation page.
Tweaking an existing Firefox profile
You need to change "network.proxy.http" & "network.proxy.http_port" profile settings.
FirefoxProfile profile = new FirefoxProfile();
profile.addAdditionalPreference("network.proxy.http", "localhost");
profile.addAdditionalPreference("network.proxy.http_port", "3128");
WebDriver driver = new FirefoxDriver(profile);
Double check if you are not able to use keys.
Otherwise use expect:
#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.
If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".
see Bootstrap 3 docs: http://getbootstrap.com/css/#grid
I had same issue. No need to re install.
In Netbeans 6.0 , Find RunTime -> Servers - > Add server -> select Tomcat install 'root' directory
In Netbeans 7.x -> Tools -> Servers-> Add server -> select Tomcat install 'root' directory
Here is in Netbeans Wiki.
The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?
Require all granted
is only in 2.4, but Allow all ...
stops working in 2.4, and we want to be able to rollout a config that works in both.
The only solution I found, which I am not sure is the proper one, is to use:
# backwards compatibility with apache 2.2
Order allow,deny
Allow from all
# forward compatibility with apache 2.4
Require all granted
Satisfy Any
This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...
See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.
You can use twitter search page to bypass 3,200 limit. However you have to scroll down many times in the search results page. For example, I searched tweets from @beyinsiz_adam. This is the link of search results: https://twitter.com/search?q=from%3Abeyinsiz_adam&src=typd&f=realtime
Now in order to scroll down many times, you can use the following javascript code.
var myVar=setInterval(function(){myTimer()},1000);
function myTimer() {
window.scrollTo(0,document.body.scrollHeight);
}
Just run it in the FireBug console. And wait some time to load all tweets.
There are obviously several reasons why this might occur, and I thought I'd add the solution to my issue. (I have a java project into which I have imported files with virtual links)
If you have a situation like mine, you will have another folder on the same level as your 'src' folder. If you do, right-click on that other folder, then select 'Build Path' > 'Add to Build Path' (if you see 'Build Path' > 'Remove from Build Path', then it had already been added.)
To further configure the Build Path, right click on your top level project dir, and select 'Build Path' > 'Configure Build Path'. Your folders should show up in the 'Source' tab.
To configure what errors you see, Click on Java Compiler > Errors/Warnings and then click 'Configure Workspace Settings'. That is the same as going to Window > Preferences > Java > Compiler > Errors/Warnings. If you don't want Eclipse to ignore something, then just change it to Warning.
Use this
<xsl:text disable-output-escaping="yes">&</xsl:text>nbsp;
edit: Downvoters should probably validate that this works first (it does, and is the most general solution to the problem.)
The resources you put in src/main/resources will be copied during the build process to target/classes which can be accessed using:
...this.getClass().getResourceAsStream("/config.txt");
Or you can do it like as well:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
Starting from SQL Server 2016+, Query Store feature was introduced to monitor performance. It provides insight into query plan choice and performance. It’s not a complete replacement of trace or extended events, but as it’s evolving from version to version, we might get a fully functional query store in future releases from SQL Server. The primary flow of Query Store
Enabling the Query Store: Query Store works at the database level on the server.
tempdb
database.
sys.database_query_store_options
(Transact-SQL)
Collect Information in the Query Store: We collect all the available information from the three stores using Query Store DMV (Data Management Views).
Query Plan Store: Persisting the execution plan information and it is accountable for capturing all information that is related to query compilation.
sys.query_store_query
(Transact-SQL)sys.query_store_plan
(Transact-SQL)sys.query_store_query_text
(Transact-SQL)
Runtime Stats Store: Persisting the execution statistics information and it is probably the most frequently updated store. These statistics represent query execution data.
sys.query_store_runtime_stats
(Transact-SQL)
Query Wait Stats Store: Persisting and capturing wait statistics information.
sys.query_store_wait_stats
(Transact-SQL)
NOTE: Query Wait Stats Store is available only in SQL Server 2017+
Check if you actually have installed the buildVersionTools you are using. In my case I tried 25.0.1 whilst I only had 25.0.2.
To check it go to the SDK Manager, clicking the icon:
Then click Launch Standalone SDK Manager at the bottom:
Now check whatever you need and install packages.
Hope it helps!
I think there is an easy way to achieve this and It's working fine for me.
To SELECT rows using REGEX
SELECT * FROM `table_name` WHERE `column_name_to_find` REGEXP 'string-to-find'
To UPDATE rows using REGEX
UPDATE `table_name` SET column_name_to_find=REGEXP_REPLACE(column_name_to_find, 'string-to-find', 'string-to-replace') WHERE column_name_to_find REGEXP 'string-to-find'
REGEXP Reference: https://www.geeksforgeeks.org/mysql-regular-expressions-regexp/
call srand(sameSeed)
before calling rand()
. More details here.
JSON of unknown format to HashMap
public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
writeJson("JsonFile.json");
readgson("JsonFile.json");
}
public static void readgson(String file) {
try {
System.out.println( "Reading JSON file from Java program" );
FileReader fileReader = new FileReader( file );
com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
if ( keys.isEmpty() ) {
System.out.println( "Empty JSON Object" );
}else {
Map<String, Object> map = json_UnKnown_Format( keys );
System.out.println("Json 2 Map : "+map);
}
} catch (IOException ex) {
System.out.println("Input File Does not Exists.");
}
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
Map<String, Object> jsonMap = new HashMap<String, Object>();
for (Entry<String, JsonElement> entry : keys) {
String keyEntry = entry.getKey();
System.out.println(keyEntry + " : ");
JsonElement valuesEntry = entry.getValue();
if (valuesEntry.isJsonNull()) {
System.out.println(valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonPrimitive()) {
System.out.println("P - "+valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonArray()) {
JsonArray array = valuesEntry.getAsJsonArray();
List<Object> array2List = new ArrayList<Object>();
for (JsonElement jsonElements : array) {
System.out.println("A - "+jsonElements);
array2List.add(jsonElements);
}
jsonMap.put(keyEntry, array2List);
}else if (valuesEntry.isJsonObject()) {
com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
}
}
return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {
JSONObject json = new JSONObject();
json.put("Key1", "Value");
json.put("Key2", 777); // Converts to "777"
json.put("Key3", null);
json.put("Key4", false);
JSONArray jsonArray = new JSONArray();
jsonArray.put("Array-Value1");
jsonArray.put(10);
jsonArray.put("Array-Value2");
json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]
JSONObject jsonObj = new JSONObject();
jsonObj.put("Obj-Key1", 20);
jsonObj.put("Obj-Key2", "Value2");
jsonObj.put(4, "Value2"); // Converts to "4"
json.put("InnerObject", jsonObj);
JSONObject jsonObjArray = new JSONObject();
JSONArray objArray = new JSONArray();
objArray.put("Obj-Array1");
objArray.put(0, "Obj-Array3");
jsonObjArray.put("ObjectArray", objArray);
json.put("InnerObjectArray", jsonObjArray);
Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
sortedTree.put("Sorted1", 10);
sortedTree.put("Sorted2", 103);
sortedTree.put("Sorted3", 14);
json.put("TreeMap", sortedTree);
try {
System.out.println("Writting JSON into file ...");
System.out.println(json);
FileWriter jsonFileWriter = new FileWriter(file);
jsonFileWriter.write(json.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
The show command may be what you want. Try
git show -s --format=%ci <commit>
Other formats for the date string are available as well. Check the manual page for details.
if you want to find mode as int Value here is the easiest way I was trying to find out mode of Array using Scipy Stats but the problem is that output of the code look like:
ModeResult(mode=array(2), count=array([[1, 2, 2, 2, 1, 2]]))
, I only want the Integer output so if you want the same just try this
import numpy as np
from scipy import stats
numbers = list(map(int, input().split()))
print(int(stats.mode(numbers)[0]))
Last line is enough to print Mode Value in Python: print(int(stats.mode(numbers)[0]))
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
These are the escape codes that I've found:
* = \x2a
( = \x28
) = \x29
" = \x22
/ = \x2f
\ = \x5c
' = \x27
? = \x3f
% = \x25
^ = \x5e
There are already many good answers to the part "what is uintptr_t data type". I will try to address the "what it can be used for?" part in this post.
Primarily for bitwise operations on pointers. Remember that in C++ one cannot perform bitwise operations on pointers. For reasons see Why can't you do bitwise operations on pointer in C, and is there a way around this?
Thus in order to do bitwise operations on pointers one would need to cast pointers to type unitpr_t and then perform bitwise operations.
Here is an example of a function that I just wrote to do bitwise exclusive or of 2 pointers to store in a XOR linked list so that we can traverse in both directions like a doubly linked list but without the penalty of storing 2 pointers in each node.
template <typename T>
T* xor_ptrs(T* t1, T* t2)
{
return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(t1)^reinterpret_cast<uintptr_t>(t2));
}
You can do "redundant styling" and that should fix the issue. You use the same styling you have on the but add it to a that is within the .
Example:
<td width="110" align="center" valign="top" style="color:#000000;">
<a href="https://example.com" target="_blank"
style="color:#000000; text-decoration:none;"><span style="color:#000000; text-decoration:none;">BOOK NOW</span></a>
</td>
The other solutions seem to stray from the blessed path and I found that my scenario was covered in the Typescript documentation which I've paraphrased below:
interface AppPackageCheck<T> {
new (packageExists: boolean): T
checkIfPackageExists(): boolean;
}
class WebApp {
public static checkIfPackageExists(): boolean {
return false;
}
constructor(public packageExists: boolean) {}
}
class BackendApp {
constructor(public packageExists: boolean) {}
}
function createApp<T>(type: AppPackageCheck<T>): T {
const packageExists = type.checkIfPackageExists();
return new type(packageExists)
}
let web = createApp(WebApp);
// compiler failure here, missing checkIfPackageExists
let backend = createApp(BackendApp);
&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if
or while
loop expressions.
TextView does not support setMargins. Android docs say:
Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.
I kept running into this problem when trying to capture JSON data in the log with the Python logging
library, for debugging and troubleshooting purposes. Getting the u
character is a real nuisance when you want to copy the text and paste it into your code somewhere.
As everyone will tell you, this is because it is a Unicode representation, and it could come from the fact that you’ve used json.loads()
to load in the data from a string in the first place.
If you want the JSON representation in the log, without the u
prefix, the trick is to use json.dumps()
before logging it out. For example:
import json
import logging
# Prepare the data
json_data = json.loads('{"key": "value"}')
# Log normally and get the Unicode indicator
logging.warning('data: {}'.format(json_data))
>>> WARNING:root:data: {u'key': u'value'}
# Dump to a string before logging and get clean output!
logging.warning('data: {}'.format(json.dumps(json_data)))
>>> WARNING:root:data: {'key': 'value'}
In 1.0 and 2.0 you can use createElement
prop of Router
to specify how exactly to create your target element. Documentation source
function createWithDefaultProps(Component, props) {
return <Component {...props} myprop="value" />;
}
// and then
<Router createElement={createWithDefaultProps}>
...
</Router>
calling
var parsed_data = JSON.parse(data);
should result in the ability to access the data like you want.
console.log(parsed_data.success);
should now show '1'
Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
or (e.g. with sqlite3 from the Python standard library):
cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))
or others yet (after VALUES
you could have (:1, :2, :3)
, or "named styles" (:fee, :fie, :fo)
or (%(fee)s, %(fie)s, %(fo)s)
where you pass a dict instead of a map as the second argument to execute
). Check the paramstyle
string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!
Probably something like this:
original_list = dictionary.get('C1')
new_list = []
for item in original_list:
new_list.append(item+10)
dictionary['C1'] = new_list
Try both of these commands and see for yourself why arp is faster:
for ip in $(seq 1 254); do ping -c 1 10.185.0.$ip > /dev/null; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done
for ip in $(seq 1 254); do arp -n 10.185.0.$ip | grep Address; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done
use Integer as the type and provide setter/getter accordingly..
private Integer num;
public Integer getNum()...
public void setNum(Integer num)...
I would just use the FindAll method on the List class. i.e.:
List<Person> filteredResults =
people.FindAll(p => return !exclusions.Contains(p));
Not sure if the syntax will exactly match your objects, but I think you can see where I'm going with this.
I believe you probably meant:
from __future__ import print_function
for song in json_object:
# now song is a dictionary
for attribute, value in song.items():
print(attribute, value) # example usage
NB: You could use song.iteritems
instead of song.items
if in Python 2.
"Truncate doesn't log anything" is correct. I'd go further:
Truncate is not executed in the context of a transaction.
The speed advantage of truncate over delete should be obvious. That advantage ranges from trivial to enormous, depending on your situation.
However, I've seen truncate unintentionally break referential integrity, and violate other constraints. The power that you gain by modifying data outside a transaction has to be balanced against the responsibility that you inherit when you walk the tightrope without a net.
Refer this link for linux command linux http://linuxcommand.org/man_pages/grep1.html
for displaying line no ,line of code and file use this command in your terminal or cmd, GitBash(Powered by terminal)
grep -irn "YourStringToBeSearch"
On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa
With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '
I was used Total Commander for taking file from Internal storage
<table style="width: auto;" ...
works fine. Tested in Chrome 38 , IE 11 and Firefox 34.
jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/
You need to use a regular expression, so that you can specify the global (g) flag:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
The problem is that you mapped your servlet to /register.html
and it expects POST method, because you implemented only doPost()
method. So when you open register.html
page, it will not open html page with the form but servlet that handles the form data.
Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).
To fix:
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
Here are a few ways to remove an item from an array using JavaScript.
All the method described do not mutate the original array, and instead create a new one.
Suppose you have an array, and you want to remove an item in position i
.
One method is to use slice()
:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))
console.log(filteredItems)
_x000D_
slice()
creates a new array with the indexes it receives. We simply create a new array, from start to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array.
In this case, one good option is to use filter()
, which offers a more declarative approach:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
console.log(filteredItems)
_x000D_
This uses the ES6 arrow functions. You can use the traditional functions to support older browsers:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
return item !== valueToRemove
})
console.log(filteredItems)
_x000D_
or you can use Babel and transpile the ES6 code back to ES5 to make it more digestible to old browsers, yet write modern JavaScript in your code.
What if instead of a single item, you want to remove many items?
Let's find the simplest solution.
You can just create a function and remove items in series:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const removeItem = (items, i) =>
items.slice(0, i-1).concat(items.slice(i, items.length))
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]
console.log(filteredItems)
_x000D_
You can search for inclusion inside the callback function:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]
console.log(filteredItems)
_x000D_
splice()
(not to be confused with slice()
) mutates the original array, and should be avoided.
(originally posted on my site https://flaviocopes.com/how-to-remove-item-from-array/)
just to add to options: <h:outputText value="&nbsp;" escape="false"/>
worked
Registering DLL for Fundsite
Outdated or missing comdlg32.ocx runtime library can be the problem of causing this error. Make sure comdlg32.ocx file is not corrupted otherwise Download the File comdlg32.ocx (~60 Kb Zip).
Download the file and extract the comdlg32.ocx to your the Windows\System32 folder or Windows\SysWOW64. In my case i started with Windows\System32 but it didn’t work at my end, so I again saved in Windows\SysWOW64.
Type following command from Start, Run dialog:“c:\windows>System32\regsvr32 Comdlg32.ocx “ or “c:\windows>SysWOW64\regsvr32 Comdlg32.ocx ”
Now Comdlg.ocx File is register and next step is to register the DLL
Copy the Fundsite.Text.Encoding. dll into .Net Framework folder for 64bit on below path C:\Windows\Microsoft.NET\Framework64\v2.0.50727
Then on command prompt and go to directory C:\Windows\Microsoft.NET\Framework64\v2.0.50727 and then run the following command as shown below.
This will register the dll successfully.
C:\Windows\Microsoft.net\framework64\v2.0.50727>regasm "Dll Name".dll
As has been pointed out ... in a select
box, the .val()
attribute will give you the value of the selected option. If the selected option does not have a value attribute it will default to the display value of the option (which is what the examples on the jQuery documentation of .val
show.
you want to use .text()
of the selected option:
$('#Crd option:selected').text()
You can with regular expressions Input Patterns (check browser compatibility)
<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>
<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>
There are 8 bits in a byte (normally speaking in Windows).
However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.
In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.
EDITED
Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.
If you're using jQuery versions 1.4.3+:
$('selector').click(false);
If not:
$('selector').click(function(){return false;});
How about this method:
Set a field in the first object to a new value. If the same field in the second object has the same value, it's probably the same instance. Otherwise, exit as different.
Now set the field in the first object to a different new value. If the same field in the second object has changed to the different value, it's definitely the same instance.
Don't forget to set field in the first object back to it's original value on exit.
Problems?
When a JSON start's with {} it is a ObjectJSON object and when it start's with [] it is an Array JOSN Array
An JSON array can consist of a/many objects and that is called an array of objects
The best way is to use the following code:
<a href="<?php echo base_url() ?>directory_name/filename.php">Link</a>
For future readers who need this answer quickly:
2^31-1 = 2.147.483.647 characters
Using python and telethon it's very easy to get chat id. This solution is best for those who work with telegram API.
If you don't have telethon, run this:
pip install telethon
If you don't have a registered app with telegram, register one: The link is this: https://my.telegram.org/
Then run the following code:
from telethon import InteractiveTelegramClient
from telethon.utils.tl_utils import get_display_name
client = InteractiveTelegramClient('session_id', 'YOUR_PHONE_NUMBER', api_id=1234YOURAPI_ID, api_hash='YOUR_API_HASH')
dialog_count = 10
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
i += 1 # 1-based index
print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))
You may want to send a message to your group so the group show up in top of the list.
If you are not very offended by the GOTO
keyword, it can be used to simulate a DO
/ WHILE
in T-SQL. Consider the following rather nonsensical example written in pseudocode:
SET I=1
DO
PRINT I
SET I=I+1
WHILE I<=10
Here is the equivalent T-SQL code using goto:
DECLARE @I INT=1;
START: -- DO
PRINT @I;
SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10
Notice the one to one mapping between the GOTO
enabled solution and the original DO
/ WHILE
pseudocode. A similar implementation using a WHILE
loop would look like:
DECLARE @I INT=1;
WHILE (1=1) -- DO
BEGIN
PRINT @I;
SET @I+=1;
IF NOT (@I<=10) BREAK; -- WHILE @I<=10
END
Now, you could of course rewrite this particular example as a simple WHILE
loop, since this is not such a good candidate for a DO
/ WHILE
construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO
/ WHILE
are rare.
REPEAT / UNTIL, anyone (does NOT work in T-SQL)?
SET I=1
REPEAT
PRINT I
SET I=I+1
UNTIL I>10
... and the GOTO
based solution in T-SQL:
DECLARE @I INT=1;
START: -- REPEAT
PRINT @I;
SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10
Through creative use of GOTO
and logic inversion via the NOT
keyword, there is a very close relationship between the original pseudocode and the GOTO
based solution. A similar solution using a WHILE
loop looks like:
DECLARE @I INT=1;
WHILE (1=1) -- REPEAT
BEGIN
PRINT @I;
SET @I+=1;
IF @I>10 BREAK; -- UNTIL @I>10
END
An argument can be made that for the case of the REPEAT
/ UNTIL
, the WHILE
based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.
If it wasn't for all of the disdain around the use of GOTO
, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.
Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO
.
I don't know why this question was reopened but here is a tidyverse
option.
x %>%
arrange(desc(value)) %>%
mutate(variable=fct_reorder(variable,value)) %>%
ggplot(aes(variable,value,fill=variable)) + geom_bar(stat="identity") +
scale_y_continuous("",label=scales::percent) + coord_flip()
If you use opacity
to a element, entire element effect that(background+other things in it),you can use mix-blend-mode
to the CSS attributes of the specific element,
Refer these sites:
You're trying to do &(2), &(4)
which won't work
#romtest {
.detailed {
th {
&:nth-child(2) {//your styles here}
&:nth-child(4) {//your styles here}
&:nth-child(6) {//your styles here}
}
}
}
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
The following should work,Please Try this:
$effectiveDate = strtotime("+1 months", strtotime(date("y-m-d")));
echo $time = date("y/m/d", $effectiveDate);
Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...
Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String
and you to compare them...
1. you have 2 string values you get from an input and you'd like to compare them, they are as below:
var date1 = '01/12/2018';
var date2 = '12/12/2018';
2. They need to be Date Object
to be compared as date values, so simply convert them to date, using new Date()
, I just re-assign them for simplicity of explanation, but you can do it anyway you like:
date1 = new Date(date1);
date2 = new Date(date2);
3. Now simply compare them, using the >
<
>=
<=
date1 > date2; //false
date1 < date2; //true
date1 >= date2; //false
date1 <= date2; //true
I was wondering if/how I can 'create' a html page for each database row?
You just need to create one php
file that generate an html template, what changes is the text based content on that page. In that page is where you can get a parameter (eg. row id) via POST
or GET
and then get the info form the database.
I'm assuming this would be better for SEO?
Search Engine as Google interpret that example.php?id=33
and example.php?id=44
are different pages, and yes, this way is better than single listing page from the SEO point of view, so you just need two php files at least (listing.php
and single.php
), because is better link this pages from the listing.php
.
Extra advice:
example.php?id=33
is really ugly and not very seo friendly, maybe you need some url rewriting code. Something like example/properties/property-name
is better ;)
Please consider:
print "Element at index $_ is $x[$_]\n" for keys @x;
What worked for me is to create a log4j properties file (you can find many examples over the net) and place it in properties folder in your project directory (create this folder if not exicts). The right click on the folder and Build Path->Use as Source Folder
.
Hope it helps!
You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.
VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;
You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.
This link may help you. Try checking in your manifest for problems. If you can get it to happen again, post your entire stack trace so that we can see what the error actually is.
EDIT: I'm sure you've checked this, but what is on line 12 of the XML file you use for the TourActivity layout?
If you want something that works and is future-proof, use a library like MomentJS.
moment(date).week();
moment(date).isoWeek()
We had a problem with the (deprecated) dialect org.hibernate.dialect.Oracledialect
and Oracle 11g database using hibernate.hbm2ddl.auto = validate
mode.
With this dialect Hibernate was unable to found the sequences (because the implementation of the getQuerySequencesString()
method, that returns this query:
"select sequence_name from user_sequences;"
for which the execution returns an empty result from database).
Using the dialect org.hibernate.dialect.Oracle9iDialect
, or greater, solves the problem, due to a different implementation of getQuerySequencesString()
method:
"select sequence_name from all_sequences union select synonym_name from all_synonyms us, all_sequences asq where asq.sequence_name = us.table_name and asq.sequence_owner = us.table_owner;"
that returns all the sequences if executed, instead.
jQuery's $.getScript()
is buggy sometimes, so I use my own implementation of it like:
jQuery.loadScript = function (url, callback) {
jQuery.ajax({
url: url,
dataType: 'script',
success: callback,
async: true
});
}
and use it like:
if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
//Stuff to do after someScript has loaded
});
How about this?
>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]
[1]
>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']
[2]
As pointed out in the comments, this would get all matches. To just get the first one, you can do:
>>> [y[0] for y in tuple_list].index('kumquat')
2
There is a good discussion in the comments as to the speed difference between all the solutions posted. I may be a little biased but I would personally stick to a one-liner as the speed we're talking about is pretty insignificant versus creating functions and importing modules for this problem, but if you are planning on doing this to a very large amount of elements you might want to look at the other answers provided, as they are faster than what I provided.
Many answers are already there, I just need to identify one difference which is not there.
for loop is fail-safe while foreach loop is fail-fast.
Fail-fast iteration throws ConcurrentModificationException
if iteration and modification are done at the same time in object.
However, fail-safe iteration keeps the operation safe from failing even if the iteration goes in infinite loop.
public class ConcurrentModification {
public static void main(String[] args) {
List<String> str = new ArrayList<>();
for(int i=0; i<1000; i++){
str.add(String.valueOf(i));
}
/**
* this for loop is fail-safe. It goes into infinite loop but does not fail.
*/
for(int i=0; i<str.size(); i++){
System.out.println(str.get(i));
str.add(i+ " " + "10");
}
/**
* throws ConcurrentModificationexception
for(String st: str){
System.out.println(st);
str.add("10");
}
*/
/* throws ConcurrentModificationException
Iterator<String> itr = str.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
str.add("10");
}*/
}
}
Hope this helps to understand the difference between for and foreach loop through different angle.
I found a good blog to go through the differences between fail-safe and fail-fast, if anyone interested: