Telerik Fiddler is a good choice
http://www.telerik.com/blogs/using-fiddler-with-apple-ios-devices
Try using a single quote instead of double quotes along with -g
Following scenario worked for me
curl -g -d '{"collection":[{"NumberOfParcels":1,"Weight":1,"Length":1,"Width":1,"Height":1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST https://yoururl.com
WITH
curl -g -d "{'collection':[{'NumberOfParcels':1,'Weight':1,'Length':1,'Width':1,'Height':1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST https://yoururl.com
This especially resolved my error curl command error : bad url colon is first character
Instead of setting up a scope variable to indicate data loading status, it is better to have a directive does everything for you:
angular.module('directive.loading', [])
.directive('loading', ['$http' ,function ($http)
{
return {
restrict: 'A',
link: function (scope, elm, attrs)
{
scope.isLoading = function () {
return $http.pendingRequests.length > 0;
};
scope.$watch(scope.isLoading, function (v)
{
if(v){
elm.show();
}else{
elm.hide();
}
});
}
};
}]);
With this directive, all you need to do is to give any loading animation element an 'loading' attribute:
<div class="loading-spiner-holder" data-loading ><div class="loading-spiner"><img src="..." /></div></div>
You can have multiple loading spinners on the page. where and how to layout those spinners is up to you and directive will simply turn it on/off for you automatically.
Lots of outdated answers to this question. As of Swift 2+ the Swift Standard Library contains the readline() function. It will return an Optional but it will only be nil if EOF has been reached, which will not happen when getting input from the keyboard so it can safely be unwrapped by force in those scenarios. If the user does not enter anything its (unwrapped) value will be an empty string. Here's a small utility function that uses recursion to prompt the user until at least one character has been entered:
func prompt(message: String) -> String {
print(message)
let input: String = readLine()!
if input == "" {
return prompt(message: message)
} else {
return input
}
}
let input = prompt(message: "Enter something!")
print("You entered \(input)")
Note that using optional binding (if let input = readLine()) to check if something was entered as proposed in other answers will not have the desired effect, as it will never be nil and at least "" when accepting keyboard input.
This will not work in a Playground or any other environment where you does not have access to the command prompt. It seems to have issues in the command-line REPL as well.
Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:
registered(X, Y) :-
X = ct101; X = ct102; X = ct103.
For a fuller explanation:
I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important
(to override the default style on bootstrap.css).
Example code
.nav {_x000D_
background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
background-color: #666 !important;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
<!-- Nav tabs -->_x000D_
<ul class="nav nav-tabs" role="tablist">_x000D_
<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
<li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
<li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
</ul>_x000D_
_x000D_
<!-- Tab panes -->_x000D_
<div class="tab-content">_x000D_
<div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
<div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
<div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
<div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/zjjpocv6/2/
For those still looking how to get GatesDa's answer to work: You can just reference the case object after declaring it to instantiate it:
trait Enum[A] {
trait Value { self: A =>
_values :+= this
}
private var _values = List.empty[A]
def values = _values
}
sealed trait Currency extends Currency.Value
object Currency extends Enum[Currency] {
case object EUR extends Currency;
EUR //THIS IS ONLY CHANGE
case object GBP extends Currency; GBP //Inline looks better
}
Instead of using position: absolute
, text-indent
can be used to solve the "inside" problem:
li {
list-style: inherit;
margin: 0 0 4px 9px;
text-indent: -9px;
}
li:before {
content: "· ";
}
I know I'm late to the party, but I needed something similar that the above answers didn't help.
I was using Angular's $watch function to detect changes in a variable. Not only did I need to know whether a property had changed on the variable, but I also wanted to make sure that the property that changed was not a temporary, calculated field. In other words, I wanted to ignore certain properties.
Here's the code: https://jsfiddle.net/rv01x6jo/
Here's how to use it:
// To only return the difference
var difference = diff(newValue, oldValue);
// To exclude certain properties
var difference = diff(newValue, oldValue, [newValue.prop1, newValue.prop2, newValue.prop3]);
Hope this helps someone.
You may try removing the table from the model and adding it again. You can do this visually by opening the .edmx file from the Solution Explorer.
Steps:
If your private method is not tested by calling your public methods then what is it doing? I'm talking private not protected or friend.
find /the_path_you_want_to_find -name index.html
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
Configuration on Ubuntu 20.04 - apache 2.4.41:
Enable the headers module
$ sudo a2enmod headers
Edit file /etc/apache2/conf-available/security.conf
and add:
Header always set X-Content-Type-Options: nosniff
Restart Apache
$ sudo systemctl restart apache2
$ culr -I localhost
HTTP/1.1 200 OK
Date: Fri, 23 Oct 2020 06:12:16 GMT
Server:
X-Content-Type-Options: nosniff
Last-Modified: Thu, 22 Oct 2020 08:06:06 GMT
You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.
Instead of using properties file, use XML file.
If the data is too small, you can even use web.xml for accessing the properties.
Please note that any of these approach will require app server restart for changes to be reflected.
I just wanted to give an alternative way to split a string with multiple delimiters, in case you are using a SQL Server version under 2016.
The general idea is to split out all of the characters in the string, determine the position of the delimiters, then obtain substrings relative to the delimiters. Here is a sample:
-- Sample data
DECLARE @testTable TABLE (
TestString VARCHAR(50)
)
INSERT INTO @testTable VALUES
('Teststring,1,2,3')
,('Test')
DECLARE @delimiter VARCHAR(1) = ','
-- Generate numbers with which we can enumerate
;WITH Numbers AS (
SELECT 1 AS N
UNION ALL
SELECT N + 1
FROM Numbers
WHERE N < 255
),
-- Enumerate letters in the string and select only the delimiters
Letters AS (
SELECT n.N
, SUBSTRING(t.TestString, n.N, 1) AS Letter
, t.TestString
, ROW_NUMBER() OVER ( PARTITION BY t.TestString
ORDER BY n.N
) AS Delimiter_Number
FROM Numbers n
INNER JOIN @testTable t
ON n <= LEN(t.TestString)
WHERE SUBSTRING(t.TestString, n, 1) = @delimiter
UNION
-- Include 0th position to "delimit" the start of the string
SELECT 0
, NULL
, t.TestString
, 0
FROM @testTable t
)
-- Obtain substrings based on delimiter positions
SELECT t.TestString
, ds.Delimiter_Number + 1 AS Position
, SUBSTRING(t.TestString, ds.N + 1, ISNULL(de.N, LEN(t.TestString) + 1) - ds.N - 1) AS Delimited_Substring
FROM @testTable t
LEFT JOIN Letters ds
ON t.TestString = ds.TestString
LEFT JOIN Letters de
ON t.TestString = de.TestString
AND ds.Delimiter_Number + 1 = de.Delimiter_Number
OPTION (MAXRECURSION 0)
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
//JAVA
public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
final int RADIUS_EARTH = 6371;
double dLat = getRad(latitude2 - latitude1);
double dLong = getRad(longitude2 - longitude1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (RADIUS_EARTH * c) * 1000;
}
private Double getRad(Double x) {
return x * Math.PI / 180;
}
The conversion you need requires the offset from UTC/Greewich, or a time-zone.
If you have an offset, there is a dedicated method on LocalDateTime
for this task:
long epochSec = localDateTime.toEpochSecond(zoneOffset);
If you only have a ZoneId
then you can obtain the ZoneOffset
from the ZoneId
:
ZoneOffset zoneOffset = ZoneId.of("Europe/Oslo").getRules().getOffset(ldt);
But you may find conversion via ZonedDateTime
simpler:
long epochSec = ldt.atZone(zoneId).toEpochSecond();
I would suggest concat when dealing with 2 strings, and || when those strings are more than 2:
select concat(a,b)
from dual
or
select 'a'||'b'||'c'||'d'
from dual
Swift 3.0 Version
if you want to present new controller.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.present(viewController, animated: true, completion: nil)
and if you want to push to another controller (if it is in navigation)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.navigationController?.pushViewController(viewController, animated: true)
It's something to do with v5, some of the icons don't work with older versions.
This link worked for me!
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype
Therefore you need only query for NOT TRUE:
SELECT * from table_name WHERE boolean_column IS NOT TRUE;
You can use the .Clear method:
Sheets("Zeros").UsedRange.Clear
Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.
It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:
public class ImageHandler : IHttpHandler
{
byte[] bytes;
public void ProcessRequest(HttpContext context)
{
int param;
if (int.TryParse(context.Request.QueryString["id"], out param))
{
using (var db = new MusicLibContext())
{
if (param == -1)
{
bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));
context.Response.ContentType = "image/png";
}
else
{
var data = (from x in db.Images
where x.ImageID == (short)param
select x).FirstOrDefault();
bytes = data.ImageData;
context.Response.ContentType = "image/" + data.ImageFileType;
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
else
{
//image not found
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
In the view, i added the ID of the photo to the query string of the handler.
I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton
. The second line can be modified to get the value of as many cells as you wish.
Here is my solution:
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();
In Spring MVC, all incoming requests go through a single servlet. This servlet - DispatcherServlet
- is the front controller. Front controller is a typical design pattern in the web applications development. In this case, a single servlet receives all requests and transfers them to all other components of the application.
The task of the DispatcherServlet
is to send request to the specific Spring MVC controller.
Usually we have a lot of controllers and DispatcherServlet
refers to one of the following mappers in order to determine the target controller:
BeanNameUrlHandlerMapping
;ControllerBeanNameHandlerMapping
;ControllerClassNameHandlerMapping
;DefaultAnnotationHandlerMapping
;SimpleUrlHandlerMapping
.If no configuration is performed, the DispatcherServlet
uses BeanNameUrlHandlerMapping
and DefaultAnnotationHandlerMapping
by default.
When the target controller is identified, the DispatcherServlet
sends request to it. The controller performs some work according to the request
(or delegate it to the other objects), and returns back to the DispatcherServlet
with the Model and the name of the View.
The name of the View is only a logical name. This logical name is then used to search for the actual View (to avoid coupling with the controller and specific View). Then DispatcherServlet
refers to the ViewResolver
and maps the logical name of the View to the specific implementation of the View.
Some possible Implementations of the ViewResolver
are:
BeanNameViewResolver
;ContentNegotiatingViewResolver
;FreeMarkerViewResolver
;InternalResourceViewResolver
;JasperReportsViewResolver
;ResourceBundleViewResolver
;TilesViewResolver
;UrlBasedViewResolver
;VelocityLayoutViewResolver
;VelocityViewResolver
;XmlViewResolver
;XsltViewResolver
.When the DispatcherServlet
determines the view that will display the results it will be rendered as the response.
Finally, the DispatcherServlet
returns the Response
object back to the client.
This worked for me, source: here
I had this error and it wasn't related with the DB constrains (at least in my case). I have an .xsd file with a GetRecord query that returns a group of records. One of the columns of that table was "nvarchar(512)" and in the middle of the project I needed to changed it to "nvarchar(MAX)".
Everything worked fine until the user entered more than 512 on that field and we begin to get the famous error message "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."
Solution: Check all the MaxLength property of the columns in your DataTable.
The column that I changed from "nvarchar(512)" to "nvarchar(MAX)" still had the 512 value on the MaxLength property so I changed to "-1" and it works!!.
go to that path "C:\Program Files (x86)\JetBrains\IntelliJ IDEA 12.1.4\bin\idea.exe.vmoptions" and change size to -Xmx512m
-Xms128m
-Xmx512m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
hope its will work
For from / to date, here is how I implemented restricting the dates based on the date entered in the other datepicker. Works pretty good:
function activateDatePickers() {
$("#aDateFrom").datepicker({
onClose: function() {
$("#aDateTo").datepicker(
"change",
{ minDate: new Date($('#aDateFrom').val()) }
);
}
});
$("#aDateTo").datepicker({
onClose: function() {
$("#aDateFrom").datepicker(
"change",
{ maxDate: new Date($('#aDateTo').val()) }
);
}
});
}
Quite simple actually:
mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");
The %
is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.
It is not good to manipulate with DOM (including checking of attributes) in any place except directives. You can add into scope some value indicating if link should be disabled.
But other problem is that ngDisabled does not work on anything except form controls, so you can't use it with <a>, but you can use it with <button> and style it as link.
Another way is to use lazy evaluation of expressions like isDisabled || action()
so action wouold not be called if isDisabled
is true.
Here goes both solutions: http://plnkr.co/edit/5d5R5KfD4PCE8vS3OSSx?p=preview
One can ask with some Java code:
long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + "M");
See javadoc.
The easiest option is to make use of the Excel copy/paste.
Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub
When you are not sure of the number of rows, then you can do it this way:
followers_df.index = range(len(followers_df))
My descriptions for the three:
position: absolute
descendents)position: absolute
ones) without scrolling.Then there is also:
According to this article on the w3c website:
CDATA is a sequence of characters from the document character set and may include character entities. User agents should interpret attribute values as follows:
- Replace character entities with characters,
- Ignore line feeds,
- Replace each carriage return or tab with a single space.
This means that (at least) CR and LF won't work inside title attribute. I suggest that you use a tooltip plugin. Most of these plugins allow arbitrary HTML to be displayed as an element's tooltip.
You don't say if the tree you want to kill is a single process group. (This is often the case if the tree is the result of forking from a server start or a shell command line.) You can discover process groups using GNU ps as follows:
ps x -o "%p %r %y %x %c "
If it is a process group you want to kill, just use the kill(1)
command but instead of giving it a process number, give it the negation of the group number. For example to kill every process in group 5112, use kill -TERM -- -5112
.
There are many elegant and efficient answers here. But the conciseness can make us lose some useful information. In particular, one often does not want to consider a connection error an Exception, and one might want to treat differently some kind of network-related errors - for example, to decide if we should retry the download.
Here's a method that does not throw Exceptions for network errors (only for truly exceptional problems, as malformed url or problems writing to the file)
/**
* Downloads from a (http/https) URL and saves to a file.
* Does not consider a connection error an Exception. Instead it returns:
*
* 0=ok
* 1=connection interrupted, timeout (but something was read)
* 2=not found (FileNotFoundException) (404)
* 3=server error (500...)
* 4=could not connect: connection timeout (no internet?) java.net.SocketTimeoutException
* 5=could not connect: (server down?) java.net.ConnectException
* 6=could not resolve host (bad host, or no internet - no dns)
*
* @param file File to write. Parent directory will be created if necessary
* @param url http/https url to connect
* @param secsConnectTimeout Seconds to wait for connection establishment
* @param secsReadTimeout Read timeout in seconds - trasmission will abort if it freezes more than this
* @return See above
* @throws IOException Only if URL is malformed or if could not create the file
*/
public static int saveUrl(final Path file, final URL url,
int secsConnectTimeout, int secsReadTimeout) throws IOException {
Files.createDirectories(file.getParent()); // make sure parent dir exists , this can throw exception
URLConnection conn = url.openConnection(); // can throw exception if bad url
if( secsConnectTimeout > 0 ) conn.setConnectTimeout(secsConnectTimeout * 1000);
if( secsReadTimeout > 0 ) conn.setReadTimeout(secsReadTimeout * 1000);
int ret = 0;
boolean somethingRead = false;
try (InputStream is = conn.getInputStream()) {
try (BufferedInputStream in = new BufferedInputStream(is); OutputStream fout = Files
.newOutputStream(file)) {
final byte data[] = new byte[8192];
int count;
while((count = in.read(data)) > 0) {
somethingRead = true;
fout.write(data, 0, count);
}
}
} catch(java.io.IOException e) {
int httpcode = 999;
try {
httpcode = ((HttpURLConnection) conn).getResponseCode();
} catch(Exception ee) {}
if( somethingRead && e instanceof java.net.SocketTimeoutException ) ret = 1;
else if( e instanceof FileNotFoundException && httpcode >= 400 && httpcode < 500 ) ret = 2;
else if( httpcode >= 400 && httpcode < 600 ) ret = 3;
else if( e instanceof java.net.SocketTimeoutException ) ret = 4;
else if( e instanceof java.net.ConnectException ) ret = 5;
else if( e instanceof java.net.UnknownHostException ) ret = 6;
else throw e;
}
return ret;
}
To save you some time here is the answer from a link in a previous answer at https://forums.asp.net/t/1448398.aspx
ActionResult is an abstract class, and it's base class for ViewResult class.
In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.
And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.
It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.
I've tried many solutions and came up with this.
Options and selections of the dropdown are cleared using this only
$("#my-multi option:selected").prop("selected", false);
$("#my-multi option").remove();
But the interface is not updated. So you have to do this
$('#my-multi').multiselect('rebuild');
Hence, the final code is
$("#my-multi option:selected").prop("selected", false);
$("#my-multi option").remove();
$('#my-multi').multiselect('rebuild');
Suggestions and improvements are welcome.
I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.
There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.
I know this question is a little old but here is my solution.
// HTML
// <input type="checkbox" onClick="setcb1()"/>
// <input type="checkbox" onClick="setcb2()"/>
// cb1 = checkbox 1
// cb2 = checkbox 2
var cb1 = getId('cb1'),
cb2 = getId('cb2');
function getId(id) {
return document.getElementById(id);
}
function setcb1() {
if(cb1.checked === true) {
cb2.checked = false;
cb2.disabled = "disabled"; // You have to disable the unselected checkbox
} else if(cb1.checked === false) {
cb2.disabled = ""; // Then enable it if there isn't one selected.
}
}
function setcb2() {
if(cb2.checked === true) {
cb1.checked = false;
cb1.disabled = "disabled"
} else if(cb2.checked === false) {
cb1.disabled = ""
}
Hope this helps!
It is not possible without using a TLD list to compare with as their exist many cases like http://www.db.de/ or http://bbc.co.uk/ that will be interpreted by a regex as the domains db.de
(correct) and co.uk
(wrong).
But even with that you won't have success if your list does not contain SLDs, too. URLs like http://big.uk.com/ and http://www.uk.com/ would be both interpreted as uk.com
(the first domain is big.uk.com).
Because of that all browsers use Mozilla's Public Suffix List:
https://en.wikipedia.org/wiki/Public_Suffix_List
You can use it in your code by importing it through this URL:
http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1
Feel free to extend my function to extract the domain name, only. It won't use regex and it is fast:
http://www.programmierer-forum.de/domainnamen-ermitteln-t244185.htm#3471878
Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:
data.busNum = 12345;
...
myFunction(
contextParamers : {
param1: any,
param2: string
param3: string
}){
contextParamers.param1 = contextParamers.param1+ 'canChange';
//contextParamers.param4 = "CannotChange";
var contextParamers2 : any = contextParamers;// lost the typescript on the new object of type any
contextParamers2.param4 = 'canChange';
return contextParamers2;
}
I've discovered a better alternative solution then the other complex solutions.
brew install https://raw.github.com/Homebrew/homebrew-versions/master/postgresql8.rb
This will download and install PostgreSQL 8.4.8
I found this solution by starting to follow the steps of searching the repo and a comment in the repo .
After a little research found that someone has a collection of rare formulars to brew up with.
If your looking for MySQL 5.1.x, give this a try.
brew install https://raw.github.com/Homebrew/homebrew-versions/master/mysql51.rb
It seems that the idiomatic way to do this is to provide a close()
method (or similar), and call it explicitely.
ALTER won't do it because column order does not matter for storage or querying
If SQL Server, you'd have to use the SSMS Table Designer to arrange your columns, which can then generate a script which drops and recreates the table
Edit Jun 2013
Cross link to my answer here: Performance / Space implications when ordering SQL Server columns?
As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:
There is one and only one instance of NoneType i.e. None is a singleton. Consequently foo == None
and foo is None
mean the same. However the is
test is faster and the Pythonic convention is to use foo is None
.
If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for foo
is bar
.
True and False are also (now) singletons, but there is no use-case for foo == True
and no use case for foo is True
.
You can use the below change event to which will trigger when the combobox value will change.
Private Sub ComboBox1_Change()
'your code here
End Sub
Also you can get the selected value using below
ComboBox1.Value
I am attaching the code below! This quicksort is a great learning tool because of the Location of the pivot value. Since it is in a constant place, you can walk through it multiple times and really get a hang of how it all works. In practice it is best to randomize the pivot to avoid O(N^2) runtime.
def quicksort10(alist):
quicksort_helper10(alist, 0, len(alist)-1)
def quicksort_helper10(alist, first, last):
""" """
if first < last:
split_point = partition10(alist, first, last)
quicksort_helper10(alist, first, split_point - 1)
quicksort_helper10(alist, split_point + 1, last)
def partition10(alist, first, last):
done = False
pivot_value = alist[first]
leftmark = first + 1
rightmark = last
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivot_value:
leftmark = leftmark + 1
while leftmark <= rightmark and alist[rightmark] >= pivot_value:
rightmark = rightmark - 1
if leftmark > rightmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
If you are using wamp server , then i recommend you to use xampp server . you . i get this error in less than i minute but i resolved this by using (isset) function . and i get no error . and after that i remove (isset) function and i don,t see any error.
by the way i am using xampp server
In SQL
, the order of the output is not defined unless you specify it in the ORDER BY
clause.
Try this:
SELECT *
FROM one
JOIN two
ON one.one_name = two.one_name
ORDER BY
one.id
Using the Python boto3 SDK (and assuming credentials are setup for AWS), the following will delete a specified object in a bucket:
import boto3
client = boto3.client('s3')
client.delete_object(Bucket='mybucketname', Key='myfile.whatever')
I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)
<meta name="304workaround" content="2013-10-24 21:17:23">
Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...
Another example of a weird problem and its solution:
This:
target_link_libraries(
${PROJECT_NAME}
${Poco_LIBRARIES}
${Poco_Foundation_LIBRARY}
${Poco_Net_LIBRARY}
${Poco_Util_LIBRARY}
)
gives: make[3]: *** No rule to make target '/usr/lib/libPocoFoundationd.so', needed by '../hello_poco/bin/mac/HelloPoco'. Stop.
But if I remove Poco_LIBRARIES
it works:
target_link_libraries(
${PROJECT_NAME}
${Poco_Foundation_LIBRARY}
${Poco_Net_LIBRARY}
${Poco_Util_LIBRARY}
)
I'm using clang8 on Mac and clang 3.9 on Linux The problem only occurs on Linux but works on Mac!
I forgot to mention: Poco_LIBRARIES
was wrong - it was not set by cmake/find_package!
My code to convert array to Json
Code
List<String>a = new ArrayList<String>();
a.add("so 1");
a.add("so 2");
a.add("so 3");
JSONArray jray = new JSONArray(a);
System.out.println(jray.toString());
output
["so 1","so 2","so 3"]
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
I think you want this syntax:
ALTER TABLE tb_TableName
add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. If that is the case, then you should run an UPDATE
first. Your script will be:
update tb_TableName
set Record_Status = ''
where Record_Status is null
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
What is the truth?
Microsoft's documentation describing the behaviour of their browser is correct.
Is there any solution to hide the addressbar?
No. If you could hide it, then you could use HTML/CSS to make something that looked like a common address bar. You could then put a different address in it. You could then trick people into thinking they were on a different site and entering their password for it.
It is impossible to conceal the user's location from them because it is essential for security that they know what their location is.
To store DataTable
in Session:
DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest;
To retrieve DataTable
from Session:
DataTable dt = (DataTable) Session["dtTest"];
I figured it out, and it's actually pretty straight forward.
Set your variable:
$image1 = "img/products/image1.jpg";
Then ceate a cell, position it, then rather than setting where the image is, use the variable you created above with the following:
$this->Cell( 40, 40, $pdf->Image($image1, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'L', false );
Now the cell will move up and down with content if other cells around it move.
Hope this helps others in the same boat.
Android has build-in patterns for email, phone number, etc, that you can use if you are building for Android API level 8 and above.
private boolean isValidEmail(CharSequence email) {
if (!TextUtils.isEmpty(email)) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
return false;
}
private boolean isValidPhoneNumber(CharSequence phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
return Patterns.PHONE.matcher(phoneNumber).matches();
}
return false;
}
Important Update:
HttpModule
and Http
from @angular/http
has been deprecated since Angular V5, should of using HttpClientModule
and HttpClient
from @angular/common/http
instead, refer CHANGELOG.
For Angular version previous from **@4.3.0, You should inject Http
from @angular/http
, and HttpModule
is for importing at your NgModule's import array.
import {HttpModule} from '@angular/http';
@NgModule({
...
imports: [HttpModule]
})
Inject http
at component or service
import { Http } from '@angular/http';
constructor(private http: Http) {}
For Angular version after(include) 4.3.0, you can use HttpClient
from @angular/common/http
instead of Http
from @angular/http
. Don't forget to import HttpClientModule
at your NgModule
's import array first.
Refer @echonax's answer.
A) What do I not understand about how the Google Apps Script console works with respect to printing so that I can see if my code is accomplishing what I'd like?
The code on .gs files of a Google Apps Script project run on the server rather than on the web browser. The way to log messages was to use the Class Logger.
B) Is it a problem with the code?
As the error message said, the problem was that console
was not defined but nowadays the same code will throw other error:
ReferenceError: "playerArray" is not defined. (line 12, file "Code")
That is because the playerArray is defined as local variable. Moving the line out of the function will solve this.
var playerArray = [];
function addplayerstoArray(numplayers) {
for (i=0; i<numplayers; i++) {
playerArray.push(i);
}
}
addplayerstoArray(7);
console.log(playerArray[3])
Now that the code executes without throwing errors, instead to look at the browser console we should look at the Stackdriver Logging. From the Google Apps Script editor UI click on View > Stackdriver Logging.
On 2017 Google released to all scripts Stackdriver Logging and added the Class Console, so including something like console.log('Hello world!')
will not throw an error but the log will be on Google Cloud Platform Stackdriver Logging Service instead of the browser console.
From Google Apps Script Release Notes 2017
June 23, 2017
Stackdriver Logging has been moved out of Early Access. All scripts now have access to Stackdriver logging.
From Logging > Stackdriver logging
The following example shows how to use the console service to log information in Stackdriver.
function measuringExecutionTime() { // A simple INFO log message, using sprintf() formatting. console.info('Timing the %s function (%d arguments)', 'myFunction', 1); // Log a JSON object at a DEBUG level. The log is labeled // with the message string in the log viewer, and the JSON content // is displayed in the expanded log structure under "structPayload". var parameters = { isValid: true, content: 'some string', timestamp: new Date() }; console.log({message: 'Function Input', initialData: parameters}); var label = 'myFunction() time'; // Labels the timing log entry. console.time(label); // Starts the timer. try { myFunction(parameters); // Function to time. } catch (e) { // Logs an ERROR message. console.error('myFunction() yielded an error: ' + e); } console.timeEnd(label); // Stops the timer, logs execution duration. }
I had this problem as well and only really started to hone in on the root cause after opening up the browser's web console. Until that, I was unable to get any error messages (even with <p:messages>
). The web console showed an HTTP 405 status code coming back from the <h:commandButton type="submit" action="#{myBean.submit}">
.
In my case, I have a mix of vanilla HttpServlet's providing OAuth authentication via Auth0 and JSF facelets and beans carrying out my application views and business logic.
Once I refactored my web.xml, and removed a middle-man-servlet, it then "magically" worked.
Bottom line, the problem was that the middle-man-servlet was using RequestDispatcher.forward(...) to redirect from the HttpServlet environment to the JSF environment whereas the servlet being called prior to it was redirecting with HttpServletResponse.sendRedirect(...).
Basically, using sendRedirect() allowed the JSF "container" to take control whereas RequestDispatcher.forward() was obviously not.
What I don't know is why the facelet was able to access the bean properties but could not set them, and this clearly screams for doing away with the mix of servlets and JSF, but I hope this helps someone avoid many hours of head-to-table-banging.
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"
I think this is bit round-about explanation but still it clarifies using real life example.
Small Example:
Let's say playing an audio involves three steps:
If your audio player does step 1,2,3 sequentially for every song then it is synchronous. You will have to wait for some time to hear the song till the song actually gets fetched and decompressed.
If your audio player does step 1,2,3 independent of each other, then it is asynchronous. ie. While playing audio 1 ( step 3), if it fetches audio 3 from harddisk in parallel (step 1) and it decompresses the audio 2 in parallel. (step 2 ) You will end up in hearing the song without waiting much for fetch and decompress.
I am joining the choir recommending that you skip the now long outdated classes Date
, Calendar
, SimpleDateFormat
and friends. In particular I would warn against using the deprecated methods and constructors of the Date
class, like the Date(String)
constructor you used. They were deprecated because they don’t work reliably across time zones, so don’t use them. And yes, most of the constructors and methods of that class are deprecated.
While at the time you asked the question, Joda-Time was (from all I know) a clearly better alternative, time has moved on again. Today Joda-Time is a largely finished project, and its developers recommend you use java.time
, the modern Java date and time API, instead. I will show you how.
ZonedDateTime localTime = ZonedDateTime.now(ZoneId.systemDefault());
// Convert Local Time to UTC
OffsetDateTime gmtTime
= localTime.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("Local:" + localTime.toString()
+ " --> UTC time:" + gmtTime.toString());
// Reverse Convert UTC Time to Local time
localTime = gmtTime.atZoneSameInstant(ZoneId.systemDefault());
System.out.println("Local Time " + localTime.toString());
For starters, note that not only is the code only half as long as yours, it is also clearer to read.
On my computer the code prints:
Local:2017-09-02T07:25:46.211+02:00[Europe/Berlin] --> UTC time:2017-09-02T05:25:46.211Z
Local Time 2017-09-02T07:25:46.211+02:00[Europe/Berlin]
I left out the milliseconds from the epoch. You can always get them from System.currentTimeMillis();
as in your question, and they are independent of time zone, so I didn’t find them intersting here.
I hesitatingly kept your variable name localTime
. I think it’s a good name. The modern API has a class called LocalTime
, so using that name, only not capitalized, for an object that hasn’t got type LocalTime
might confuse some (a LocalTime
doesn’t hold time zone information, which we need to keep here to be able to make the right conversion; it also only holds the time-of-day, not the date).
Your conversion from local time to UTC was incorrect and impossible
The outdated Date
class doesn’t hold any time zone information (you may say that internally it always uses UTC), so there is no such thing as converting a Date
from one time zone to another. When I just ran your code on my computer, the first line it printed, was:
Local:Sat Sep 02 07:25:45 CEST 2017,1504329945967 --> UTC time:Sat Sep 02 05:25:45 CEST 2017-1504322745000
07:25:45 CEST
is correct, of course. The correct UTC time would have been 05:25:45 UTC
, but it says CEST
again, which is incorrect.
Now you will never need the Date
class again, :-) but if you were ever going to, the must-read would be All about java.util.Date on Jon Skeet’s coding blog.
Question: Can I use the modern API with my Java version?
If using at least Java 6, you can.
check with either:
ps -edaf | grep mongo | grep -v grep # "ps" flags may differ on your OS
or
/etc/init.d/mongodb status # for MongoDB version < 2.6
/etc/init.d/mongod status # for MongoDB version >= 2.6
or
service mongod status
to see if mongod is running (you need to be root to do this, or prefix everything with sudo
). Please note that the 'grep' command will always also show up as a separate process.
check the log file /var/log/mongo/mongo.log to see if there are any problems reported
Change this:
if(isset($_POST['submit'])){
if(!(isset($_POST['userName']))){
$username = 'Anonymous';
}
else $username = $_POST['userName'];
}
To this:
if(!empty($_POST['userName'])){
$username = $_POST['userName'];
}
if(empty($_POST['userName'])){
$username = 'Anonymous';
}
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
Can't do CLOBs in a Statement.
And: (OraclePreparedStatement) ps
On Windows I usually use windows types. To use it you have to include <Windows.h>
.
In this case uint32_t is UINT32 or just UINT.
All types definitions are here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx
As James mentioned above, the best way is to look at the header where the type is defined.
You can find the definition of pthread_t in pthreadtypes.h which can be found at:
/usr/include/bits/pthreadtypes.h
Adding host: localhost
was the magic for me
development:
adapter: postgresql
database: database_name_here
host: localhost
username: user_name_here
The VBScript Messagebox is fairly limited as to the labels you can apply to the buttons, your choices are pretty much limited to:
So you are going to have to build your own form if you want "ON"/"OFF"
Better yet, why not rephrase the prompt in the box so one of the above options works.
For example:
Do you want the light on?
[Yes] [No]
And for God's sake don't do one of these UI monstrosities!
Switch setting? (Click "yes" for ON and "No" for Off)
[Yes] [No]
The following approach is more concise than piping Join-Path statements:
$p = "a"; "b", "c", "d" | ForEach-Object -Process { $p = Join-Path $p $_ }
$p then holds the concatenated path 'a\b\c\d'.
(I just noticed that this is the exact same approach as Mike Fair's, sorry.)
In this case you use -1.
Windows MySQL v5 throws an error but Linux and other versions only raise a warning. This needs to be fixed. WTF?
Also see an attempt to fix this as bug #19498 in the MySQL Bugtracker:
Bryce Nesbitt on April 4 2008 4:36pm:
On MS Windows the "no DEFAULT" rule is an error, while on other platforms it is often a warning. While not a bug, it's possible to get trapped by this if you write code on a lenient platform, and later run it on a strict platform:
Personally, I do view this as a bug. Searching for "BLOB/TEXT column can't have a default value" returns about 2,940 results on Google. Most of them are reports of incompatibilities when trying to install DB scripts that worked on one system but not others.
I am running into the same problem now on a webapp I'm modifying for one of my clients, originally deployed on Linux MySQL v5.0.83-log. I'm running Windows MySQL v5.1.41. Even trying to use the latest version of phpMyAdmin to extract the database, it doesn't report a default for the text column in question. Yet, when I try running an insert on Windows (that works fine on the Linux deployment) I receive an error of no default on ABC column. I try to recreate the table locally with the obvious default (based on a select of unique values for that column) and end up receiving the oh-so-useful BLOB/TEXT column can't have a default value.
Again, not maintaining basic compatability across platforms is unacceptable and is a bug.
How to disable strict mode in MySQL 5 (Windows):
Edit /my.ini and look for line
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Replace it with
sql_mode='MYSQL40'
Restart the MySQL service (assuming that it is mysql5)
net stop mysql5
net start mysql5
If you have root/admin access you might be able to execute
mysql_query("SET @@global.sql_mode='MYSQL40'");
export CLASSPATH=/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar
or, if you already have some classpath set
export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar
and, if also you want to include current directory
export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar:.
I prefer to not rely on shell aliases or another package.
Adding a simple line to scripts
section of your package.json
, you can run local npm commands like
npm run webpack
package.json
{
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack"
},
"devDependencies": {
"webpack": "^4.1.1",
"webpack-cli": "^2.0.11"
}
}
I have the same error. It's weird that it only happens whenever I used my dbContext to query to any of my model or get its list like:
var results = _dbContext.MyModel.ToList();
We tried to reinstall the Entity Framework, reference it properly but to no avail.
Luckily, we tried to check the Nuget for ALL
solutions, then update everything or make sure everything
is the same version because we noticed that the two projects has different EF versions on the Web project. And it works. The error is gone.
Here is the screenshot on how to Manage Nuget for all solutions:
You'll be wanting to use the 'read' command
while read name
do
echo "$name"
done < names.txt
Note that "$name" is quoted -- if it's not, it will be split using the characters in $IFS
as delimiters. This probably won't be noticed if you're just echoing the variable, but if your file contains a list of file names which you want to copy, those will get broken down by $IFS
if the variable is unquoted, which is not what you want or expect.
If you want to use Mike Clark's approach (loading into a variable rather than using read), you can do it without the use of cat
:
NAMES="$(< scripts/names.txt)" #names from names.txt file
for NAME in $NAMES; do
echo "$NAME"
done
The problem with this is that it loads the whole file into $NAMES
, when you read it back out, you can either get the whole file (if quoted) or the file broken down by $IFS
, if not quoted. By default, this will give you individual words, not individual lines. So if the name "Mary Jane" appeared on a line, you would get "Mary" and "Jane" as two separate names. Using read
will get around this... although you could also change the value of $IFS
cordova build android --release
I was able to resolve this, after trying so so many different things, by simply doing :
npm install cordova -g # to upgrade to version 10.0.0
cordova platform rm android
cordova platform add android # to upgrade to android version 9.0.0
Your problem is that each time you run the method you are assigning a new value to the constant. This is not allowed, as it makes the constant non-constant; even though the contents of the string are the same (for the moment, anyhow), the actual string object itself is different each time the method is called. For example:
def foo
p "bar".object_id
end
foo #=> 15779172
foo #=> 15779112
Perhaps if you explained your use case—why you want to change the value of a constant in a method—we could help you with a better implementation.
Perhaps you'd rather have an instance variable on the class?
class MyClass
class << self
attr_accessor :my_constant
end
def my_method
self.class.my_constant = "blah"
end
end
p MyClass.my_constant #=> nil
MyClass.new.my_method
p MyClass.my_constant #=> "blah"
If you really want to change the value of a constant in a method, and your constant is a String or an Array, you can 'cheat' and use the #replace
method to cause the object to take on a new value without actually changing the object:
class MyClass
BAR = "blah"
def cheat(new_bar)
BAR.replace new_bar
end
end
p MyClass::BAR #=> "blah"
MyClass.new.cheat "whee"
p MyClass::BAR #=> "whee"
<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />
});
<script> ("#foo").val() </script>
which returns 1 if you have selected a and so on..
Put in the URL bar and then click enter:
javascript:alert(document.title);
You can select and copy the text from the alert depending on the website and the web browser you are using.
https://play.golang.org/p/JGZ7mN0-U-
for k, v := range m {
fmt.Printf("key[%s] value[%s]\n", k, v)
}
or
for k := range m {
fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Go language specs for for
statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.
Issue: The Jet OLE DB provider reads a registry key to determine how many rows are to be read to guess the type of the source column. By default, the value for this key is 8. Hence, the provider scans the first 8 rows of the source data to determine the data types for the columns. If any field looks like text and the length of data is more than 255 characters, the column is typed as a memo field. So, if there is no data with a length greater than 255 characters in the first 8 rows of the source, Jet cannot accurately determine the nature of the data type. As the first 8 row length of data in the exported sheet is less than 255 its considering the source length as VARCHAR(255) and unable to read data from the column having more length.
Fix: The solution is just to sort the comment column in descending order. In 2012 onwards we can update the values in Advance tab in the Import wizard.
If you want an efficient search that is often repeated, first sort the array (Array.Sort
) and then use Array.BinarySearch
.
Click on View/Show Symbol/Show All Character - to show the [SOH] characters in the file Click on the [SOH] symbol in the file CTRL=H to bring up the replace Leave the 'Find What:' as is Change the 'Replace with:' to the character of your choosing (comma,semicolon, other...) Click 'Replace All' Done and done!
Just in case if you want to do this using an npm package semver
link
let fs = require('fs');
let semver = require('semver');
if (fs.existsSync('./package.json')) {
var package = require('./package.json');
let currentVersion = package.version;
let type = process.argv[2];
if (!['major', 'minor', 'patch'].includes(type)) {
type = 'patch';
}
let newVersion = semver.inc(package.version, type);
package.version = newVersion;
fs.writeFileSync('./package.json', JSON.stringify(package, null, 2));
console.log('Version updated', currentVersion, '=>', newVersion);
}
package.json
should look like,
{
"name": "versioning",
"version": "0.0.0",
"description": "Update version in package.json using npm script",
"main": "version.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"version": "node version.js"
},
"author": "Bhadresh Arya",
"license": "ISC",
"dependencies": {
"semver": "^7.3.2"
}
}
just pass major
, minor
, patch
argument with npm run version
. Default will be patch
.
example:
npm run version
or npm run verison patch
or npm run verison minor
or npm run version major
A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field
L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.
I got a GPU called NVIDIA GTX GeForce 1650 Ti
in my machine with tensorflow-gpu==2.2.0
Run the following two lines of code:
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Output:
Num GPUs Available: 1
If you aren't worried about squeaking every single last bit of performance the suggestion to use a HashSet or binary search is solid. Your datasets just aren't large enough that this is going to be a problem 99% of the time.
But if this just one of thousands of times you are going to do this and performance is critical (and proven to be unacceptable using HashSet/binary search), you could certainly write your own algorithm that walked the sorted lists doing comparisons as you went. Each list would be walked at most once and in the pathological cases wouldn't be bad (once you went this route you'd probably find that the comparison, assuming it's a string or other non-integral value, would be the real expense and that optimizing that would be the next step).
import datetime
def diff_times_in_seconds(t1, t2):
# caveat emptor - assumes t1 & t2 are python times, on the same day and t2 is after t1
h1, m1, s1 = t1.hour, t1.minute, t1.second
h2, m2, s2 = t2.hour, t2.minute, t2.second
t1_secs = s1 + 60 * (m1 + 60*h1)
t2_secs = s2 + 60 * (m2 + 60*h2)
return( t2_secs - t1_secs)
# using it
diff_times_in_seconds( datetime.datetime.strptime( "13:23:34", '%H:%M:%S').time(),datetime.datetime.strptime( "14:02:39", '%H:%M:%S').time())
For anyone still coming to this post, the other option is to simply omit the parentheses:
Sub SomeOtherSub(Stattyp As String)
'Daty and the other variables are defined here
CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2
End Sub
The Call
keywords is only really in VBA for backwards compatibilty and isn't actually required.
If however, you decide to use the Call
keyword, then you have to change your syntax to suit.
'// With Call
Call Foo(Bar)
'// Without Call
Foo Bar
Both will do exactly the same thing.
That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call
keyword and the parentheses
It might help somebody. I had the same problem, same error message, same everything. I tried solutions from other answers, didn't help until I realised that the bean I am using has the same name as the one that is actually been autowired. It happened in the midst of refactor, thus I had to rename the class, which resulted positively. Cheers
var ws = new WebSocket("ws://" + window.location.host + ":6666");
ws.onopen = function() { ws.send( .. etc
You could use cursor.lastrowid (see "Optional DB API Extensions"):
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
username varchar(50),
password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('test','test'))
print(cursor.lastrowid)
# 1
If two people are inserting at the same time, as long as they are using different cursor
s, cursor.lastrowid
will return the id
for the last row that cursor
inserted:
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
print(cursor2.lastrowid)
# 3
print(cursor.lastrowid)
# 2
cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
(100,'blah','blah'))
print(cursor.lastrowid)
# 100
Note that lastrowid
returns None
when you insert more than one row at a time with executemany
:
cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
(('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None
I think what you are being asked to do (or perhaps asking yourself?) is take a character value which matches the name of a column in a particular dataframe (possibly also given as a character). There are two tricks here. Most people learn to extract columns with the "$" operator and that won't work inside a function if the function is passed a character vecor. If the function is also supposed to accept character argument then you will need to use the get
function as well:
df1 <- data.frame(a=1:10, b=11:20)
mean_col <- function( dfrm, col ) mean( get(dfrm)[[ col ]] )
mean_col("df1", "b")
# [1] 15.5
There is sort of a semantic boundary between ordinary objects like character vectors and language objects like the names of objects. The get
function is one of the functions that lets you "promote" character values to language level evaluation. And the "$" function will NOT evaluate its argument in a function, so you need to use"[[". "$" only is useful at the console level and needs to be completely avoided in functions.
You can simply answers, in just one line
No, you can never instance Abstract Class
But, interviewer still not agree, then you can tell him/her
all you can do is, you can create an Anonymous Class.
And, according to Anonymous class, class declared and instantiate at the same place/line
So, it might be possible that, interviewer would be interested to check your confidence level and how much you know about the OOPs .
You don't need to change the compliance level here, or rather, you should but that's not the issue.
The code compliance ensures your code is compatible with a given Java version.
For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).
The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.
Instead, you should check the JDK/JRE you're using to build.
In Eclipse, open the project properties and check the selected JRE in the Java build path.
If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.
textarea {
width: 700px;
height: 100px;
resize: none; }
assign your required width and height for the textarea and then use. resize: none ; css property which will disable the textarea's stretchable property.
You can create a local computer policy on Windows. See the TechNet at http://technet.microsoft.com/en-us/magazine/dd630947
gpedit.msc
to open the Group Policy Editor,Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
I am using xampp v3.2.4 and mysql server 8.0.20.
I added local-infile=1
to [mysql]
and [mysqld]
in the file "my.ini". The file is located at "C:\xampp\mysql\bin\my.ini".
Then I inserted the data from csv file using the following code LOAD DATA INFILE ...
. It is important to move LOCAL. Otherwise it won't work.
Thanks for all suggestions above. A combination finally worked out for me.
To check all the applications listening on all ports, there is command:
netstat -ntpl
For some frequently used movements and actions, I have defined the following mappings. This saves a keystroke compared to the CTRL+O combination and since I need them frequently, they pay off in the long run.
inoremap <A-$> <C-o>$
inoremap <A-^> <C-o>^
inoremap <A-h> <Left>
inoremap <A-l> <Right>
inoremap <A-O> <C-O>O
inoremap <A-o> <C-o>o
You can do:
foo.instance_of?(String)
And the more general:
foo.kind_of?(String)
You can use a media-query hack to select Safari 6.1-7.0 from other browsers.
@media \\0 screen {}
Disclaimer: This hack also targets old Chrome versions (before July 2013).
You need to prevent the default behaviour. You can either use e.preventDefault()
or return false;
In this case, the best thing is, you can use return false;
here:
<form onsubmit="completeAndRedirect(); return false;">
So this is an older question, but for those still looking for an answer, the CSS property Box-Sizing is priceless here:
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box;
It means that you can set the width of the Div to a percentage, and any border you add to the div will be included within that percentage. So, for example, the following would add the 1px border to the inside of the width of the div:
div { box-sizing:border-box; width:50%; border-right:1px solid #000; }
If you'd like more info: http://css-tricks.com/box-sizing/
Also make sure the page is valid. You can check this in the browsers developer tools (F12)
In the Console tab select the correct Target/Frame and check for the [Page_IsValid] property
If the page is not valid the form will not submit and therefore not fire the event.
fileExists()
is a method of FileSystemObject
, not a global scope function.
You also have an issue with the delete, DeleteFile()
is also a method of FileSystemObject
.
Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.
So you could use the block:
if NOT fso.FileExists(newname) Then
file.move fso.buildpath(OUT_PATH, newname)
else
fso.DeleteFile newname
file.move fso.buildpath(OUT_PATH, newname)
end if
Also be careful that your string comparison with the =
sign is case sensitive. Use strCmp
with vbText
compare option for case insensitive string comparison.
Apple recommends defining enums like this since Xcode 4.4:
typedef enum ShapeType : NSUInteger {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;
They also provide a handy macro NS_ENUM
:
typedef NS_ENUM(NSUInteger, ShapeType) {
kCircle,
kRectangle,
kOblateSpheroid
};
These definitions provide stronger type checking and better code completion. I could not find official documentation of NS_ENUM
, but you can watch the "Modern Objective-C" video from WWDC 2012 session here.
UPDATE
Link to official documentation here.
getimagesize('image.jpg')
function works only if allow_url_fopen
is set to 1 or On inside php.ini file on the server,
if it is not enabled, one should use
ini_set('allow_url_fopen',1);
on top of the file where getimagesize() function is used.
Your IDE should also support this. My IDE (SlickeEdit) calls it a "tag library." Simply add a tag library for the jar file, and you should be able to browse the classes and methods in a hierarchical manner.
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
::
is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::
, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
or you can simply use
def question_params
params.require(:question).permit(team_ids: [])
end
After reading cURL documentation on the options you used, it looks like the private key of certificate is not in the same file. If it is in different file, you need to mention it using --key file and supply passphrase.
So, please make sure that either cert.pem has private key (along with the certificate) or supply it using --key option.
Also, this documentation mentions that Note that this option assumes a "certificate" file that is the private key and the private certificate concatenated!
How they are concatenated? It is quite easy. Put them one after another in the same file.
You can get more help on this here.
I believe this might help you.
Using Tyler Dodge's excellent answer kept lagging on my iPad, so I added some throttling code, now it's quite smooth. There is some minimal skipping sometimes while scrolling.
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
e.preventDefault();
});
var scrolling = false;
// Uses body because jquery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart','.scrollable',function(e) {
// Only execute the below code once at a time
if (!scrolling) {
scrolling = true;
if (e.currentTarget.scrollTop === 0) {
e.currentTarget.scrollTop = 1;
} else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
e.currentTarget.scrollTop -= 1;
}
scrolling = false;
}
});
// Prevents preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove','.scrollable',function(e) {
e.stopPropagation();
});
Also, adding the following CSS fixes some rendering glitches (source):
.scrollable {
overflow: auto;
overflow-x: hidden;
-webkit-overflow-scrolling: touch;
}
.scrollable * {
-webkit-transform: translate3d(0,0,0);
}
Check following html I removed display:block from style
<div id="tfl" style="width: 187px; height: 260px; font-family: Verdana, Arial, Helvetica, sans-serif !important; background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/widget-panel.gif) #fff no-repeat; font-size: 11px; border: 1px solid #103994; border-radius: 4px; box-shadow: 2px 2px 3px 1px #ccc;">
<div style="display: block; padding: 30px 0 15px 0;">
<h2 style="color: rgb(36, 66, 102); text-align: center; display: block; font-size: 15px; font-family: arial; border: 0; margin-bottom: 1em; margin-top: 0; font-weight: bold !important; background: 0; padding: 0">Journey Planner</h2>
<form action="http://journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2" id="jpForm" method="post" target="tfl" style="margin: 5px 0 0 0 !important; padding: 0 !important;">
<input type="hidden" name="language" value="en" />
<!-- in language = english -->
<input type="hidden" name="execInst" value="" /><input type="hidden" name="sessionID" value="0" />
<!-- to start a new session on JP the sessionID has to be 0 -->
<input type="hidden" name="ptOptionsActive" value="-1" />
<!-- all pt options are active -->
<input type="hidden" name="place_origin" value="London" />
<!-- London is a hidden parameter for the origin location -->
<input type="hidden" name="place_destination" value="London" /><div style="padding-right: 15px; padding-left: 15px">
<input type="text" name="name_origin" style="width: 155px !important; padding: 1px" value="From" /><select style="width: 155px !important; margin: 0 !important;" name="type_origin"><option value="stop">Station or stop</option>
<option value="locator">Postcode</option>
<option value="address">Address</option>
<option value="poi">Place of interest</option>
</select>
</div>
<div style="margin-top: 10px; margin-bottom: 4px; padding-right: 15px; padding-left: 15px; padding-bottom: 15px; background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/panel-separator.gif) no-repeat bottom;">
<input type="text" name="name_destination" style="width: 100% !important; padding: 1px" value="232 Kingsbury Road (NW9)" /><select style="width: 155px !important; margin-top: 0 !important;" name="type_destination"><option value="stop">Station or stop</option>
<option value="locator">Postcode</option>
<option value="address" selected="selected">Address</option>
<option value="poi">Place of interest</option>
</select>
</div>
<div style="background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/panel-separator.gif) no-repeat bottom; padding-bottom: 2px; padding-top: 2px; overflow: hidden; margin-bottom: 8px">
<div style="clear: both; background: url(http://www.tfl.gov.uk/tfl-global/images/options-icons.gif) no-repeat 9.5em 0; height: 30px; padding-right: 15px; padding-left: 15px"><a style="text-decoration: none; color: #113B92; font-size: 11px; white-space: nowrap; display: inline-block; padding: 4px 0 5px 0; width: 155px" target="tfl" href="http://journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2?language=en&ptOptionsActive=1" onclick="javascript:document.getElementById('jpForm').ptOptionsActive.value='1';document.getElementById('jpForm').execInst.value='readOnly';document.getElementById('jpForm').submit(); return false">More options</a></div>
</div>
<div style="text-align: center;">
<input type="submit" title="Leave now" value="Leave now" style="border-style: none; background-color: #157DB9; display: inline-block; padding: 4px 11px; color: #fff; text-decoration: none; border-radius: 3px; border-radius: 3px; border-radius: 3px; box-shadow: 0 1px 3px rgba(0,0,0,0.25); box-shadow: 0 1px 3px rgba(0,0,0,0.25); box-shadow: 0 1px 3px rgba(0,0,0,0.25); text-shadow: 0 -1px 1px rgba(0,0,0,0.25); border-bottom: 1px solid rgba(0,0,0,0.25); position: relative; cursor: pointer; font: bold 13px/1 Arial,Helvetica,sans-serif; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.4); line-height: 1;" />
</div>
</form>
</div>
</div
Invoke-Sqlcmd -Query "sp_who" -ServerInstance . -QueryTimeout 3
Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.
The code below does the following:
static TypeHashes _type = new TypeHashes(typeof(Program));
private void Run()
{
TracerConfig.Reset("debugoutput");
using (Tracer t = new Tracer(_type, "Run"))
{
for (int i = 0; i < 4; i++)
{
DoSomeThingAsync(i);
}
}
Application.Run(); // Start window message pump to prevent termination
}
private async void DoSomeThingAsync(int i)
{
using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
{
t.Info("Hi in DoSomething {0}",i);
try
{
int result = await Calculate(i);
t.Info("Got async result: {0}", result);
}
catch (ArgumentException ex)
{
t.Error("Got argument exception: {0}", ex);
}
}
}
Task<int> Calculate(int i)
{
var t = new Task<int>(() =>
{
using (Tracer t2 = new Tracer(_type, "Calculate"))
{
if( i % 2 == 0 )
throw new ArgumentException(String.Format("Even argument {0}", i));
return i++;
}
});
t.Start();
return t;
}
When you observe the traces
22:25:12.649 02172/02820 { AsyncTest.Program.Run
22:25:12.656 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.657 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0
22:25:12.658 02172/05220 { AsyncTest.Program.Calculate
22:25:12.659 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.659 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1
22:25:12.660 02172/02756 { AsyncTest.Program.Calculate
22:25:12.662 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.662 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2
22:25:12.662 02172/02820 { AsyncTest.Program.DoSomeThingAsync
22:25:12.662 02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3
22:25:12.664 02172/02756 } AsyncTest.Program.Calculate Duration 4ms
22:25:12.666 02172/02820 } AsyncTest.Program.Run Duration 17ms ---- Run has completed. The async methods are now scheduled on different threads.
22:25:12.667 02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1
22:25:12.667 02172/02756 } AsyncTest.Program.DoSomeThingAsync Duration 8ms
22:25:12.667 02172/02756 { AsyncTest.Program.Calculate
22:25:12.665 02172/05220 Exception AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
22:25:12.668 02172/02756 Exception AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
22:25:12.724 02172/05220 } AsyncTest.Program.Calculate Duration 66ms
22:25:12.724 02172/02756 } AsyncTest.Program.Calculate Duration 57ms
22:25:12.725 02172/05220 Error AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0
Server stack trace:
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Exception rethrown at [0]:
at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()
at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()
at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106
22:25:12.725 02172/02756 Error AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2
Server stack trace:
at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Exception rethrown at [0]:
at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()
at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()
at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0
22:25:12.726 02172/05220 } AsyncTest.Program.DoSomeThingAsync Duration 70ms
22:25:12.726 02172/02756 } AsyncTest.Program.DoSomeThingAsync Duration 64ms
22:25:12.726 02172/05220 { AsyncTest.Program.Calculate
22:25:12.726 02172/05220 } AsyncTest.Program.Calculate Duration 0ms
22:25:12.726 02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3
22:25:12.726 02172/05220 } AsyncTest.Program.DoSomeThingAsync Duration 64ms
You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.
The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.
Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.
You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.
Just to add in the reverse as a trick, at a PowerShell prompt you can do:
ii .
or
start .
to open a Windows Explorer window in your current directory.
There are very few real use cases in which being able to evaluate a String
as a fragment of Java code is necessary or desirable. That is, asking how to do this is really an XY problem: you actually have a different problem, which can be solved a different way.
First ask yourself, where did this String
that you wish to evaluate come from? Did another part of your program generate it, or was it input provided by the user?
Another part of my program generated it: so, you want one part of your program to decide the kind of operation to perform, but not perform the operation, and a second part that performs the chosen operation. Instead of generating and then evaluating a String
, use the Strategy, Command or Builder design pattern, as appropriate for your particular case.
It is user input: the user could input anything, including commands that, when executed, could cause your program to misbehave, crash, expose information that should be secret, damage persistent information (such as the content of a database), and other such nastiness. The only way to prevent that would be to parse the String
yourself, check it was not malicious, and then evaluate it. But parsing it yourself is much of the work that the requested eval
function would do, so you have saved yourself nothing. Worse still, checking that arbitrary Java
was not malicious is impossible, because checking that is the halting problem.
It is user input, but the syntax and semantics of permitted text to evaluate is greatly restricted: No general purpose facility can easily implement a general purpose parser and evaluator for whatever restricted syntax and semantics you have chosen. What you need to do is implement a parser and evaluator for your chosen syntax and semantics. If the task is simple, you could write a simple recursive-descent or finite-state-machine parser by hand. If the task is difficult, you could use a compiler-compiler (such as ANTLR) to do some of the work for you.
I just want to implement a desktop calculator!: A homework assignment, eh? If you could implement the evaluation of the input expression using a provided eval
function, it would not be much of a homework assignment, would it? Your program would be three lines long. Your instructor probably expects you to write the code for a simple arithmetic parser/evaluator. There is well known algorithm, shunting-yard, which you might find useful.
Maybe You are trying to open folder with open
, check it once.
Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;
inputString.splitlines()
Will give you a list with each item, the splitlines()
method is designed to split each line into a list element.
The main concept of partial view is returning the HTML code rather than going to the partial view it self.
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
this action return the HTML code of the partial view ("HolidayPartialView").
To refresh partial view replace the existing item with the new filtered item using the jQuery below.
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
You cannot do it for File, which is primarily an intelligent file path. Can you refactor your code so that it declares the variables, and passes around arguments, with type OutputStream instead of FileOutputStream? If so, see classes java.io.ByteArrayOutputStream and java.io.ByteArrayInputStream
OutputStream outStream = new ByteArrayOutputStream();
outStream.write(whatever);
outStream.close();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);
...
I use [^\t\r\n\x20-\x7E]+
and that seems to be working fine.
Personally, I use ... | Out-Null
because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null
and [void] ...
. $null = ...
is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null
and ... > $null
come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null
), compared to putting $null =
or [void]
before the expression to determine what happens after executing it.
Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help
command or your favorite search engine to try to find out what Out-Null
does. You get a useful result immediately, right? Now try to do the same with [void]
and $null =
. Not so easy, is it?
Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void]
, $null =
, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*
* I am presuming that Out-Null
is clear and well-known, which I don't know to be $true
. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.
This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...
window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
Now that you are editing the file you need to add the line into the server block, like so;
server {
client_max_body_size 8M;
//other lines...
}
If you are hosting multiple sites add it to the http context like so;
http {
client_max_body_size 8M;
//other lines...
}
And also update the upload_max_filesize
in your php.ini file so that you can upload files of the same size.
Once you are done you need to save, this can be done in vi with pressing esc
key and typing :wq
and returning.
Now you need to restart nginx and php to reload the configs. This can be done using the following commands;
sudo service nginx restart
sudo service php5-fpm restart
Or whatever your php service is called.
The HttpContext.Current.User.Identity.Name returns null
This depends on whether the authentication mode is set to Forms or Windows in your web.config file.
For example, if I write the authentication like this:
<authentication mode="Forms"/>
Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:
<authentication mode="Windows"/>
I can run the application again and check for the username, and I will get the username successfully.
For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.
I find this problem appearing when I've done a git add .
in a subdirectory below where my .gitignore
file lives (the home directory of my repository, so to speak). Try changing directories to your uppermost directory and running git add .
followed by git commit -m "my commit message"
.
I had the same problem with numpy arrays and the solution is to flatten them:
data = {
'b': array1.flatten(),
'a': array2.flatten(),
}
df = pd.DataFrame(data)
Would not \\(.*?\\)
work? That is the non-greedy syntax.
you can do this:
bc <<< 'scale=2; 100/3'
33.33
UPDATE 20130926
: you can use:
bc -l <<< '100/3' # saves a few hits
33.33333333333333333333
The secret key is combined with the header and the payload to create a unique hash. You are only able to verify this hash if you have the secret key.
You can choose a good, long password. Or you can generate it from a site like this.
Example (but don't use this one now):
8Zz5tw0Ionm3XPZZfN0NOml3z9FMfmpgXwovR9fp6ryDIoGRM8EPHAB6iHsc0fb
You can tag your DOM element using #someTag
, then get it with @ViewChild('someTag')
.
See complete example:
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}
console.log
will print Some text.
Just to enhance @adivis12 answer, you don't need to do the if
statement. Put it like this:
fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
dict_of_dfs[BAR].plot(ax=ax)
Although it is much easier to restore database using SSMS as stated in many answers. You can also restore Database using .bak with SQL server query, for example
RESTORE DATABASE AdventureWorks2012 FROM DISK = 'D:\AdventureWorks2012.BAK'
GO
In above Query you need to keep in mind about .mdf/.ldf file location. You might get error
System.Data.SqlClient.SqlError: Directory lookup for the file "C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\AdventureWorks.MDF" failed with the operating system error 3(The system cannot find the path specified.). (Microsoft.SqlServer.SmoExtended)
So you need to run Query as below
RESTORE FILELISTONLY
FROM DISK = 'D:\AdventureWorks2012.BAK'
Once you will run above Query you will get location of mdf/ldf use it Restore database using query
USE MASTER
GO
RESTORE DATABASE DBASE
FROM DISK = 'D:\AdventureWorks2012.BAK'
WITH
MOVE 'DBASE' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE.MDF',
MOVE 'DBASE_LOG' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE_1.LDF',
NOUNLOAD, REPLACE, NOUNLOAD, STATS = 5
GO
Source:Restore database from .bak file in SQL server (With & without scripts)
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}
I'd try something like this:
$(function(){
$("#searchclear").click(function(){
$("#d").select2('val', 'All');
});
});
gdb has --init-command <somefile>
where somefile has a list of gdb commands to run, I use this to have //GDB
comments in my code, then `
echo "file ./a.out" > run
grep -nrIH "//GDB"|
sed "s/\(^[^:]\+:[^:]\+\):.*$/\1/g" |
awk '{print "b" " " $1}'|
grep -v $(echo $0|sed "s/.*\///g") >> run
gdb --init-command ./run -ex=r
as a script, which puts the command to load the debug symbols, and then generates a list of break commands to put a break point for each //GDB
comment, and starts it running
Add poster="placeholder.png"
to the video tag.
<video width="470" height="255" poster="placeholder.png" controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
<object data="video.mp4" width="470" height="255">
<embed src="video.swf" width="470" height="255">
</object>
</video>
Does that work?
Just to give more perspective to the answers
Spark-shell is a scala repl
You can type :help to see the list of operation that are possible inside the scala shell
scala> :help
All commands can be abbreviated, e.g., :he instead of :help.
:edit <id>|<line> edit history
:help [command] print this summary or command-specific help
:history [num] show the history (optional num is commands to show)
:h? <string> search the history
:imports [name name ...] show import history, identifying sources of names
:implicits [-v] show the implicits in scope
:javap <path|class> disassemble a file or class name
:line <id>|<line> place line(s) at the end of history
:load <path> interpret lines in a file
:paste [-raw] [path] enter paste mode or paste a file
:power enable power user mode
:quit exit the interpreter
:replay [options] reset the repl and replay all previous commands
:require <path> add a jar to the classpath
:reset [options] reset the repl to its initial state, forgetting all session entries
:save <path> save replayable session to a file
:sh <command line> run a shell command (result is implicitly => List[String])
:settings <options> update compiler options, if possible; see reset
:silent disable/enable automatic printing of results
:type [-v] <expr> display the type of an expression without evaluating it
:kind [-v] <expr> display the kind of expression's type
:warnings show the suppressed warnings from the most recent line which had any
:load interpret lines in a file
Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL
If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:
import pandas as pd
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')
df.to_csv('file.csv', index=False)
print(df)
Col0 Col1 Col2
0 1 4 7
1 2 5 8
2 3 6 9
Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)
The option you're asking about is for the find
command though, not for bash. From your command line, you can man find
to see the options.
The one you're looking for is -o
for "or":
list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.
$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt
Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:
$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 one.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 two three.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 foo.bmp
The Bash FAQ has lots of other excellent tips about programming in bash.
While I don't think there is a way to fully do this you can take a few measures to stop almost everyone from viewing the HTML.
You can first of all try and stop the inspect menu by doing the following:
<body oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;">
I would also suggest using the method that Jonas gave of using his javascript and putting what you don't want people to see in a div with id="element-to-hide" and his given js script to furthermore stop people from inspecting.
I'm pretty sure that it's quite hard to get past that. But then someone can just type view-source:www.exapmle.com and that will show them the source. So you will then probably want to encrypt the HTML(I would advise using a website that gives you an extended security option). There are plenty of good websites that do this for free (eg:http://www.smartgb.com/free_encrypthtml.php) and use extended security which you can't usually unencrypt through HTML un encryptors.
This will basically encrypt your HTML so if you view the source using the method I showed above you will just get encrypted HTML(that is also extremely difficult to unencrypt if you used the extended security option). But you can view the unencrypted HTML through inspecting but we have already blocked that(to a very reasonable extent)
Ok so you can't fully hide the HTML but you can do an extremely good job at stopping people seeing it.(If you think about it most people don't care about looking at a page's HTML, some people don't even know about inspecting and viewing the source and the people who do probably won't be bothered or won't be able to get past theses implications! So probably no one will see you HTML)
(Hope this helps!)
I'm running Ubuntu 14.04; and apt still couldn't find package; I tried all the answers above and more. The URL that worked for me is this:
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Source: http://www.liquidweb.com/kb/how-to-install-mongodb-on-ubuntu-14-04/
sys.exit()
should return an integer, not a string:
sys.exit(1)
The value 1
is in $?
.
$ cat e.py
import sys
sys.exit(1)
$ python e.py
$ echo $?
1
Edit:
If you want to write to stderr, use sys.stderr
.
Inside, the less scope the variable is visible into the better.
First copy your jar file and paste into you Android project's libs folder.
Now right click on newly added (Pasted) jar file and select option
Build Path -> Add to build path
Now you added jar file will get displayed under Referenced Libraries. Again right click on it and select option
Build Path -> Configure Build path
A new window will get appeared. Select Java Build Path from left menu panel and then select Order and export Enable check on added jar file.
Now run your project.
More details @ Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)
We had the same error even though the user was properly mapped to the login.
After trying to delete the user it was discovered that a few SPs contained "with execute as" that user.
The issue was solved by dropping those SPs, dropping the user, recreating the user linked to login, and recreating the SPs.
Possibly it got in this state from restoring from backup (during a time when the related login didn't exist) or bulk schema syncing (if its possible to create an SP with execute as even though the user doesn't exist. Could also have been related to this answer.
Aside from the Documents
folder, iOS also lets you save files to the temp
and Library
folders.
For more information on which one to use, see this link from the documentation:
You can do it in a shorthand as:
_.uniq(foo, 'a')
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
A compact way to go about doing that could be:
make foo && ./$_
Nice to have a one-liner so you can just re-run your executable again easily.
For files encoding...
public class FRomUtf8ToIso {
static File input = new File("C:/Users/admin/Desktop/pippo.txt");
static File output = new File("C:/Users/admin/Desktop/ciccio.txt");
public static void main(String[] args) throws IOException {
BufferedReader br = null;
FileWriter fileWriter = new FileWriter(output);
try {
String sCurrentLine;
br = new BufferedReader(new FileReader( input ));
int i= 0;
while ((sCurrentLine = br.readLine()) != null) {
byte[] isoB = encode( sCurrentLine.getBytes() );
fileWriter.write(new String(isoB, Charset.forName("ISO-8859-15") ) );
fileWriter.write("\n");
System.out.println( i++ );
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static byte[] encode(byte[] arr){
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-15");
ByteBuffer inputBuffer = ByteBuffer.wrap( arr );
// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);
// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
}
}
You code should be:
<section id="right">
<label for="form_msg">Message</label>
<textarea name="form_msg" id="#msg_text"></textarea>
<input id="submit" class="button" name="submit" type="submit" value="Send">
</section>
Js
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
The PHP:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
//send email
mail("[email protected]","My Subject:",$email,$message);
}
?>
Check this SO answer out.
It looks like the only way is to provide the whole modal structure with your ajax response.
As you can check from the bootstrap source code, the load function is binded to the root element.
In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..)
plugin on your body element, even though it will probably break the show/hide functions of the root element.
The video quality depends upon the Connection speed using API
alternatively for other than API means without YouTube app you can follow this link
Please use DataType attribue but this will except negative values so the regular expression below will avoid this
[DataType(DataType.PhoneNumber,ErrorMessage="Not a number")]
[Display(Name = "Oxygen")]
[RegularExpression( @"^\d+$")]
[Required(ErrorMessage="{0} is required")]
[Range(0,30,ErrorMessage="Please use values between 0 to 30")]
public int Oxygen { get; set; }
Going off of @Powerlord's answer,
"There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0."
You can still start your counter at 0 (arrays, querys), but offset it
if (($counter + 1) % 3 == 0) {
echo 'image file';
}
The following code snippet resolved my issue. Thought this might be useful to others.
var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");
_x000D_
Rather using default encodeURIComponent
my first line of code is converting all spaces
into hyphens
using regex pattern /\s\g
and the following line just does the reverse, i.e. converts all hyphens
back to spaces
using another regex pattern /-/g
. Here /g
is actually responsible for finding all
matching characters.
When I am sending this value to my Ajax call, it traverses as normal spaces
or simply %20
and thus gets rid of double-encoding
.
I was using firefox and some reason, it was not taking the click command though from past 2months it was working. My feeling was to make use of sendKeys and this page solved the problem. Now I am using sendKeys(Keys.Enter)
You can use a combination of other LINQ methods to handle not matching condition:
var res = dictionary.Where(x => x.Value.ID == someID)
.Select(x => x.Value.DisplayName)
.DefaultIfEmpty("Unknown")
.First();
difference-between-value-object-pattern-and-data-transfer-pattern
Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):
string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,
You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s
to pattern: \[^\w\d\s]
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
XSS can be prevented in JSP by using JSTL <c:out>
tag or fn:escapeXml()
EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.
For example:
<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>
This will escape characters which may malform the rendered HTML such as <
, >
, "
, '
and &
into HTML/XML entities such as <
, >
, "
, '
and &
.
Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. &
becomes &amp;
instead of &
and ultimately the enduser would see &
being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.
If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>
, <i>
, <u>
, etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also Markdown or HTML.
The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement
instead of Statement
. In JPA terms, use Query
.
An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.
You can use standard directory functions
$dir = opendir('/tmp');
while ($file = readdir($dir)) {
if ($file == '.' || $file == '..') {
continue;
}
echo $file;
}
closedir($dir);
In your request
object there is a property called connection
, which is a net.Socket
object. The net.Socket object has a property remoteAddress
, therefore you should be able to get the IP with this call:
request.connection.remoteAddress
See documentation for http and net
EDIT
As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['x-forwarded-for']
For those who are more comfortable with learning by visualizing, here is a handy diagram I created to explain Process and Threads.
I used the information from MSDN - About Processes and Threads
The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
Since your styles are inline, you can write:
$(selector).css("-moz-user-select", "");
You should be using SqlConnection.State
e.g,
using System.Data;
if (myConnection != null && myConnection.State == ConnectionState.Closed)
{
// do something
// ...
}
To identify unlock screen I believe that you can use ID 4624. But then you also need to look at the Logon Type which in this case is 7: http://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventid=4624
Event ID for Logoff is 4634
I found the answer:
$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');
and on the <img>
tag put src='cid:logo_2u'
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
You can use this way, but be sure that there is no Page.Redirect()
is used.
If you want to redirect to another page then you can try this:
page.aspx:
<asp:Button AccessKey="S" ID="submitBtn" runat="server" OnClick="Submit" Text="Submit"
Width="90px" ValidationGroup="vg" CausesValidation="true" OnClientClick = "Confirm()" />
JavaScript code:
function Confirm()
{
if (Page_ClientValidate())
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Data has been Added. Do you wish to Continue ?"))
{
confirm_value.value = "Yes";
}
else
{
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
and this is your code behind snippet :
protected void Submit(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Response.Redirect("~/AddData.aspx");
}
else
{
Response.Redirect("~/ViewData.aspx");
}
}
This will sure work.
I want to provide an answer that worked as the only thing for me (I realize that I might be the only one ever). I had in one macro that I was calling using the ribbon. It had the following code:
colStore = new Collection
I wasn't aware that it throws an error so I was baffled and tried everything in here. The button just stopped working and I couldn't get it to work. When I noticed the error and corrected it to:
Set colStore = new Collection
It started working again. Absolutely strange if you ask me but maybe it helps someone out there who was as desperate as me.
The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:
Route::post('test/register', array('uses'=>'TestController@create'));
Also, you need to hash your passwords:
public function create()
{
$user = new User;
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::back();
}
And I removed the line:
$user= Input::all();
Because in the next command you replace its contents with
$user = new User;
To debug your Input, you can, in the first line of your controller:
dd( Input::all() );
It will display all fields in the input.
Use substring()
and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
I came researching the options that I would have to do this, however, I believe the method I use is the simplest:
SELECT COUNT(*),
DATEADD(dd, DATEDIFF(dd, 0, date_field),0) as dtgroup
FROM TABLE
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, date_field),0)
ORDER BY dtgroup ASC;
jQuery's .eq() can help you traverse through elements with an indexed approach.
var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
var element = testimonialElements.eq(i);
//do something with element
}
Just because you are referencing Project B's DLL doesn't mean that the Resource Manager of Project A is aware of Project B's App_GlobalResources directory.
Are you using web site projects or web application projects? In the latter, Visual Studio should allow you to link source code files (not sure about the former, I've never used them). This is a little-know but useful feature, which is described here. That way, you can link the Project B resource files into Project A.
The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)
After the redirect put exit(); to stop the rest of the script to execute
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
Adding local classes, lambdas and the toString()
method to complete the previous two answers. Further, I add arrays of lambdas and arrays of anonymous classes (which do not make any sense in practice though):
package com.example;
public final class TestClassNames {
private static void showClass(Class<?> c) {
System.out.println("getName(): " + c.getName());
System.out.println("getCanonicalName(): " + c.getCanonicalName());
System.out.println("getSimpleName(): " + c.getSimpleName());
System.out.println("toString(): " + c.toString());
System.out.println();
}
private static void x(Runnable r) {
showClass(r.getClass());
showClass(java.lang.reflect.Array.newInstance(r.getClass(), 1).getClass()); // Obtains an array class of a lambda base type.
}
public static class NestedClass {}
public class InnerClass {}
public static void main(String[] args) {
class LocalClass {}
showClass(void.class);
showClass(int.class);
showClass(String.class);
showClass(Runnable.class);
showClass(SomeEnum.class);
showClass(SomeAnnotation.class);
showClass(int[].class);
showClass(String[].class);
showClass(NestedClass.class);
showClass(InnerClass.class);
showClass(LocalClass.class);
showClass(LocalClass[].class);
Object anonymous = new java.io.Serializable() {};
showClass(anonymous.getClass());
showClass(java.lang.reflect.Array.newInstance(anonymous.getClass(), 1).getClass()); // Obtains an array class of an anonymous base type.
x(() -> {});
}
}
enum SomeEnum {
BLUE, YELLOW, RED;
}
@interface SomeAnnotation {}
This is the full output:
getName(): void
getCanonicalName(): void
getSimpleName(): void
toString(): void
getName(): int
getCanonicalName(): int
getSimpleName(): int
toString(): int
getName(): java.lang.String
getCanonicalName(): java.lang.String
getSimpleName(): String
toString(): class java.lang.String
getName(): java.lang.Runnable
getCanonicalName(): java.lang.Runnable
getSimpleName(): Runnable
toString(): interface java.lang.Runnable
getName(): com.example.SomeEnum
getCanonicalName(): com.example.SomeEnum
getSimpleName(): SomeEnum
toString(): class com.example.SomeEnum
getName(): com.example.SomeAnnotation
getCanonicalName(): com.example.SomeAnnotation
getSimpleName(): SomeAnnotation
toString(): interface com.example.SomeAnnotation
getName(): [I
getCanonicalName(): int[]
getSimpleName(): int[]
toString(): class [I
getName(): [Ljava.lang.String;
getCanonicalName(): java.lang.String[]
getSimpleName(): String[]
toString(): class [Ljava.lang.String;
getName(): com.example.TestClassNames$NestedClass
getCanonicalName(): com.example.TestClassNames.NestedClass
getSimpleName(): NestedClass
toString(): class com.example.TestClassNames$NestedClass
getName(): com.example.TestClassNames$InnerClass
getCanonicalName(): com.example.TestClassNames.InnerClass
getSimpleName(): InnerClass
toString(): class com.example.TestClassNames$InnerClass
getName(): com.example.TestClassNames$1LocalClass
getCanonicalName(): null
getSimpleName(): LocalClass
toString(): class com.example.TestClassNames$1LocalClass
getName(): [Lcom.example.TestClassNames$1LocalClass;
getCanonicalName(): null
getSimpleName(): LocalClass[]
toString(): class [Lcom.example.TestClassNames$1LocalClass;
getName(): com.example.TestClassNames$1
getCanonicalName(): null
getSimpleName():
toString(): class com.example.TestClassNames$1
getName(): [Lcom.example.TestClassNames$1;
getCanonicalName(): null
getSimpleName(): []
toString(): class [Lcom.example.TestClassNames$1;
getName(): com.example.TestClassNames$$Lambda$1/1175962212
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212
getSimpleName(): TestClassNames$$Lambda$1/1175962212
toString(): class com.example.TestClassNames$$Lambda$1/1175962212
getName(): [Lcom.example.TestClassNames$$Lambda$1;
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212[]
getSimpleName(): TestClassNames$$Lambda$1/1175962212[]
toString(): class [Lcom.example.TestClassNames$$Lambda$1;
So, here are the rules. First, lets start with primitive types and void
:
void
, all the four methods simply returns its name.Now the rules for the getName()
method:
getName()
) that is the package name followed by a dot (if there is a package), followed by the name of its class-file as generated by the compiler (whithout the suffix .class
). If there is no package, it is simply the name of the class-file. If the class is an inner, nested, local or anonymous class, the compiler should generate at least one $
in its class-file name. Note that for anonymous classes, the class name would end with a dollar-sign followed by a number.$$Lambda$
, followed by a number, followed by a slash, followed by another number.Z
for boolean
, B
for byte
, S
for short
, C
for char
, I
for int
, J
for long
, F
for float
and D
for double
. For non-array classes and interfaces the class descriptor is L
followed by what is given by getName()
followed by ;
. For array classes, the class descriptor is [
followed by the class descriptor of the component type (which may be itself another array class).getName()
method returns its class descriptor. This rule seems to fail only for array classes whose the component type is a lambda (which possibly is a bug), but hopefully this should not matter anyway because there is no point even on the existence of array classes whose component type is a lambda.Now, the toString()
method:
toString()
returns "interface " + getName()
. If it is a primitive, it returns simply getName()
. If it is something else (a class type, even if it is a pretty weird one), it returns "class " + getName()
.The getCanonicalName()
method:
getCanonicalName()
method returns just what the getName()
method returns.getCanonicalName()
method returns null
for anonymous or local classes and for array classes of those.getCanonicalName()
method returns what the getName()
method would replacing the compiler-introduced dollar-signs by dots.getCanonicalName()
method returns null
if the canonical name of the component type is null
. Otherwise, it returns the canonical name of the component type followed by []
.The getSimpleName()
method:
getSimpleName()
returns the name of the class as written in the source file.getSimpleName()
returns an empty String
.getSimpleName()
just returns what the getName()
would return without the package name. This do not makes much sense and looks like a bug for me, but there is no point in calling getSimpleName()
on a lambda class to start with.getSimpleName()
method returns the simple name of the component class followed by []
. This have the funny/weird side-effect that array classes whose component type is an anonymous class have just []
as their simple names.The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.
Fair disclosure: I'm the primary developer.
Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.
The most commonly used date formats are automatically supported, and additional date formats can be added if desired.
To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.
Besides the DatePicker, the library also has the TimePicker and DateTimePicker components. I pasted screenshots of all the components (and the demo program) below.
The library can be installed into your Java project from the project release page.
The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .
SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);