Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
This error is weird as many proposed answers and got mixed solutions. I tried them, add them. It was only when I added pip install --upgrade pip
finally removed the error for me. But I have no time to isolate which is which,so this is just fyi.
setup.py
is a Python script that is usually shipped with libraries or programs, written in that language. It's purpose is the correct installation of the software.
Many packages use the distutils
framework in conjuction with setup.py
.
I've now seen this in legacy tools using Python2.7, where a build (like a Dockerfile) installs an unpinned dependancy, for example pytest. PyTest has dropped Python 2.7 support, so you may need to specify version < the new package release.
Or bite the bullet and convert that app to Python 3 if that is viable.
This below command worked for me
Python version - 2.7
package - python-jenkins
command - $ pip install 'python-jenkins>=1.1.1'
At least for Ubuntu (maybe also others) works this (inspired by a previous post in this thread):
printf "Installed with pip:";
pip list 2>/dev/null | gawk '{print $1;}' | while read; do pip show "${REPLY}" 2>/dev/null | grep 'Location: /usr/local/lib/python2.7/dist-packages' >/dev/null; if (( $? == 0 )); then printf " ${REPLY}"; fi; done; echo
Now python gives you the choice to install pip
during the installation (I am on Windows, and at least python does so for Windows!). Considering you had chosen to install pip
during installation of python (you don't actually have to choose because it is default), pip
is already installed for you. Then, type in pip
in command prompt, you should see a help come up. You can find necessary usage instructions there. E.g. pip list
shows you the list of installed packages. You can use
pip uninstall package_name
to uninstall any package that you don't want anymore. Read more here (pip documentation).
You define the dependent module inside the setup.py of your own package with the "install_requires" option.
If your package needs to have some console script generated then you can use the "console_scripts" entry point in order to generate a wrapper script that will be placed within the 'bin' folder (e.g. of your virtualenv environment).
From Ian Bicking's own introduction to pip:
pip was originally written to improve on easy_install in the following ways
- All packages are downloaded before installation. Partially-completed installation doesn’t occur as a result.
- Care is taken to present useful output on the console.
- The reasons for actions are kept track of. For instance, if a package is being installed, pip keeps track of why that package was required.
- Error messages should be useful.
- The code is relatively concise and cohesive, making it easier to use programmatically.
- Packages don’t have to be installed as egg archives, they can be installed flat (while keeping the egg metadata).
- Native support for other version control systems (Git, Mercurial and Bazaar)
- Uninstallation of packages.
- Simple to define fixed sets of requirements and reliably reproduce a set of packages.
I use this:
function fnIsAppleMobile()
{
if (navigator && navigator.userAgent && navigator.userAgent != null)
{
var strUserAgent = navigator.userAgent.toLowerCase();
var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
if (arrMatches != null)
return true;
} // End if (navigator && navigator.userAgent)
return false;
} // End Function fnIsAppleMobile
var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove
For JDK 1.3 or earlier :
-Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006
For JDK 1.4
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006
For newer JDK :
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6006
Please change the port number based on your needs.
From java technotes
From 5.0 onwards the -agentlib:jdwp option is used to load and specify options to the JDWP agent. For releases prior to 5.0, the -Xdebug and -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the VM rather than the older JVMDI interface)
One more thing to note, from JVM Tool interface documentation:
JVM TI was introduced at JDK 5.0. JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI) which, as of JDK 6, are no longer provided.
As per UI Doc :
First get index of tab which you want to activate.
var index = $('#tabs a[href="'+id+'"]').parent().index();
Activate it
tabs.tabs( "option", "active", index );
truncate tableName
That is what you are looking for.
Truncate will delete all records in the table, emptying it.
You can also do this by passing function with onclick event
<a onclick="getColor(this);" color="red">
<script type="text/javascript">
function getColor(el)
{
color = $(el).attr('color');
alert(color);
}
</script>
You can try as follows it works for me.
Start server:
sudo service mysql start
Now, Go to sock folder:
cd /var/run
Back up the sock:
sudo cp -rp ./mysqld ./mysqld.bak
Stop server:
sudo service mysql stop
Restore the sock:
sudo mv ./mysqld.bak ./mysqld
Start mysqld_safe:
sudo mysqld_safe --skip-grant-tables --skip-networking &
Init mysql shell:
mysql -u root
Change password:
Hence, First choose the database
mysql> use mysql;
Now enter below two queries:
mysql> update user set authentication_string=password('123456') where user='root';
mysql> update user set plugin="mysql_native_password" where User='root';
Now, everything will be ok.
mysql> flush privileges;
mysql> quit;
For checking:
mysql -u root -p
done!
N.B, After login please change the password again from phpmyadmin
Now check hostname/phpmyadmin
Username: root
Password: 123456
For more details please check How to reset forgotten password phpmyadmin in Ubuntu
Here are the steps with Auto Layout
that worked for me on XCode 8.2.1.
Size Inspector
of View Controller
, and change Simulated Size
to Freeform
with height 1000 instead of Fixed
.View Controller
as RootView.Scroll View
as subview of RootView and rename it as ScrollView.Vertical Stack View
as subview of ScrollView and rename it as ContentView.Attributes Inspector
of ContentView, and change Distribution
to Fill Equally
instead of Fill
.View
as subview of ContentView and rename it as RedView.Red
as the background of RedView.View
as subview of ContentView and rename it as BlueView.Blue
as the background of BlueView.Update Frames
button.
View hierarchy:
View Controller Scene (Height: 1000):
Run on iPhone7 (Height: 1334 / 2):
We can add the parent pom as a dependency with type pom and make exclusion on that. Because anyhow parent pom is downloaded. This worked for me
<dependency>
<groupId>com.abc.boot</groupId>
<artifactId>abc-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<type>pom</type>
<exclusions>
<exclusion>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</exclusion>
</exclusions>
</dependency>
Here is a list of available builds for debian: https://github.com/nodesource/distributions/tree/master/deb
For this example, lets assume you want version 14 (LTS at the time of writing)
We can download this script from github, execute it and install the version of node we want. For security reasons it's a good idea to read the script prior to executing it.
curl -sL https://raw.githubusercontent.com/nodesource/distributions/master/deb/setup_14.x | bash
apt-get install -y nodejs # may or may not require sudo based on your setup
I like this approach because it doesn't require extraneous dependencies like nvm to target specific versions
If you are building for a different distro or architecture you can find more builds here https://nodejs.org/dist/
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
As Chris suggested the reason you're using ViewModel doesn't stop you from using PagedList
.
You need to form a collection of your ViewModel objects that needs to be send to the view for paging over.
Here is a step by step guide on how you can use PagedList
for your viewmodel data.
Your viewmodel (I have taken a simple example for brevity and you can easily modify it to fit your needs.)
public class QuestionViewModel
{
public int QuestionId { get; set; }
public string QuestionName { get; set; }
}
and the Index method of your controller will be something like
public ActionResult Index(int? page)
{
var questions = new[] {
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 1" },
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 2" },
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 3" },
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 4" }
};
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(questions.ToPagedList(pageNumber, pageSize));
}
And your Index view
@model PagedList.IPagedList<ViewModel.QuestionViewModel>
@using PagedList.Mvc;
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.QuestionId)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuestionName)
</td>
</tr>
}
</table>
<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager( Model, page => Url.Action("Index", new { page }) )
Here is the SO link with my answer that has the step by step guide on how you can use PageList
multipart/form-data
is used when you want to upload files to the server. Please check this article for details.
Having $line
as it is now, you can simply split the string based on at least one whitespace separator
my @answer = split(' ', $line); # creates an @answer array
then
print("@answer\n"); # print array on one line
or
print("$_\n") for (@answer); # print each element on one line
I prefer using ()
for split
, print
and for
.
The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):
./gradlew wrapper --gradle-version 5.5
Moreover, you can use --distribution-type
parameter with either bin
or all
value to choose a distribution type. Use all
distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:
./gradlew wrapper --gradle-version 5.5 --distribution-type all
Or you can create a custom wrapper
task
task wrapper(type: Wrapper) {
gradleVersion = '5.5'
}
and run ./gradlew wrapper
.
We can also convert data.frame columns generically to a simple vector. as.vector
is not enough as it retains the data.frame class and structure, so we also have to pull out the first (and only) element:
df_column_object <- aframe[,2]
simple_column <- df_column_object[[1]]
All the solutions suggested so far require hardcoding column titles. This makes them non-generic (imagine applying this to function arguments).
Alternatively, you could, of course read the column names from the column first and then insert them in the code in the other solutions.
Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.
Step 1. Use the following namespaces
using System.Windows;
using System.Threading;
using System.Windows.Threading;
Step 2. Put the following line where you need to update UI
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
//Update UI here
}));
Syntax
[BrowsableAttribute(false)] public object Invoke( DispatcherPriority priority, Delegate method )
Parameters
priority
Type:
System.Windows.Threading.DispatcherPriority
The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.
method
Type:
System.Delegate
A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.
Return Value
Type:
System.Object
The return value from the delegate being invoked or null if the delegate has no return value.
Version Information
Available since .NET Framework 3.0
Another option is to bind 'View.TrackActivityInSolutionExplorer' to a keyboard short-cut, which is the same as 'Tools-->Options-->Projects and Solutions-->Track Active Item in Solution Explorer'
If you activate the short-cut twice the file is selected in the solution explorer, and the tracking is disabled again.
Visual Studio 2013+
There is now a feature built in to the VS2013 solution explorer called Sync with Active Document. The icon is two arrows in the solution explorer, and has the hotkey Ctrl + [, S to show the current document in the solution explorer. Does not enable the automatic setting mentioned above, and only happens once.
Overriding the input directive does seem to do the job. I made some minor alterations to Dan Hunsaker's code:
$parse().assign()
on fields without a ngModel attributes.assign()
function param order.app.directive('input', function ($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, element, attrs) {
if (attrs.ngModel && attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
});
It looks like SyndFeed
is not using generics.
You could either have an unsafe cast and a warning suppression:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = (List<SyndEntry>) sf.getEntries();
or call Collections.checkedList - although you'll still need to suppress the warning:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = Collections.checkedList(sf.getEntries(), SyndEntry.class);
You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but this post about the invalid JSON primitive covers why the JSON is being URLEncoded.
I'd advise against passing a raw, manually-serialized JSON string into your method. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.
I'd suggest something more along these lines:
var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }];
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
error: function(errMsg) {
alert(errMsg);
}
});
The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data
parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.
On the server-side, match your method's input parameters to the shape of the data you're passing in:
public class Marker
{
public decimal position { get; set; }
public int markerPosition { get; set; }
}
[WebMethod]
public string CreateMarkers(List<Marker> Markers)
{
return "Received " + Markers.Count + " markers.";
}
You can also accept an array, like Marker[] Markers
, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.
In general keeping data like this is not a great thing to do if you can avoid it, because people are always confusing tabs and spaces.
Solving your problem is very straightforward in a scripting language like Perl, Python or Ruby. Here's some example code:
#!/usr/bin/perl -w
use strict;
my $sort_field = 2;
my $split_regex = qr{\s+};
my @data;
push @data, "7 8\t 9";
push @data, "4 5\t 6";
push @data, "1 2\t 3";
my @sorted_data =
map { $_->[1] }
sort { $a->[0] <=> $b->[0] }
map { [ ( split $split_regex, $_ )[$sort_field], $_ ] }
@data;
print "unsorted\n";
print join "\n", @data, "\n";
print "sorted by $sort_field, lines split by $split_regex\n";
print join "\n", @sorted_data, "\n";
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
Both id
and name
are bean identifiers in Spring IOC container/ApplicationContecxt. The id
attribute lets you specify exactly one id but using name
attribute you can give alias name to that bean.
You can check the spring doc here.
(This is more of a comment but I can't comment because of the low reputation, somebody might find these useful)
If you're in sth.com/product and you want to redirect to sth.com/product/index use
window.location.href = "index";
If you want to redirect to sth.com/home
window.location.href = "/home";
and if you want you want to redirect to sth.com/home/index
window.location.href = "/home/index";
There is pretty concise and easy way:
Response.Write("<script>alert('Your text');</script>");
for (x in restaurants) {
if (restaurants[x].restaurant.food == 'chicken') {
return restaurants[x].restaurant.name;
}
}
Use namespace
using System.Collections.Specialized;
Make instance of DataContext
Class
LinqToSqlDataContext dc = new LinqToSqlDataContext();
Use
OrderedDictionary dict = dc.TableName.ToDictionary(d => d.key, d => d.value);
In order to retrieve the values use namespace
using System.Collections;
ICollection keyCollections = dict.Keys;
ICOllection valueCollections = dict.Values;
String[] myKeys = new String[dict.Count];
String[] myValues = new String[dict.Count];
keyCollections.CopyTo(myKeys,0);
valueCollections.CopyTo(myValues,0);
for(int i=0; i<dict.Count; i++)
{
Console.WriteLine("Key: " + myKeys[i] + "Value: " + myValues[i]);
}
Console.ReadKey();
Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...
If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do:
@Component({
selector: 'my-component',
template: 'app-element',
host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}
And if you use a class on the entry tag, Angular will merge the classes, i.e.,
<my-component class="someClass2">
I have both someClass1 & someClass2 applied to me
</my-component>
The other answers were incorrect, at least in my case. request.path
does not provide the full url, only the relative url, e.g. /paper/53
. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path
.
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.
For example:
def run():
print "this does nothing"
def chooser():
return "run"
def main():
'''works just like:
run()'''
eval(chooser())()
The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.
$(this).parent().parent().attr('id');
Is how you would get the id of the parent's parent.
EDIT:
$(this).closest('ul').attr('id');
Is a more foolproof solution for your case.
Check in Jenkins.xml and update like below
<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8090</arguments>
Write this code in the same line, this change the icon color:
<li class="fa fa-id-card-o" style="color:white" aria-hidden="true">
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
That's assuming that SomeClass.prop1
is the desired Key
for the dictionary.
You can simply write:
char c = (char) 2;
or
char c = Convert.ToChar(2);
or more complex option for ASCII encoding only
char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];
$(document).ready(function(){_x000D_
$('input').on("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" />
_x000D_
@Test
public void testSearchManagementStaff() throws SQLException
{
boolean res=true;
ManagementDaoImp mdi=new ManagementDaoImp();
boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
assertEquals(res,b);
}
$hash_type$salt$password
If the hash does not use a salt, then there is no $
sign for that. The actual hash in your case is after the 2nd $
The reason for this is, so you can have many types of hashes with different salts and feeds that string into a function that knows how to match it with some other value.
Found a site on google explaining some changes, according to the author of the page fb does not allow custom buttons. Heres the website.
Unfortunately, it’s against Facebook’s developer policies, which state:
You must not circumvent our intended limitations on core Facebook features.
The Facebook Connect button is intended to be rendered in FBML, which means it’s only meant to look the way Facebook lets it.
Simple solution:
8080
:`sudo lsof -i:8080`
`kill $PID`
PID is got from step 1's output.
This thread seems to answer your question : simultaneous-read-write-a-file
Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.
Here's another way of attaching the event based on W3C DOM Level 2 Events Specification:
transport_select.addEventListener(
'change',
function() { toggleSelect(this.id); },
false
);
ios 7 update
NSString *encode = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString *decode = [encode stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Go to the Xcode Debugging preferences. Make sure that "Load Symbols lazily" is NOT selected.
One more important difference: typedef
s cannot be forward declared. So for the typedef
option you must #include
the file containing the typedef
, meaning everything that #include
s your .h
also includes that file whether it directly needs it or not, and so on. It can definitely impact your build times on larger projects.
Without the typedef
, in some cases you can just add a forward declaration of struct Foo;
at the top of your .h
file, and only #include
the struct definition in your .cpp
file.
If you have newly upgraded your php version you might be forget to restart your webserver service.
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
For the latest Android Studio v2.3.3 (October 11th, 2017) :
1. Click View
on menu bar
2. Click Open Module Settings
3. Open Flavors
tab
4. Choose Min Sdk
version you need
6. Click OK
NamingException's answer worked for me. Except I used
var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()
datepicker
didn't work but dtpicker
did.
in jsp file:
request.getAttribute("javax.servlet.forward.request_uri")
if you load up the XMLDoc I'm pretty sure the .ToString() function posses an overload for this.
But is this for debugging? The reason that it is sent like that is to take up less space (i.e stripping unneccessary whitespace from the XML).
Use this query:
UPDATE `table` SET date_date=now();
Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE `table` SET date_date=now()");
mysql_close($con);
?>
One of the first differences that I can recall from top of my head are multiple domains running in the same server, partial resource retrieval, this allows you to retrieve and speed up the download of a resource (it's what almost every download accelerator does).
If you want to develop an application like a website or similar, you don't need to worry too much about the differences but you should know the difference between GET
and POST
verbs at least.
Now if you want to develop a browser then yes, you will have to know the complete protocol as well as if you are trying to develop a HTTP server.
If you are only interested in knowing the HTTP protocol I would recommend you starting with HTTP/1.1 instead of 1.0.
Try Linq:
Result = string.Join("", input.ToCharArray().Where(x=> ((int)x) < 127));
This will filter out all non ascii characters. Now if you want an equivalent, try the following:
Result = string.Join("", System.Text.Encoding.ASCII.GetChars(System.Text.Encoding.ASCII.GetBytes(input.ToCharArray())));
I use the following rake task to override the Rails drop_database
method.
lib/database.rake
require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
def drop_database(name)
raise "Nah, I won't drop the production database" if Rails.env.production?
execute <<-SQL
UPDATE pg_catalog.pg_database
SET datallowconn=false WHERE datname='#{name}'
SQL
execute <<-SQL
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = '#{name}';
SQL
execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
end
end
end
end
Edit: This is for Postgresql 9.2+
Just type <del>र</del>
in your web page.
In addition to the steps you have already taken, you will need to set the recovery mode to simple before you can shrink the log.
THIS IS NOT A RECOMMENDED PRACTICE for production systems... You will lose your ability to recover to a point in time from previous backups/log files.
See example B on this DBCC SHRINKFILE (Transact-SQL) msdn page for an example, and explanation.
I'm surprised no one mentioned mapping the file into memory: mmap
With this you can access the file as if it were already loaded into memory and the OS will take care of mapping it in and out as possible. Also, if you do this from 2 independent processes and they map the file "shared", they will share the underlying memory.
Once mapped, it will behave like a bytearray. You can use regular expressions, find or any of the other common methods.
Beware that this approach is a little OS specific. It will not be automatically portable.
#ck-button:hover {
background:red;
}
Fiddle: http://jsfiddle.net/zAFND/4/
I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
/// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}
If you are ok to do transformation, you may try this.
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());
#0000ffff
- that is the code that you need for transparent. I just did it and it worked.
The easiest way would be to package the Vagrant box and then copy (e.g. scp
or rsync
) it over to the other PC, add it and vagrant up
;-)
For detailed steps, check this out =>
Is there any way to clone a vagrant box that is already installed
In a node.js server console.log
outputs to the terminal window, not to the browser's console window.
How are you running your server? You should see the output directly after you start it.
There is a simpler way to achieve it,
HTML
<a href="https://getbootstrap.com/" id="fooLinkID" target="_blank">Bootstrap is life !</a>
JavaScript
// Simulating click after 3 seconds
setTimeout(function(){
document.getElementById('fooLinkID').click();
}, 3 * 1000);
Using plain javascript to simulate a click along with addressing the target property.
You can check working example here on jsFiddle.
a.map(e => e)
is another alternative for this job. As of today .map()
is very fast (almost as fast as .slice(0)
) in Firefox, but not in Chrome.
On the other hand, if an array is multi-dimensional, since arrays are objects and objects are reference types, none of the slice or concat methods will be a cure... So one proper way of cloning an array is an invention of Array.prototype.clone()
as follows.
Array.prototype.clone = function(){_x000D_
return this.map(e => Array.isArray(e) ? e.clone() : e);_x000D_
};_x000D_
_x000D_
var arr = [ 1, 2, 3, 4, [ 1, 2, [ 1, 2, 3 ], 4 , 5], 6 ],_x000D_
brr = arr.clone();_x000D_
brr[4][2][1] = "two";_x000D_
console.log(JSON.stringify(arr));_x000D_
console.log(JSON.stringify(brr));
_x000D_
"As of Android 1.6, incoming SMS message broadcasts (android.provider.Telephony.SMS_RECEIVED
) are delivered as an "ordered broadcast" — meaning that you can tell the system which components should receive the broadcast first."
This means that you can intercept incoming message and abort broadcasting of it further on.
In your AndroidManifest.xml
file, make sure to have priority set to highest:
<receiver android:name=".receiver.SMSReceiver" android:enabled="true">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
In your BroadcastReceiver
, in onReceive()
method, before performing anything with your message, simply call abortBroadcast();
EDIT: As of KitKat, this doesn't work anymore apparently.
EDIT2: More info on how to do it on KitKat here:
Delete SMS from android on 4.4.4 (Affected rows = 0(Zero), after deleted)
I agree with Green, Symfony needs namespace, so why not use them ?
This is how an example controller class starts:
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class WelcomeController extends Controller { ... }
I prefer something like the following:
type StringRef []byte
func (s StringRef) String() string {
return string(s[:])
}
…
// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))
For Hp-UX only below command worked for me:
TZ=aaa24 date +%Y%m%d
you can use it as :
ydate=`TZ=aaa24 date +%Y%m%d`
echo $ydate
You may use line-height on div1 as below:
<div id="div1" style="line-height:0px;">
<div></div><div></div><div></div><br/><div></div><div></div><div></div>
</div>
See this: http://jsfiddle.net/wCpU8/
import binascii
binascii.a2b_hex(hex_string)
Thats the way I did it.
All of the aforementioned answers are great... I'm just adding one no one had mentioned yet about persisting data through activities and that is to use the built in android SQLite database to persist relevant data... In fact you can place your databaseHelper in the application state and call it as needed throughout the activates.. Or just make a helper class and make the DB calls when needed... Just adding another layer for you to consider... But all of the other answers would suffice as well.. Really just preference
In case, it helps someone:
Use case: i am using a self-signed certificate for my development on localhost.
Error: Caused by: java.security.cert.CertificateException: No name matching localhost found
Solution: When you generate your self-signed certicate, make sure you answer this question like that(See Bruno's answer for the why):
What is your first and last name?
[Unknown]: localhost
As a bonus, here are my steps:
1. Generate self-signed certificate:
keytool -genkeypair -alias netty -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 4000
Enter keystore password: ***
Re-enter new password: ***
What is your first and last name?
[Unknown]: localhost
...
2. Copy the certificate in src/main/resources(if necessary)
3. Update the cacerts
keytool -v -importkeystore -srckeystore keystore.p12 -srcstoretype pkcs12 -destkeystore "%JAVA_HOME%\jre\lib\security\cacerts" -deststoretype jks
4. Update your config(in my case application.properties):
server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=jumping_monkey
server.ssl.key-store-type=pkcs12
server.ssl.key-alias=netty
Cheers
Adding to kennytm's answer. When you do a shallow copy parent.copy() a new dictionary is created with same keys,but the values are not copied they are referenced.If you add a new value to parent_copy it won't effect parent because parent_copy is a new dictionary not reference.
parent = {1: [1,2,3]}
parent_copy = parent.copy()
parent_reference = parent
print id(parent),id(parent_copy),id(parent_reference)
#140690938288400 140690938290536 140690938288400
print id(parent[1]),id(parent_copy[1]),id(parent_reference[1])
#140690938137128 140690938137128 140690938137128
parent_copy[1].append(4)
parent_copy[2] = ['new']
print parent, parent_copy, parent_reference
#{1: [1, 2, 3, 4]} {1: [1, 2, 3, 4], 2: ['new']} {1: [1, 2, 3, 4]}
The hash(id) value of parent[1], parent_copy[1] are identical which implies [1,2,3] of parent[1] and parent_copy[1] stored at id 140690938288400.
But hash of parent and parent_copy are different which implies They are different dictionaries and parent_copy is a new dictionary having values reference to values of parent
If you want an index, you can use std::find
in combination with std::distance
.
auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
// name not in vector
} else
{
auto index = std::distance(Names.begin(), it);
}
After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.
This caused the app pool to give up and reply with the exception noted in the question.
Somewhere along the way my installshield project had its App pool definition changed to use "3" (probably just a mis-click or mis-type).
You could use a wrapper around the original array (which is IList), like in this (untested) piece of code.
public class SubList<T> : IList<T>
{
#region Fields
private readonly int startIndex;
private readonly int endIndex;
private readonly int count;
private readonly IList<T> source;
#endregion
public SubList(IList<T> source, int startIndex, int count)
{
this.source = source;
this.startIndex = startIndex;
this.count = count;
this.endIndex = this.startIndex + this.count - 1;
}
#region IList<T> Members
public int IndexOf(T item)
{
if (item != null)
{
for (int i = this.startIndex; i <= this.endIndex; i++)
{
if (item.Equals(this.source[i]))
return i;
}
}
else
{
for (int i = this.startIndex; i <= this.endIndex; i++)
{
if (this.source[i] == null)
return i;
}
}
return -1;
}
public void Insert(int index, T item)
{
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
public T this[int index]
{
get
{
if (index >= 0 && index < this.count)
return this.source[index + this.startIndex];
else
throw new IndexOutOfRangeException("index");
}
set
{
if (index >= 0 && index < this.count)
this.source[index + this.startIndex] = value;
else
throw new IndexOutOfRangeException("index");
}
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
public void CopyTo(T[] array, int arrayIndex)
{
for (int i=0; i<this.count; i++)
{
array[arrayIndex + i] = this.source[i + this.startIndex];
}
}
public int Count
{
get { return this.count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(T item)
{
throw new NotSupportedException();
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
for (int i = this.startIndex; i < this.endIndex; i++)
{
yield return this.source[i];
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
Try below code:
alert.setTitle(R.string.WtsOnYourMind);
final EditText input = new EditText(context);
input.setHeight(100);
input.setWidth(340);
input.setGravity(Gravity.LEFT);
input.setImeOptions(EditorInfo.IME_ACTION_DONE);
alert.setView(input);
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
One minor update, you should change the checks for "if errorlevel 1" to the following...
IF %ERRORLEVEL% NEQ 0
This is because on XP you can get negative numbers as errors. 0 = no problems, anything else is a problem.
And keep in mind the way that DOS handles the "IF ERRORLEVEL" tests. It will return true if the number you are checking for is that number or higher so if you are looking for specific error numbers you need to start with 255 and work down.
for python3:
data_set_a = dict_a.items()
data_set_b = dict_b.items()
difference_set = data_set_a ^ data_set_b
I just used the @misir-jafarov and is working now with :
here is my code :
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
jQuery('.art-img img').each(function(){
var t = jQuery(this),
s = 'url(' + t.attr('src') + ')',
p = t.parent(),
d = jQuery('<div></div>');
p.append(d);
d.css({
'height' : t.parent().css('height'),
'background-size' : 'cover',
'background-repeat' : 'no-repeat',
'background-position' : '50% 20%',
'background-image' : s
});
t.hide();
});
}
Hope it helps.
Run
locate pip3
it should give you a list of results like this
/<path>/pip3
/<path>/pip3.x
go to /usr/local/bin to make a symbolic link to where your pip3 is located
ln -s /<path>/pip3.x /usr/local/bin/pip3
Here's a gist which does this: https://gist.github.com/dcollien/312bce1270a5f511bf4a
(an es6 version, and a .js version which can be included in a script tag)
You can use it as follows:
<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
ImageTools.resize(this.files[0], {
width: 320, // maximum width
height: 240 // maximum height
}, function(blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
document.getElementById('preview').src = window.URL.createObjectURL(blob);
// you can also now upload this blob using an XHR.
});
};
</script>
It includes a bunch of support detection and polyfills to make sure it works on as many browsers as I could manage.
(it also ignores gif images - in case they're animated)
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyReflectionClass);
MethodInfo method = type.GetMethod("MyMethod");
MyReflectionClass c = new MyReflectionClass();
string result = (string)method.Invoke(c, null);
Console.WriteLine(result);
}
}
public class MyReflectionClass
{
public string MyMethod()
{
return DateTime.Now.ToString();
}
}
Tested!
In Windows -> control panel -> Region -> Additional Settings -> Time -> Short Time:
Format your time as HH:mm
in the format
hh = 12 hours
HH = 24 hours
mm = minutes
tt = AM or PM
so to get the required result the format should be HH:mm and not hh:mm tt
Update! New & improved! Find plugin @ GitHub!
On another note, while that method is simple, I've created a jQuery plug (found at this jsFiddle, just copy and past code between comment lines) that makes changing the cursor on any element as simple as $("element").cursor("pointer")
.
But that's not all! Act now and you'll get the hand functions position
& ishover
for no extra charge! That's right, 2 very handy cursor functions ... FREE!
They work as simple as seen in the demo:
$("h3").cursor("isHover"); // if hovering over an h3 element, will return true,
// else false
// also handy as
$("h2, h3").cursor("isHover"); // unless your h3 is inside an h2, this will be
// false as it checks to see if cursor is hovered over both elements, not just the last!
// And to make this deal even sweeter - use the following to get a jQuery object
// of ALL elements the cursor is currently hovered over on demand!
$.cursor("isHover");
Also:
$.cursor("position"); // will return the current cursor position as { x: i, y: i }
// at anytime you call it!
Supplies are limited, so Act Now!
I always seem to use svn copy as a server operation so not sure if it works with two working paths.
Here is an example of restoring a deleted file into a local working copy of the project:
svn copy https://repos/project/modules/module.js@3502 modules/module.js
While being inside the project directory. This works as well for restoring entire directories.
This is my method:
def is_square(n) -> bool:
return int(n**0.5)**2 == int(n)
Take square root of number. Convert to integer. Take the square. If the numbers are equal, then it is a perfect square otherwise not.
It is incorrect for a large square such as 152415789666209426002111556165263283035677489.
String path = Server.MapPath("~/MP_Upload/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
In case you need to check against any amount of whitespace, not just single space, you can do this:
To strip string of extra white space (also condences whitespace in the middle to one space):
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
Use --build-arg
with each argument.
If you are passing two argument then add --build-arg
with each argument like:
docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .
It's the same way you run it from command line. Just put that "command line" into a ".bat" file.
So, if you use java -cp .;foo.jar Bar
, put that into a .bat file as
@echo off
java -cp .;foo.jar Bar
Just get rid of the parenthesis and that will give you an array with one element and:
var test = tesst.match(/a(.*)j/);
var test = tesst.match(/a.*j/);
If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis
If you only want the first match found, you might want to use RegExp.exec() instead.
You can use the below code:
RegExp(/a.*j/).exec("afskfsd33j")
In postgresql all foreign keys must reference a unique key in the parent table, so in your bar
table you must have a unique (name)
index.
See also http://www.postgresql.org/docs/9.1/static/ddl-constraints.html#DDL-CONSTRAINTS-FK and specifically:
Finally, we should mention that a foreign key must reference columns that either are a primary key or form a unique constraint.
Emphasis mine.
List<String> al=new ArrayList<string>();
al.add("One");
al.add("Two");
al.add("Three");
for(String al1:al) //for each construct
{
System.out.println(al1);
}
O/p will be
One
Two
Three
For jQuery version < 1.9:
$('#inputId').attr('disabled', true);
For jQuery version >= 1.9:
$('#inputId').prop('disabled', true);
For the given json format as in file ~/my-app/src/db/abc.json:
[
{
"name":"Ankit",
"id":1
},
{
"name":"Aditi",
"id":2
},
{
"name":"Avani",
"id":3
}
]
inorder to import to .js file like ~/my-app/src/app.js:
const json = require("./db/abc.json");
class Arena extends React.Component{
render(){
return(
json.map((user)=>
{
return(
<div>{user.name}</div>
)
}
)
}
);
}
}
export default Arena;
Output:
Ankit Aditi Avani
If you are talking about Python's actual array
(available through import array from array
), then the principle of least astonishment applies and you can check whether it is empty the same way you'd check if a list is empty.
from array import array
an_array = array('i') # an array of ints
if an_array:
print("this won't be printed")
an_array.append(3)
if an_array:
print("this will be printed")
Here's a linearization option on simple data that uses tools from scikit learn.
Given
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer
np.random.seed(123)
# General Functions
def func_exp(x, a, b, c):
"""Return values from a general exponential function."""
return a * np.exp(b * x) + c
def func_log(x, a, b, c):
"""Return values from a general log function."""
return a * np.log(b * x) + c
# Helper
def generate_data(func, *args, jitter=0):
"""Return a tuple of arrays with random data along a general function."""
xs = np.linspace(1, 5, 50)
ys = func(xs, *args)
noise = jitter * np.random.normal(size=len(xs)) + jitter
xs = xs.reshape(-1, 1) # xs[:, np.newaxis]
ys = (ys + noise).reshape(-1, 1)
return xs, ys
transformer = FunctionTransformer(np.log, validate=True)
Code
Fit exponential data
# Data
x_samp, y_samp = generate_data(func_exp, 2.5, 1.2, 0.7, jitter=3)
y_trans = transformer.fit_transform(y_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_samp, y_trans) # 2
model = results.predict
y_fit = model(x_samp)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, np.exp(y_fit), "k--", label="Fit") # 3
plt.title("Exponential Fit")
Fit log data
# Data
x_samp, y_samp = generate_data(func_log, 2.5, 1.2, 0.7, jitter=0.15)
x_trans = transformer.fit_transform(x_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_trans, y_samp) # 2
model = results.predict
y_fit = model(x_trans)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, y_fit, "k--", label="Fit") # 3
plt.title("Logarithmic Fit")
Details
General Steps
x
, y
or both)np.exp()
) and fit to original dataAssuming our data follows an exponential trend, a general equation+ may be:
We can linearize the latter equation (e.g. y = intercept + slope * x) by taking the log:
Given a linearized equation++ and the regression parameters, we could calculate:
A
via intercept (ln(A)
)B
via slope (B
)Summary of Linearization Techniques
Relationship | Example | General Eqn. | Altered Var. | Linearized Eqn.
-------------|------------|----------------------|----------------|------------------------------------------
Linear | x | y = B * x + C | - | y = C + B * x
Logarithmic | log(x) | y = A * log(B*x) + C | log(x) | y = C + A * (log(B) + log(x))
Exponential | 2**x, e**x | y = A * exp(B*x) + C | log(y) | log(y-C) = log(A) + B * x
Power | x**2 | y = B * x**N + C | log(x), log(y) | log(y-C) = log(B) + N * log(x)
+Note: linearizing exponential functions works best when the noise is small and C=0. Use with caution.
++Note: while altering x data helps linearize exponential data, altering y data helps linearize log data.
A simple solution:
<a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>
Or
<script>
/** Change the style **/
function overStyle(object){
object.style.color = 'orange';
// Change some other properties ...
}
/** Restores the style **/
function outStyle(object){
object.style.color = 'orange';
// Restore the rest ...
}
</script>
<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
It's 2018 now, and Python have already evolve to the __future__
long time ago. So how about using the amazing pathlib
coming with Python 3.4 to accomplish the task instead of struggling with os
, os.path
, glob
, shutil
, etc.
So we have 3 paths here (possibly duplicated):
mod_path
: which is the path of the simple helper scriptsrc_path
: which contains a couple of template files waiting to be copied.cwd
: current directory, the destination of those template files.and the problem is: we don't have the full path of src_path
, only know it's relative path to the mod_path
.
Now let's solve this with the the amazing pathlib
:
# Hope you don't be imprisoned by legacy Python code :)
from pathlib import Path
# `cwd`: current directory is straightforward
cwd = Path.cwd()
# `mod_path`: According to the accepted answer and combine with future power
# if we are in the `helper_script.py`
mod_path = Path(__file__).parent
# OR if we are `import helper_script`
mod_path = Path(helper_script.__file__).parent
# `src_path`: with the future power, it's just so straightforward
relative_path_1 = 'same/parent/with/helper/script/'
relative_path_2 = '../../or/any/level/up/'
src_path_1 = (mod_path / relative_path_1).resolve()
src_path_2 = (mod_path / relative_path_2).resolve()
In the future, it just that simple. :D
Moreover, we can select and check and copy/move those template files with pathlib
:
if src_path != cwd:
# When we have different types of files in the `src_path`
for template_path in src_path.glob('*.ini'):
fname = template_path.name
target = cwd / fname
if not target.exists():
# This is the COPY action
with target.open(mode='wb') as fd:
fd.write(template_path.read_bytes())
# If we want MOVE action, we could use:
# template_path.replace(target)
The other answers don't work for me. I'm trying to get the command line working in Jenkins. All you need are the following command line arguments:
--non-interactive
--trust-server-cert
I use a relative path solution,
./../../../../../images/img.png
every ../ will take you one folder up towards the root. Hope this helps..
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
params
is for GET-style URL parameters, data
is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.
Your raw post contains JSON data though. requests
can handle JSON encoding for you, and it'll set the correct Content-Type
header too; all you need to do is pass in the Python object to be encoded as JSON into the json
keyword argument.
You could split out the URL parameters as well:
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
then post your data with:
import requests
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, json=data)
The json
keyword is new in requests
version 2.4.2; if you still have to use an older version, encode the JSON manually using the json
module and post the encoded result as the data
key; you will have to explicitly set the Content-Type header in that case:
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, data=json.dumps(data), headers=headers)
I've tryied all answers of this topic, but just this below worked fine on my project.
Angular 7 and AGM Core 1.0.0-beta.7
<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
<agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
*ngFor="let localizacao of localizacoesTec">
</agm-marker>
</agm-map>
The properties [agmFitBounds]="true"
at agm-marker
and [fitBounds]="true"
at agm-map
does the job
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
E.g.
<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
HttpOnly
cookies.document.cookie
property, which contains a semicolon separated list of name=value
pairs.There is no BI project in Visual Studio. Youll need to download SSDT. SSDT 2017 works fine :)
https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt
To get the ASCII code of a character, you can use the ord()
function.
Here is an example code:
value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)
Output:
Your value here: qwerty
[113, 119, 101, 114, 116, 121]
Here's a Django logging-based solution. It uses the DEBUG setting rather than actually checking whether or not you're running the development server, but if you find a better way to check for that it should be easy to adapt.
LOGGING = {
'version': 1,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/path/to/your/file.log',
'formatter': 'simple'
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
}
}
if DEBUG:
# make all loggers use the console.
for logger in LOGGING['loggers']:
LOGGING['loggers'][logger]['handlers'] = ['console']
see https://docs.djangoproject.com/en/dev/topics/logging/ for details.
The documentation for the parameter spark.files.overwrite
says this: "Whether to overwrite files added through SparkContext.addFile()
when the target file exists and its contents do not match those of the source." So it has no effect on saveAsTextFiles method.
You could do this before saving the file:
val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://localhost:9000"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }
Aas explained here: http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html
For what it's worth I found this issue was happening in a batch import command because of a try/catch loop catching an SQL error (with em->flush()
) that I didn't do anything about. In my case it was because I was trying to insert a record with a non-nullable property left as null.
Typically this would cause a critical exception to happen and the command or controller to halt, but I was just logging this problem instead and carrying on. The SQL error had caused the entity manager to close.
Check your dev.log
file for any silly SQL errors like this as it could be your fault. :)
For those who want to do this in pure javascript, look at:
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
There are two different ways of generating a UUID.
If you just need a unique ID, you want a version 1 or version 4.
Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.
Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.
If you need to always generate the same UUID from a given name, you want a version 3 or version 5.
Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.
Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.
Important things for Java benchmarks are:
System.gc()
between iterations, it's a good idea to run it between tests, so that each test will hopefully get a "clean" memory space to work with. (Yes, gc()
is more of a hint than a guarantee, but it's very likely that it really will garbage collect in my experience.)I'm just in the process of blogging about the design of a benchmarking framework in .NET. I've got a couple of earlier posts which may be able to give you some ideas - not everything will be appropriate, of course, but some of it may be.
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
In all schemas:
=> \dt *.*
In a particular schema:
=> \dt public.*
It is possible to use regular expressions with some restrictions
\dt (public|s).(s|t)
List of relations
Schema | Name | Type | Owner
--------+------+-------+-------
public | s | table | cpn
public | t | table | cpn
s | t | table | cpn
Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for
.
which is taken as a separator as mentioned above,*
which is translated to the regular-expression notation.*
,?
which is translated to.
, and$
which is matched literally. You can emulate these pattern characters at need by writing?
for.
,(R+|)
forR*
, or(R|)
forR?
.$
is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words,$
is automatically appended to your pattern). Write*
at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of\do
).
For numerous reasons, No.
Why is explained in this MSDN post.
First, from a performance perspective the pointers get larger, so data structures get larger, and the processor cache stays the same size. That basically results in a raw speed hit (your mileage may vary). So you start in a hole and you have to dig yourself out of that hole by using the extra memory above 4G to your advantage. In Visual Studio this can happen in some large solutions but I think a preferable thing to do is to just use less memory in the first place. Many of VS’s algorithms are amenable to this. Here’s an old article that discusses the performance issues at some length: https://docs.microsoft.com/archive/blogs/joshwil/should-i-choose-to-take-advantage-of-64-bit
Secondly, from a cost perspective, probably the shortest path to porting Visual Studio to 64 bit is to port most of it to managed code incrementally and then port the rest. The cost of a full port of that much native code is going to be quite high and of course all known extensions would break and we’d basically have to create a 64 bit ecosystem pretty much like you do for drivers. Ouch.
Are you sure you want to use __getattribute__
? What are you actually trying to achieve?
The easiest way to do what you ask is:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
test = 0
or:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
@property
def test(self):
return 0
Edit:
Note that an instance of D
would have different values of test
in each case. In the first case d.test
would be 20, in the second it would be 0. I'll leave it to you to work out why.
Edit2:
Greg pointed out that example 2 will fail because the property is read only and the __init__
method tried to set it to 20. A more complete example for that would be:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
_test = 0
def get_test(self):
return self._test
def set_test(self, value):
self._test = value
test = property(get_test, set_test)
Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.
Actually,
Cursor.Current = Cursors.WaitCursor;
temporarily sets the Wait cursor, but doesn’t ensure that the Wait cursor shows until the end of your operation. Other programs or controls within your program can easily reset the cursor back to the default arrow as in fact happens when you move mouse while operation is still running.
A much better way to show the Wait cursor is to set the UseWaitCursor property in a form to true:
form.UseWaitCursor = true;
This will display wait cursor for all controls on the form until you set this property to false. If you want wait cursor to be shown on Application level you should use:
Application.UseWaitCursor = true;
If you need to parse ASN.1 objects in script, there's a library for that: https://github.com/lapo-luchini/asn1js
For doing the math, I found jsbn convenient: http://www-cs-students.stanford.edu/~tjw/jsbn/
Walking the ASN.1 structure and extracting the exp/mod/subject/etc. is up to you -- I never got that far!
<?php
$val1 = rand(1,4);
$val2=rand(1,4);
if ($pars[$last0] == "reviews" && $pars[$last] > 0) {
echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
<div class="w100">
<div style="background:transparent!important;" class="w100 well" id="postreview">
<?php
$_GET[user_id] = $user[user_id];
$_GET[member_id] = $_COOKIE[userid];
$_GET[subaction] = "savereview";
$_GET[ip] = $_SERVER[REMOTE_ADDR];
$_GET[httpr] = $_ENV[requesturl];
echo form("member_review","",$w[website_id],$w);?>
</div></div>
ive replaced the 'else' with '&&' so both are placed ... argh
You can use python slicing, but note it's not in-place.
In [15]: import pandas as pd
In [16]: import numpy as np
In [17]: df = pd.DataFrame(np.random.random((5,2)))
In [18]: df
Out[18]:
0 1
0 0.294077 0.229471
1 0.949007 0.790340
2 0.039961 0.720277
3 0.401468 0.803777
4 0.539951 0.763267
In [19]: df[3:]
Out[19]:
0 1
3 0.401468 0.803777
4 0.539951 0.763267
Queue
is an interface. You can't instantiate an interface directly except via an anonymous inner class. Typically this isn't what you want to do for a collection. Instead, choose an existing implementation. For example:
Queue<Integer> q = new LinkedList<Integer>();
or
Queue<Integer> q = new ArrayDeque<Integer>();
Typically you pick a collection implementation by the performance and concurrency characteristics you're interested in.
Please try this - Create a directory 'config' in your lumen setup, and then create app.php file inside this 'config' dir. it will look like this -
<?php return ['app.timezone' => 'America/Los_Angeles'];
Then you can access its value anywhere like this -
$value = config('app.timezone');
If it doesn't work, you can add this lines in routes.php
date_default_timezone_set('America/Los_Angeles');
This worked for me!
Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog
class need to override the toString()
method (as mentioned in other answers) from the Object
class to return a valid result.
public class Print {
public static void main(final String[] args) {
List<Dog> list = new ArrayList<Dog>();
Dog e = new Dog("Tommy");
list.add(e);
list.add(new Dog("tiger"));
System.out.println(list);
for(Dog d:list) {
System.out.println(d);
// prints [Tommy, tiger]
}
}
private static class Dog {
private final String name;
public Dog(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
The output of this code is:
[Tommy, tiger]
Tommy
tiger
rt.jar
contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.
For MacOS it is called classes.jar
and located under /System/Library/Frameworks/<java_version>/Classes
. Same not messing with it rule applies there as well :).
http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html
Using the answers already provided, you can roll your own git ignore
command using an alias. Either add this to your ~/.gitconfig file:
ignore = !sh -c 'echo $1 >> .gitignore' -
Or run this command from the (*nix) shell of your choice:
git config --global alias.ignore '!sh -c "echo $1 >> .gitignore" -'
You can likewise create a git exclude
command by replacing ignore
with exclude
and .gitignore
with .git/info/exclude
in the above.
(If you don't already understand the difference between these two files having read the answers here, see this question.)
I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:
split -l 100000 database.sql database-
It will give files like:
database-aaa
database-aab
database-aac
...
How about this:
When the page first loads, do this:
var myTable = document.getElementById("myTable");
myTable.oldHTML=myTable.innerHTML;
Then when you want to clear the table:
myTable.innerHTML=myTable.oldHTML;
The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.
It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.
In the rejection message, Mr van Rossum mentions using return
, which is really sensible and something I need to remember personally. :)
You can use JSON.stringify
like:
JSON.stringify(new_tweets);
To edit bashrc in Ubuntu
$ /usr/bin/vim ~/.bashrc
type PATH=$PATH:$HOME/anaconda3/bin
Press Esc and :wq
to save bashrc file and exit vim
enter image description here
then
$ export PATH=~/anaconda3/bin:$PATH
and type $ source ~/.bashrc
Now to confirm the installation of conda type
$ conda --version
See the documentation events section
Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".
Version 4.0 +
Events are now in format: select2:selecting
(instead of select2-selecting
)
Thanks to snakey for the notification that this has changed as of 4.0
$('#yourselect').on("select2:selecting", function(e) {
// what you would like to happen
});
Version Before 4.0
$('#yourselect').on("select2-selecting", function(e) {
// what you would like to happen
});
Just to clarify, the documentation for select2-selecting
reads:
select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()
whereas change has:
change Fired when selection is changed.
So change
may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.
When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT
variable for you; after all, your script runs in their environment.
Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000
instead of process.env.PORT || 3000
where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.
This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;
app.listen(port);
You need to
set identity_insert YourTable ON
Then delete your row and reinsert it with different identity.
Once you have done the insert don't forget to turn identity_insert off
set identity_insert YourTable OFF
Try the jquery each
function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
If you perhaps also want to eliminate all of the duplicates and keep only a single one of each
Change the formula =COUNTIF(A:A,A2)
to =COUNIF($A$2:A2,A2)
and drag the formula down.
Then autofilter for anything greater than 1 and you can delete them.
just a little hack that works
echo "$(awk '{awk code}' file)" > file
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];
display: inline-block; will prevent break between the words in a list item
li {
display: inline-block;
}
Add below event to DateTimePicker
Private Sub DateTimePicker1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles DateTimePicker1.KeyPress
e.Handled = True
End Sub
If you don't call the favicon, favicon.ico
, you can use that tag to specify the actual path (incase you have it in an images/
directory). The browser/webpage looks for favicon.ico
in the root directory by default.
Noting klaisbyskov's comment about your key length needing to be gigabytes in size, and assuming that you do in fact need this, then I think your only options are:
Hashing comes with the caveat that one day, you might get a collision.
Triggers will scan the entire table.
Over to you...
Possible Permission Issue
I know this post is fairly old, but I ran into a similar issue and my file was spelled correctly.
I originally created the app_offline.htm file in another location and then moved it to the root of my application. Because of my setup I then had a permissions issue.
The website acted as if it was not there. Creating the file within the root directory instead of moving it, fixed my problem. (Or you could just fix the permission in properties->security)
Hope it helps someone.
If you type this command:
echo cd d:/some/path >> ~/.bashrc
Appends the line cd d:/some/path
to .bashrc
. The >>
creates a file if it doesn’t exist and then appends.
One obscure (having just dealt with it), yet possible, cause of this is an internal mod_rewrite rule, in the main config file (not .htaccess) that writes to a path which exists at the root of the server file system. Say you have a /media
directory in your site, and you rewrite something like this:
RewriteRule /some_image.png /media/some_other_location.png
If you have a /media
directory at the root of your server, the rewrite will be attempted to that (resulting in the access denied error) rather than the one in your site directory, since the file system root is checked first by mod_rewrite, for the existence of the first directory in the path, before your site directory.
let startDate = $('[name=daterangepicker_start]').val();
alert(startDate);
FYI : How to download data in CSV from Kibana:
In Kibana--> 1. Go to 'Discover' in left side
Select Index Field (based on your dashboard data) (*** In case if you are not sure which index to select-->go to management tab-->Saved Objects-->Dashboard-->select dashboard name-->scroll down to JSON-->you will see the Index name )
left side you see all the variables available in the data-->click over the variable name that you want to have in csv-->click add-->this variable will be added on the right side of the columns avaliable
Top right section of the kibana-->there is the time filter-->click -->select the duration for which you want the csv
Top upper right -->Reporting-->save this time/variable selection with a new report-->click generate CSV
Go to 'Management' in left side--> 'Reporting'-->download your csv
You might only want to allow cleartext while debugging, but keep the security benefits of rejecting cleartext in production. This is useful for me because I test my app against a development server that does not support https. Here is how to enforce https in production, but allow cleartext in debug mode:
In build.gradle:
// Put this in your buildtypes debug section:
manifestPlaceholders = [usesCleartextTraffic:"true"]
// Put this in your buildtypes release section
manifestPlaceholders = [usesCleartextTraffic:"false"]
In the application tag in AndroidManifest.xml
android:usesCleartextTraffic="${usesCleartextTraffic}"
In my case, I had a mix and match error between projects created in VS2015 and VS2017. In my .vcxproj file, there's this section called PropertyGroup Label="Globals">. I had a section for TargetPlatformVersion=10.0.15063.0. When I removed the TargetPlatformVersion, that solved the problem.
Sorry I can't copy and paste the block here, but stackoverflows coding format did not allow that.
TL;DR
Markdown doesn't support color but you can inline HTML inside Markdown, e.g.:
<span style="color:blue">some *blue* text</span>.
Longer answer
As the original/official syntax rules state (emphasis added):
Markdown’s syntax is intended for one purpose: to be used as a format for writing for the web.
Markdown is not a replacement for HTML, or even close to it. Its syntax is very small, corresponding only to a very small subset of HTML tags. The idea is not to create a syntax that makes it easier to insert HTML tags. In my opinion, HTML tags are already easy to insert. The idea for Markdown is to make it easy to read, write, and edit prose. HTML is a publishing format; Markdown is a writing format. Thus, Markdown’s formatting syntax only addresses issues that can be conveyed in plain text.
For any markup that is not covered by Markdown’s syntax, you simply use HTML itself.
As it is not a "publishing format," providing a way to color your text is out-of-scope for Markdown. That said, it is not impossible as you can include raw HTML (and HTML is a publishing format). For example, the following Markdown text (as suggested by @scoa in a comment):
Some Markdown text with <span style="color:blue">some *blue* text</span>.
Would result in the following HTML:
<p>Some Markdown text with <span style="color:blue">some <em>blue</em> text</span>.</p>
Now, StackOverflow (and probably GitHub) will strip the raw HTML out (as a security measure) so you lose the color here, but it should work on any standard Markdown implementation.
Another possibility is to use the non-standard Attribute Lists originally introduced by the Markuru implementation of Markdown and later adopted by a few others (there may be more, or slightly different implementations of the same idea, like div and span attributes in pandoc). In that case, you could assign a class to a paragraph or inline element, and then use CSS to define a color for a class. However, you absolutely must be using one of the few implementations which actually support the non-standard feature and your documents are no longer portable to other systems.
Here's a rather simple solution:
In the controller we return our errors like this:
if (!ModelState.IsValid)
{
return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
}
Here's some of the client script:
function displayValidationErrors(errors)
{
var $ul = $('div.validation-summary-valid.text-danger > ul');
$ul.empty();
$.each(errors, function (idx, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}
That's how we handle it via ajax:
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var isSuccessful = (data['success']);
if (isSuccessful) {
$('#partial-container-steps').html(data['view']);
initializePage();
}
else {
var errors = data['errors'];
displayValidationErrors(errors);
}
}
});
Also, I render partial views via ajax in the following way:
var view = this.RenderRazorViewToString(partialUrl, viewModel);
return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);
RenderRazorViewToString method:
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
I think several of the answers hit around the possible solution to your problem.
I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the "Home Directory" tab of the site properties window that opens. Select the radio button "A redirection to a URL", enter the url for the new site (http://subdomain.hosttwo.com), and check the checkboxes for "The exact URL entered above", "A permanent redirection for this resource" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.
Or you could create a page on the site of http://subdomain.hostone.com, using one of the following methods (depending on what the hosting platform supports)
PHP Redirect:
<?
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://subdomain.hosttwo.com" );
?>
ASP Redirect:
<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://subdomain.hosttwo.com"
%>
ASP .NET Redirect:
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://subdomain.hosttwo.com");
}
</script>
Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for http://subdomain.hosttwo.com is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click "Properties". On the displayed "Web Site" tab, you should see an "Advanced" button next to the IP address that you'll need to click. On the "Advanced Web Site Identification" window that appears, click "Add". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to http://subdomain.hostone.com, and you'll see the site at http://subdomain.hosttwo.com appear, even though your URL shows http://subdomain.hostone.com
Hope that helps...
Intent myIntent = new Intent(MainActivity.this, Katra_home.class);
startActivity(myIntent);
This Should the perfect one :)
No need for scripts or other 'tricks': openssl
and ssh-keygen
are enough. I'm assuming no password for the keys (which is bad).
All the following methods give an RSA key pair in the same format
With openssl (man genrsa)
openssl genrsa -out dummy-genrsa.pem 2048
In OpenSSL v1.0.1 genrsa
is superseded by genpkey
so this is the new way to do it (man genpkey):
openssl genpkey -algorithm RSA -out dummy-genpkey.pem -pkeyopt rsa_keygen_bits:2048
With ssh-keygen
ssh-keygen -t rsa -b 2048 -f dummy-ssh-keygen.pem -N '' -C "Test Key"
If you have an RSA key pair in DER format, you may want to convert it to PEM to allow the format conversion below:
Generation:
openssl genpkey -algorithm RSA -out genpkey-dummy.cer -outform DER -pkeyopt rsa_keygen_bits:2048
Conversion:
openssl rsa -inform DER -outform PEM -in genpkey-dummy.cer -out dummy-der2pem.pem
in PEM format:
openssl rsa -in dummy-xxx.pem -pubout
in OpenSSH v2 format see:
ssh-keygen -y -f dummy-xxx.pem
OS and software version:
[user@test1 ~]# cat /etc/redhat-release ; uname -a ; openssl version
CentOS release 6.5 (Final)
Linux test1.example.local 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
OpenSSL 1.0.1e-fips 11 Feb 2013
References:
thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D
import java.util.*;
public class HelloWorld {
public static void main(String[] Args) {
Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);
int First = list.get(1);
int Second = list.get(2);
if (First < Second) {
System.out.println("One or more of your items have been restocked. The current stock is: " + First);
Random rn = new Random();
int answer = rn.nextInt(99) + 1;
System.out.println("You are buying " + answer + " New stock");
First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}
}
}
In order to search only in one folder, you have to click on it and press Alt
+ Shift
+ F
.
When you use Ctrl
, VS Code looks in all project.
The non-jQuery vanilla Javascript way, extracted from 12me21's comment:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php");
xhr.onload = function(event){
alert("Success, server responded with: " + event.target.response); // raw response
};
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm"));
xhr.send(formData);
For POST
's the default content type is "application/x-www-form-urlencoded" which matches what we're sending in the above snippet. If you want to send "other stuff" or tweak it somehow see here for some nitty gritty details.
A late but useful answer, PHP has a function specifically for this purpose.
$string = mb_strimwidth($string, 0, 100);
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end
It's an old one but in case someone can benefit from this. You will also get this error if your array is empty.
In my case I had:
$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];
which I changed to:
$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
if(is_array($buyers_array)) {
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];
} else {
echo 'Buyers id ' . $this_buyer_id . ' not found';
}
Yes, you can. Go to Tools > Designers > Table and Designers and uncheck "Prevent Saving Changes That Prevent Table Recreation".
(I know the question is old, but I think this might be good as a reference for people with similar questions)
If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:
If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:
There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject]
or [JsonProperty]
.
There are predefined naming strategies like CamelCaseNamingStrategy
, but you can implement your own ones.
The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization
Since Java 8:
List<String> myList = map.keySet().stream().collect(Collectors.toList());
Update: 04/2018: Note that Vincenty distance is deprecated since GeoPy version 1.13 - you should use geopy.distance.distance() instead!
The answers above are based on the Haversine formula, which assumes the earth is a sphere, which results in errors of up to about 0.5% (according to help(geopy.distance)
). Vincenty distance uses more accurate ellipsoidal models such as WGS-84, and is implemented in geopy. For example,
import geopy.distance
coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
print geopy.distance.vincenty(coords_1, coords_2).km
will print the distance of 279.352901604
kilometers using the default ellipsoid WGS-84. (You can also choose .miles
or one of several other distance units).
Your answer is below the perfect solution to hide to file extension in php.
<?php
$path = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo basename($path, ".php");
?>
You can use the CellMouseEnter and CellMouseLeave to track the row number that the mouse is currently hovering over.
Then use a ContextMenu object to display you popup menu, customised for the current row.
Here's a quick and dirty example of what I mean...
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu m = new ContextMenu();
m.MenuItems.Add(new MenuItem("Cut"));
m.MenuItems.Add(new MenuItem("Copy"));
m.MenuItems.Add(new MenuItem("Paste"));
int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
}
m.Show(dataGridView1, new Point(e.X, e.Y));
}
}
No need to changes anything on DB level, just you have to changes in SQL Query it will work.
Example -
"SELECT * FROM <TABLE> where userId = '" + iv_userId + "' AND password = BINARY '" + iv_password + "'";
Binary keyword will make case sensitive.
This seems to be very easy
>>> from mimetypes import MimeTypes
>>> import urllib
>>> mime = MimeTypes()
>>> url = urllib.pathname2url('Upload.xml')
>>> mime_type = mime.guess_type(url)
>>> print mime_type
('application/xml', None)
Please refer Old Post
Update - In python 3+ version, it's more convenient now:
import mimetypes
print(mimetypes.guess_type("sample.html"))
https://limxtop.blogspot.com/2019/05/app-log.html
Read this article please, where provides complete implement:
setprop log.tag.<YOUR_LOG_TAG> <LEVEL>
in running time.Blending mode used to apply the background tint.
Tint to apply to the background. Must be a color value, in the form of
#rgb
,#argb
,#rrggbb
, or#aarrggbb
.This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
def merge_with(f, xs, ys):
xs = a_copy_of(xs) # dict(xs), maybe generalizable?
for (y, v) in ys.iteritems():
xs[y] = v if y not in xs else f(xs[x], v)
merge_with((lambda x, y: x + y), A, B)
You could easily generalize this:
def merge_dicts(f, *dicts):
result = {}
for d in dicts:
for (k, v) in d.iteritems():
result[k] = v if k not in result else f(result[k], v)
Then it can take any number of dicts.
You can get the actual height of called layout with this code:
public int getLayoutSize() {
// Get the layout id
final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
final AtomicInteger layoutHeight = new AtomicInteger();
root.post(new Runnable() {
public void run() {
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the height of Status Bar
int statusBarHeight = rect.top;
// Get the height occupied by the decoration contents
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
int titleBarHeight = contentViewTop - statusBarHeight;
Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop);
// By now we got the height of titleBar & statusBar
// Now lets get the screen size
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
int screenWidth = metrics.widthPixels;
Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);
// Now calculate the height that our layout can be set
// If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also
layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
Log.i("MY", "Layout Height = " + layoutHeight);
// Lastly, set the height of the layout
FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
rootParams.height = layoutHeight.get();
root.setLayoutParams(rootParams);
}
});
return layoutHeight.get();
}
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);
Update
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences
method of the Context
class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.
(1) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
(2) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE
is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
. In MODE_WORLD_READABLE
other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE
other applications also have write permissions for the created file.
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor
object has to be used. Editor
is a nested interface in the SharedPreference
class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also supports methods like remove()
and clear()
to delete the preference values from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences()
method of the activity. The getPreference
method uses the getSharedPreferences()
method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also the same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference
. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
You can use Aggregate
, to concatenate the strings into a single, character separated string but will throw an Invalid Operation Exception if the collection is empty.
You can use Aggregate
function with a seed string.
var seed = string.Empty;
var seperator = ",";
var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
var carAggregate = cars.Aggregate(seed,
(partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');
you can use string.Join
doesn’t care if you pass it an empty collection.
var seperator = ",";
var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
var carJoin = string.Join(seperator, cars);
If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
I know that is a old question, but...
You can also use this in your class:
@Autowired
private HttpServletRequest context;
And this will provide the current instance of HttpServletRequest
for you use on your method.
I suggest you to update your SDK and start new project and recompile everything you have. It seems you have some inner program errors. Or you are missing package.
And ofc do what Abdijeek said.
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
I spent couple of hours with google and found the answer here
PUT => If user can update all or just a portion of the record, use PUT (user controls what gets updated)
PUT /users/123/email
[email protected]
PATCH => If user can only update a partial record, say just an email address (application controls what can be updated), use PATCH.
PATCH /users/123
[description of changes]
Why Patch
PUT
method need more bandwidth or handle full resources instead on partial. So PATCH
was introduced to reduce the bandwidth.
Explanation about PATCH
PATCH
is a method that is not safe, nor idempotent, and allows full and partial updates and side-effects on other resources.
PATCH
is a method which enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.
PATCH /users/123
[
{ "op": "replace", "path": "/email", "value": "[email protected]" }
]
Here more information about put and patch
Radio buttons are,
<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">
to check on click,
$('.radioButtons').click(function(){
if($("#radio_1")[0].checked){
//logic here
}
});
My suggestion is a variation on Kiran's answer above. I used this in a project.
Swift 5
// convenience property API on my class object to provide access to the my WindowController (MyController).
var myXWindowController: MyController? {
var myWC: MyController?
for viewController in self.windowControllers {
if ((viewController as? MyController) != nil) {
myWC = viewController as? MyController
break
}
}
return myWC
}
// example of use
guard let myController = myXWindowController else {
reportAssertionFailure("Failed to get MyXController from WindowController.")
return
}
{
"preOrderData" : [
{
"pname": "xyz",
"quantity": "1",
"unit": "Peice",
"description": "xyz 100 gram",
"preferred_brand": "xyz",
"entry_date": "2020-10-05 11:11:27",
"creation_date": "2020-10-05 11:11:27",
"updated_date": "2020-10-05 11:11:27",
"user": "[email protected]",
"user_type": "individual"
},
{
"productname": "abc cream",
"quantity": "1",
"unit": "Peice",
"description": "abc 100 gram",
"preferred_brand": "abccream",
"entry_date": "2020-10-05 11:11:27",
"creation_date": "2020-10-05 11:11:27",
"updated_date": "2020-10-05 11:11:27",
"user": "[email protected]",
"user_type": "individual"
}
]
}
I think the result for those two should always be the same. The difference is that you need an instance of the class to use isInstance
but just the Class
object to use isAssignableFrom
.
I was looking through all the wordy explanations so instead turned to a video from University of New South Wales for rescue.Here is the simple explanation: if we have a cell that has address x
and value 7
, the indirect way to ask for address of value 7
is &7
and the indirect way to ask for value at address x
is *x
.So (cell: x , value: 7) == (cell: &7 , value: *x)
.Another way to look into it: John
sits at 7th seat
.The *7th seat
will point to John
and &John
will give address
/location of the 7th seat
. This simple explanation helped me and hope it will help others as well. Here is the link for the excellent video: click here.
Here is another example:
#include <stdio.h>
int main()
{
int x; /* A normal integer*/
int *p; /* A pointer to an integer ("*p" is an integer, so p
must be a pointer to an integer) */
p = &x; /* Read it, "assign the address of x to p" */
scanf( "%d", &x ); /* Put a value in x, we could also use p here */
printf( "%d\n", *p ); /* Note the use of the * to get the value */
getchar();
}
Add-on: Always initialize pointer before using them.If not, the pointer will point to anything, which might result in crashing the program because the operating system will prevent you from accessing the memory it knows you don't own.But simply putting p = &x;
, we are assigning the pointer a specific location.
I just had the same problem trying to get Spyder to run in Virtual Environment.
The solution is simple:
Activate your virtual environment.
Then pip install Spyder and its dependencies (PyQt5) in your virtual environment.
Then launch Spyder3 from your virtual environment CLI.
It works fine for me now.
Another thing to check is whether you have Windows Firewall enabled, since that might be blocking port 42424.
No. Not necessarily.
If you need to place a DIV within a TD, be sure you're using the TD properly. If you don't care about tabular-data, and semantics, then you ultimately won't care about DIVs in TDs. I don't think there's a problem though - if you have to do it, you're fine.
According to the HTML Specification
A <div>
can be placed where flow content is expected1, which is the <td>
content model2.
You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.
You have extra spaces after END;
that cause the heredoc not terminated.
Try this: org.apache.commons.math3.util.Precision.round(double x, int scale)
See: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html
Apache Commons Mathematics Library homepage is: http://commons.apache.org/proper/commons-math/index.html
The internal implemetation of this method is:
public static double round(double x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}
public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
Do you mean something like this? JSFiddle
Attribute used:
margin-left: 50px;