Adding mode:'no-cors'
to the request header guarantees that no response will be available in the response
Adding a "non standard" header, line 'access-control-allow-origin'
will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent
You're also doing fetch
wrong ... fetch
returns a "promise" for a Response
object which has promise creators for json
, text
, etc. depending on the content type...
In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.json();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
});
}
however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.text();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = muutuja;
});
}
here is the sample code to draw image on canvas-
$("#selectedImage").change(function(e) {
var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 500, 500);
}});
In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
Ok, the Java code I used was wrong, here comes the right Java class:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class PostFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
File file = new File("c:/TRASH/zaba_1.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
note using MultipartEntity.
Give your inputs names it will make it easier
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>
UPDATE:
If you give your button an id things can be even easier:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>
Javascript:
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
button.onclick = function() {
foo(value);
}
Using dplyr::mutate
:
library(dplyr)
df <- mutate(df, x = paste(n, s))
df
> df
n s b x
1 2 aa TRUE 2 aa
2 3 bb FALSE 3 bb
3 5 cc TRUE 5 cc
Setting the image using picture.ImageLocation()
works fine, but you are using a relative path. Check your path against the location of the .exe
after it is built.
For example, if your .exe
is located at:
<project folder>/bin/Debug/app.exe
The image would have to be at:
<project folder>/bin/Image/1.jpg
Of course, you could just set the image at design-time (the Image
property on the PictureBox
property sheet).
If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image
. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory
to Copy if newer
.
At this point the image file will be copied when you build the application and you can use
picture.ImageLocation = @"Image\1.jpg";
You have to write your own method in this case. Use a loop and get each character using charAt(i)
and set it to your Character[]
array using arrayname[i] = string.charAt[i]
.
Here's the example:
// Test
public void foo() {
C c = new C();
A s;
s = ((A.B)c).get();
System.out.println(s.getR());
}
// classes
class C {}
class A {
public class B extends C{
A get() {return A.this;}
}
public String getR() {
return "This is string";
}
}
My finally working approach is to try potential candidates of expected encodings by detecting invalid characters in the strings created from the byte array by the encodings. If I don't encounter invalid characters, I suppose the tested encoding works fine for the tested data.
For me, having only Latin and German special characters to consider, in order to determine the proper encoding for a byte array, I try to detect invalid characters in a string with this method:
/// <summary>
/// detect invalid characters in string, use to detect improper encoding
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static bool DetectInvalidChars(string s)
{
const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
return s.Any(ch => !(
specialChars.Contains(ch) ||
(ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z')));
}
(NB: if you have other Latin-based languages to consider, you might want to adapt the specialChars const string in the code)
Then I use it like this (I only expect UTF-8 or Default encoding):
// determine encoding by detecting invalid characters in string
var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
if (StringFuncs.DetectInvalidChars(invoiceXmlText))
invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default
If using Guava library, there are methods Ints.checkedCast(long)
and Ints.saturatedCast(long)
for converting long
to int
.
For node_modules you have to follow the below steps
1) In Command prompt -> Goto your project directory.
2) Command :npm init
3) It asks you to set up your package.json file
4) Command: npm install
or npm update
If you installed mongodb with homebrew, there's an easier way:
List mongo job with launchctl:
launchctl list | grep mongo
Stop mongo job:
launchctl stop <job label>
(For me this is launchctl stop homebrew.mxcl.mongodb
)
Start mongo job:
launchctl start <job label>
For Any *.Exe file written in any language .You can view the source code with hiew (otherwise Hackers view). You can download it at www.hiew.ru. It will be the demo version but still can view the code.
After this follow these steps:
Press alt+f2 to navigate to the file.
Press enter to see its assembly / c++ code.
@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this
[{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map( ( {name, email} ) => {
return <p key={email}>{name} - {email}</p>
})
Cheers!
It depends greatly on your application. For example, some applications consist mostly of GUI code that cannot be unit tested.
* {
-ms-touch-action: manipulation;
touch-action: manipulation;
}
Disable double tap to zoom on touch screens. Internet explorer included.
Needed this answer myself and from the link provided by David Moye, decided on this and thought it might be of use to others with the same question:
CREATE PROCEDURE ...
AS
BEGIN
BEGIN TRANSACTION
-- lock table "a" till end of transaction
SELECT ...
FROM a
WITH (TABLOCK, HOLDLOCK)
WHERE ...
-- do some other stuff (including inserting/updating table "a")
-- release lock
COMMIT TRANSACTION
END
Without external variables:
$('.element').bind('mousewheel', function(e, d) {
if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
|| (this.scrollTop === 0 && d > 0)) {
e.preventDefault();
}
});
//Resolved
const fetchPromise1 = fetch(url);
fetchPromise1.then(response => {
console.log(response);
});
//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);
Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.
You may want to experiment with BulkCopy in your C# or VB.Net code.
using Linq would be:
listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";
UPDATE
This can be simplified to be...
listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";
For multiple items (condition is met by multiple items):
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");
I had to make some changes to make it work, as some things seem to have changed in the meantime:
Here's a working example, hope this helps (I'm using JodaTime but in this case SimpleDate would be sufficient):
import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;
public class DateAdapter extends XmlAdapter<Object, Object> {
@Override
public Object marshal(Object dt) throws Exception {
return new DateTime((Date) dt).toString("YYYY-MM-dd");
}
@Override
public Object unmarshal(Object s) throws Exception {
return DatatypeConverter.parseDate((String) s).getTime();
}
}
In the xsd, I have followed the excellent references given above, so I have included this xml annotation:
<xsd:appinfo>
<jaxb:schemaBindings>
<jaxb:package name="at.mycomp.xml" />
</jaxb:schemaBindings>
<jaxb:globalBindings>
<jaxb:javaType name="java.util.Date" xmlType="xsd:date"
parseMethod="at.mycomp.xml.DateAdapter.unmarshal"
printMethod="at.mycomp.xml.DateAdapter.marshal" />
</jaxb:globalBindings>
</xsd:appinfo>
Ok, here's a simple box that follows the cursor
Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.
Select the right image (use a sprite) to orientate the rocket.
Yeah, annoying as hell. :-)
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = ""
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
I was having the same problem with a virtual host on Ubuntu 14.04
For me the following solution worked:
http://ubuntuforums.org/showthread.php?t=2185282
It's just adding a <Directory >
tag to /etc/apache2/apache2.conf
The same thing happened to me as I was installing the HPCC benchmark (includes HPL and a few other benchmarks). I added -lm
to the compiler flags in my build script and then it successfully compiled.
Since you tagged Java-ee as well - then YES it is possible.
and in core java as well it is possible using static blocks
and check this How can you run a Java program without main method?
Edit:
as already pointed out in other answers - it does not support from Java 7
http://animeshrivastava.blogspot.in/2017/08/activity-lifecycle-oncreate-beating_3.html
@Override
protected void onSaveInstanceState(Bundle b)
{
super.onSaveInstanceState(b);
String str="Screen Change="+String.valueOf(screenChange)+"....";
Toast.makeText(ctx,str+"You are changing orientation...",Toast.LENGTH_SHORT).show();
screenChange=true;
}
After you follow the first response, you can run your app using
react-native run-android --variant=debug
And your app will run without need for the packager
As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.
For example in firefox preferences:
Notice the last option.
For anyone stumbling upon this thread, here's a more complete solution. It will compare two objects and give you the key of all properties that are either only in object1, only in object2, or are both in object1 and object2 but have different values:
/*
* Compare two objects by reducing an array of keys in obj1, having the
* keys in obj2 as the intial value of the result. Key points:
*
* - All keys of obj2 are initially in the result.
*
* - If the loop finds a key (from obj1, remember) not in obj2, it adds
* it to the result.
*
* - If the loop finds a key that are both in obj1 and obj2, it compares
* the value. If it's the same value, the key is removed from the result.
*/
function getObjectDiff(obj1, obj2) {
const diff = Object.keys(obj1).reduce((result, key) => {
if (!obj2.hasOwnProperty(key)) {
result.push(key);
} else if (_.isEqual(obj1[key], obj2[key])) {
const resultKeyIndex = result.indexOf(key);
result.splice(resultKeyIndex, 1);
}
return result;
}, Object.keys(obj2));
return diff;
}
Here's an example output:
// Test
let obj1 = {
a: 1,
b: 2,
c: { foo: 1, bar: 2},
d: { baz: 1, bat: 2 }
}
let obj2 = {
b: 2,
c: { foo: 1, bar: 'monkey'},
d: { baz: 1, bat: 2 }
e: 1
}
getObjectDiff(obj1, obj2)
// ["c", "e", "a"]
If you don't care about nested objects and want to skip lodash, you can substitute the _.isEqual
for a normal value comparison, e.g. obj1[key] === obj2[key]
.
<% %>
Executes the ruby code within the brackets.
<%= %>
Prints something into erb file.
<%== %>
Equivalent to <%= raw %>
. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)
<% -%>
Avoids line break after expression.
<%# %>
Comments out code within brackets; not sent to client (as opposed to HTML comments).
Visit Ruby Doc for more infos about ERB.
if you have only one xml in your table, you can convert it in 2 steps:
CREATE TABLE Batches(
BatchID int,
RawXml xml
)
declare @xml xml=(select top 1 RawXml from @Batches)
SELECT --b.BatchID,
x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)
-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.
-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.
-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).
Compare the following differences:
/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root
/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root
/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET
If each row of the matrix is the same size, then you can simply use a linear array and multiplication.
That is,
a=()
for (( i=0; i<4; ++i )); do
for (( j=0; j<5; ++j )); do
a[i*5+j]=0
done
done
Then your a[2][3] = 3
becomes
a[2*5+3] = 3
This approach might be worth turning into a set of functions, but since you can't pass arrays to or return arrays from functions, you would have to use pass-by-name and sometimes eval
. So I tend to file multidimensional arrays under "things bash is simply Not Meant To Do".
For ng9 upgraders:
npm i -g core-js@^3
..then:
npm cache clean -f
..followed by:
npm i
i think you should do:
var myInterval
on.onclick = function() {
myInterval=setInterval(fontChange, 500);
};
off.onclick = function() {
clearInterval(myInterval);
};
I have tried this pure component:
const RawHTML = ({children, className = ""}) =>
<div className={className}
dangerouslySetInnerHTML={{ __html: children.replace(/\n/g, '<br />')}} />
Features
className
prop (easier to style it)\n
to <br />
(you often want to do that)<RawHTML>{myHTML}</RawHTML>
I have placed the component in a Gist at Github: RawHTML: ReactJS pure component to render HTML
I encountered a similar problem in my project. After struggling a lot, I found this solution:
if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
// do something
You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.
CSS3 allows this sort of thing and it looks like this:
body {
background-image: url(images/bgtop.png), url(images/bg.png);
background-repeat: repeat-x, repeat;
}
The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:
<body>
<div id="bgTopDiv">
content here
</div>
</body>
body{
background-image: url(images/bg.png);
}
#bgTopDiv{
background-image: url(images/bgTop.png);
background-repeat: repeat-x;
}
This is not the best practice in .NET framework (4 & +) to check equality
String.Compare(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase) == 0
Use the following instead
String.Equals(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase)
- Use an overload of the String.Equals method to test whether two strings are equal.
- Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.
For some reason, you're re-instantiating the form after you check is_valid()
. Forms only get a cleaned_data
attribute when is_valid()
has been called, and you haven't called it on this new, second instance.
Just get rid of the second form = SearchForm(request.POST)
and all should be well.
Integers:
int value = 100000;
String.format("%,d", value); // outputs 100,000
Doubles:
double value = 21403.3144d;
String.format("%,.2f", value); // outputs 21,403.31
String.format is pretty powerful.
- Edited per psuzzi feedback.
I faced this error when I created second activity in my project in the newly updated Android Studio,I solved it simply by copy pasting the whole xml code from first layout to the second and then I just removed the code that's unnecessary.
Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:
public function foo(Request $request){
$bodyContent = $request->getContent();
}
I removed the float from the second div to make it work.
QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.
The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)
If your bound property is DateTime, then all you need is
Binding={Property, StringFormat=d}
Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on
HTML
<div ng-controller="ControllerZero">
<input ng-model="message" >
<button ng-click="handleClick(message);">BROADCAST</button>
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
<my-component ng-model="message"></my-component>
JS
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on
myModule.directive('myComponent', function(mySharedService) {
return {
restrict: 'E',
controller: function($scope, $attrs, mySharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'Directive: ' + mySharedService.message;
});
},
replace: true,
template: '<input>'
};
});
And here three our controllers where ControllerZero
used as trigger to invoke prepForBroadcast
function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
The ControllerOne
and ControllerTwo
listen message
change by using $scope.$on
handler.
There seems to be a 'text-stroke' property, but (at least for me) it only works in Safari.
I run this
var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);
$.ajax({
type: 'GET',
url: 'linkserverApi',
success: function(success) {
console.log('Success!');
console.log(success);
},
error: function() {
console.log('Uh Oh!');
},
jsonp: 'jsonp'
});
And edit header in the response
'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'
'Access-Control-Max-Age' , '3628800'
'Access-Control-Allow-Origin', 'websiteresponseUrl'
'Content-Type', 'text/javascript; charset=utf8'
An ID is meant to identify the element uniquely. Any styles applied to it should also be unique to that element. If you have styles you want to apply to many elements, you should add a class to them all, rather than relying on ID selectors...
<div id="sections">
<div id="s1" class="sec">...</div>
<div id="s2" class="sec">...</div>
...
</div>
and
.sec {
...
}
Or in your specific case you could select all divisions inside your parent container, if nothing else is inside it, like so:
#sections > div {
...
}
encodeURIComponent()
Converts the input into a URL-encoded string
encodeURI()
URL-encodes the input, but assumes a full URL is given, so returns a valid URL by not encoding the protocol (e.g. http://) and host name (e.g. www.stackoverflow.com).
decodeURIComponent()
and decodeURI()
are the opposite of the above
You don't mention if the columns are nullable. If they are and you want the same semantics that the AVG
aggregate provides you can do (2008)
SELECT *,
(SELECT AVG(c)
FROM (VALUES(R1),
(R2),
(R3),
(R4),
(R5)) T (c)) AS [Average]
FROM Request
The 2005 version is a bit more tedious
SELECT *,
(SELECT AVG(c)
FROM (SELECT R1
UNION ALL
SELECT R2
UNION ALL
SELECT R3
UNION ALL
SELECT R4
UNION ALL
SELECT R5) T (c)) AS [Average]
FROM Request
JFrame
is the window; it can have one or more JPanel
instances inside it. JPanel
is not the window.
You need a Swing tutorial:
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
I'll make a strong suggestion for rvm.
It's a great way to manage multiple Rubies and gems sets without colliding with the system version.
I'll add that now (4/2/2013), I use rbenv a lot, because my needs are simple. RVM is great, but it's got a lot of capability I never need, so I have it on some machines and rbenv on my desktop and laptop. It's worth checking out both and seeing which works best for your needs.
I found this problem in the latest Chrome as well as the latest Safari on the Mac OS X as of Mar 17, 2016. None of the fixes above worked for me, including assigning src to empty and then back to some site, or adding in some randomly-named "name" parameter, or adding in a random number on the end of the URL after the hash, or assigning the content window href to the src after assigning the src.
In my case, it was because I was using Javascript to update the IFRAME, and only switching the hash in the URL.
The workaround in my case was that I created an interim URL that had a 0 second meta redirect to that other page. It happens so fast that I hardly notice the screen flash. Plus, I made the background color of the interim page the same as the other page, and so you notice it even less.
The difference is subtle.
In JavaScript an undefined
variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a;
for instance, then a
will be undefined
, because it was never assigned any value.
But if you then assign a = null;
then a
will now be null
. In JavaScript null
is an object (try typeof null
in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined
is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional
parameter doSomething(1, 2) then
optional will be the "three"
string but if you pass doSomething(1, 2, null)
then optional will be null
.
As for the equal ==
and strictly equal ===
comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0"
will return true; while 0 === "0"
will return false, because a number is not a string.
You may use those operators to check between undefined
an null
. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
A bit late in the game but just in case it helps anyone.
If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).
The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.
I got the url above from PayPal's tech support.
Tested using a simple Hosted button and IPN. Good luck.
class ShowDateTime extends React.Component {
constructor() {
super();
this.state = {
curTime : null
}
}
componentDidMount() {
setInterval( () => {
this.setState({
curTime : new Date().toLocaleString()
})
},1000)
}
render() {
return(
<div>
<h2>{this.state.curTime}</h2>
</div>
);
}
}
I had a similar issue while working with Jupyter. I was trying to copy files from one directory to another using copy function of shutil. The problem was that I had forgotten to import the package.(Silly) But instead of python giving import error, it gave this error.
Solved by adding:
from shutil import copy
First you'll need to get it into a byte[]
, so do this:
byte[] ba = Encoding.Default.GetBytes("sample");
and then you can get the string:
var hexString = BitConverter.ToString(ba);
now, that's going to return a string with dashes (-
) in it so you can then simply use this:
hexString = hexString.Replace("-", "");
to get rid of those if you want.
NOTE: you could use a different Encoding
if you needed to.
This works for me:
String generateUniqueFileName() {
String filename = "";
long millis = System.currentTimeMillis();
String datetime = new Date().toGMTString();
datetime = datetime.replace(" ", "");
datetime = datetime.replace(":", "");
String rndchars = RandomStringUtils.randomAlphanumeric(16);
filename = rndchars + "_" + datetime + "_" + millis;
return filename;
}
// USE:
String newFile;
do{
newFile=generateUniqueFileName() + "." + FileExt;
}
while(new File(basePath+newFile).exists());
Output filenames should look like :
2OoBwH8OwYGKW2QE_4Sep2013061732GMT_1378275452253.Ext
You can use not(expression)
function
not()
is a function in xpath (as opposed to an operator)
Example:
//a[not(contains(@id, 'xx'))]
OR
expression != true()
I just used a model variable to show/hide the dialog and removed the data-dismiss="alert"
Example:
<div data-ng-show="vm.result == 'error'" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-ng-click="vm.result = null" aria-hidden="true">×</button>
<strong>Error ! </strong>{{vm.exception}}
</div>
works for me and stops the need to go out to jquery
I think the best first approach is to make sure to turn on detailed error messages via your web.config file, like this:
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed"></httpErrors>
</system.webServer>
</configuration>
After doing this, you should get a more detailed error message from the server.
In my particular case, the more detailed error pointed out that my <defaultDocument>
section of the web.config file was not allowed at the folder level where I'd placed my web.config. It said
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". "
This has been answered for the most part, but I will expand...
Step 1
My goal was to enable zoom at certain times, and disable it at others.
// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');
// ...later...
// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');
Step 2
The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...
It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.
// after updating viewport tag, force the page to pick up changes
document.body.style.opacity = .9999;
setTimeout(function(){
document.body.style.opacity = 1;
}, 1);
Step 3
My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).
// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;
I hope this helps somebody. I spent several hours banging my mouse before finding a solution.
& is bitwise AND operator comparing bits of each operand.
For example,
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.
I encountered a similar problem with glassfish application server and Oracle JDK/JRE but not in Open JDK/JRE.
When connecting to a SSL domain I always ran into:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
...
Caused by: java.io.EOFException: SSL peer shut down incorrectly
The solution for me was to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files because the server only understood certificates that are not included in Oracle JDK by default, only OpenJDK includes them. After installing everything worked like charme.
JCE 7: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JCE 8: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
use css :
p { margin:0 }
Try this wonderful plugin http://www.getfirebug.com :)
EDIT: Firebug is now closed as a project, it was migrated to https://www.mozilla.org/en-US/firefox/developer
After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home
This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.
Hope this helps.
The short version is that you cannot use variable-width patterns in lookbehinds using Python's re
module. There is no way to change this:
>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
re.sub("(?<=fo+)bar(?=baz)", "quux", string)
File "C:\Development\Python25\lib\re.py", line 150, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "C:\Development\Python25\lib\re.py", line 241, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:
>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)
This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.
Starting with Jackson 2.6, a property can be marked as read- or write-only. It's simpler than hacking the annotations on both accessors and keeps all the information in one place:
public class User {
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
}
Excluding unwanted Manifest entries fixed the MainClass file not found error in a Gradle build jar file.
jar{
exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
from {
-----
}
}
The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:
<VirtualHost 111.22.33.55>
DocumentRoot /www/subdomain
ServerName www.domain.tld
ServerAlias *.domain.tld
</VirtualHost>
However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.
From your description, what you probably want is os.Readdirnames.
func (f *File) Readdirnames(n int) (names []string, err error)
Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.
...
If n <= 0, Readdirnames returns all the names from the directory in a single slice.
Snippet:
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
names, err := file.Readdirnames(0)
if err != nil {
return err
}
fmt.Println(names)
Credit to SquattingSlavInTracksuit's comment; I'd have suggested promoting their comment to an answer if I could.
A very simple example: Split a list of full names to get a list of names, regardless of first or last
List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");
fullNames.stream()
.flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
.forEach(System.out::println);
This prints out:
Barry
Allen
Bruce
Wayne
Clark
Kent
I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:
logging {
channel default_file {
file "/var/log/named/default.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel general_file {
file "/var/log/named/general.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel database_file {
file "/var/log/named/database.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel security_file {
file "/var/log/named/security.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel config_file {
file "/var/log/named/config.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel resolver_file {
file "/var/log/named/resolver.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel xfer-in_file {
file "/var/log/named/xfer-in.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel xfer-out_file {
file "/var/log/named/xfer-out.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel notify_file {
file "/var/log/named/notify.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel client_file {
file "/var/log/named/client.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel unmatched_file {
file "/var/log/named/unmatched.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel queries_file {
file "/var/log/named/queries.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel network_file {
file "/var/log/named/network.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel update_file {
file "/var/log/named/update.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel dispatch_file {
file "/var/log/named/dispatch.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel dnssec_file {
file "/var/log/named/dnssec.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel lame-servers_file {
file "/var/log/named/lame-servers.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
category default { default_file; };
category general { general_file; };
category database { database_file; };
category security { security_file; };
category config { config_file; };
category resolver { resolver_file; };
category xfer-in { xfer-in_file; };
category xfer-out { xfer-out_file; };
category notify { notify_file; };
category client { client_file; };
category unmatched { unmatched_file; };
category queries { queries_file; };
category network { network_file; };
category update { update_file; };
category dispatch { dispatch_file; };
category dnssec { dnssec_file; };
category lame-servers { lame-servers_file; };
};
Hope this helps.
Horrible, I know, but I just couldn't help myself:
namespace ConsoleApplication2
{
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c=Convert.ToChar(adomRng.Next(48,128))).ToString(), "[A-Za-z0-9]"));
rndString += c;
}
Console.WriteLine(rndString + Environment.NewLine);
}
}
}
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
My guess is the best you can come up with is
this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
: planRec.approved_by.ToString();
Of course since you're hinting at the fact that approved_by
is an object
(which cannot equal ""), this would be rewritten as
this.approved_by = (planRec.approved_by ?? string.Empty).ToString();
You should use Comparable instead of a Comparator if a default sort is what your looking for.
See here, this may be of some help - When should a class be Comparable and/or Comparator?
Try this -
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestSort {
public static void main(String args[]){
ToSort toSort1 = new ToSort(new Float(3), "3");
ToSort toSort2 = new ToSort(new Float(6), "6");
ToSort toSort3 = new ToSort(new Float(9), "9");
ToSort toSort4 = new ToSort(new Float(1), "1");
ToSort toSort5 = new ToSort(new Float(5), "5");
ToSort toSort6 = new ToSort(new Float(0), "0");
ToSort toSort7 = new ToSort(new Float(3), "3");
ToSort toSort8 = new ToSort(new Float(-3), "-3");
List<ToSort> sortList = new ArrayList<ToSort>();
sortList.add(toSort1);
sortList.add(toSort2);
sortList.add(toSort3);
sortList.add(toSort4);
sortList.add(toSort5);
sortList.add(toSort6);
sortList.add(toSort7);
sortList.add(toSort8);
Collections.sort(sortList);
for(ToSort toSort : sortList){
System.out.println(toSort.toString());
}
}
}
public class ToSort implements Comparable<ToSort> {
private Float val;
private String id;
public ToSort(Float val, String id){
this.val = val;
this.id = id;
}
@Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
@Override
public String toString(){
return this.id;
}
}
FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:
String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
=> will produce "oau"
That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
You might want to add name for the unique key as many times the default unique_key name by rails can be too long for which the DB can throw the error.
To add name for your index just use the name:
option.
The migration query might look something like this -
add_index :table_name, [:column_name_a, :column_name_b, ... :column_name_n], unique: true, name: 'my_custom_index_name'
More info - http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
You can use inverse the order of elements in HTML. Then besides using order
as in Michael_B's answer you can use flex-direction: row-reverse;
or flex-direction: column-reverse;
depending on your layout.
Working sample:
.flex {_x000D_
display: flex;_x000D_
flex-direction: row-reverse;_x000D_
/* Align content at the "reversed" end i.e. beginning */_x000D_
justify-content: flex-end;_x000D_
}_x000D_
_x000D_
/* On hover target its "previous" elements */_x000D_
.flex-item:hover ~ .flex-item {_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
/* styles just for demo */_x000D_
.flex-item {_x000D_
background-color: orange;_x000D_
color: white;_x000D_
padding: 20px;_x000D_
font-size: 3rem;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div class="flex">_x000D_
<div class="flex-item">5</div>_x000D_
<div class="flex-item">4</div>_x000D_
<div class="flex-item">3</div>_x000D_
<div class="flex-item">2</div>_x000D_
<div class="flex-item">1</div>_x000D_
</div>
_x000D_
I'm assuming you're using express
, given the logs you have in your question. The key is to set the timeout
property on server (the following sets the timeout to one second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;
If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:
var http = require('http');
var server = http.createServer(function (req, res) {
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}, 200);
}).listen(1337, '127.0.0.1');
server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');
As mentioned by Seeker, the problem could have been that you setup the click()
function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.
An important point is to run such scripts after the document is ready. This is done by placing the click()
initialization within that other function as in:
jQuery(document).ready(function()
{
jQuery("body").click(function()
{
// ... your click code here ...
});
});
This is usually the best method, especially if you include your JavaScript code in your <head>
tag. If you include it at the very bottom of the page, then the ready()
function is less important, but it may still be useful.
To find where the name google clashes .... try this:
python3
then >>> help('google')
... I got info about google-auth:
NAME
google
PACKAGE CONTENTS
auth (package)
oauth2 (package)
Also then try
pip show google-auth
Then
sudo pip3 uninstall google-auth
... and re-try >>> help('google')
I then see protobuf:
NAME
google
PACKAGE CONTENTS
protobuf (package)
Joel Spolsky wrote a good blog post about this. http://www.joelonsoftware.com/articles/Wrong.html Basically it comes down to not making your code harder to read when a decent IDE will tell you want type the variable is if you can't remember. Also, if you make your code compartmentalized enough, you don't have to remember what a variable was declared as three pages up.
Just follow 3 steps
Enable mode_rewrite using following command
sudo a2enmod rewrite
Password will be asked. So enter your password
Update your 000-default.conf or default.conf file located at /etc/apache2/sites-available/ directory. you can not edit it directly. so use following command to open
sudo gedit /etc/apache2/sites-available/000-default.conf
Or sudo gedit /etc/apache2/sites-available/default.conf
you will get
DocumentRoot /var/www/html
OR
DocumentRoot /var/www
line. Add following code after it.
<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Make user the directory tag path is same as shown in your file.
Restart your apache server using following command
sudo service apache2 restart
We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.
For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON). That is one problem where you could use JSON perhaps.
Here is something practical: Yahoo JSON
Using Excel 2010 x64
. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:
Swap the data columns, to end with X_data in column A and Y_data in column B.
My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me:
an Excel XY plot literally wants {x,y}
pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away.
For me an XY plot means Y=f(X)
plotted.
By.cssSelector(".ban")
or By.cssSelector(".hot")
or By.cssSelector(".ban.hot")
should all select it unless there is another element that has those classes.
In CSS, .name
means find an element that has a class with name
. .foo.bar.baz
means to find an element that has all of those classes (in the same element).
However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.
You can't databind to a property and then explictly assign a value to the databound property.
In place of 1.+ use the latest version of crashlytics -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
}
you should use this way -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
}
your problem will be resolved for sure. Happy coding !!
You can use:
return View("../Category/NotFound", model);
It was tested in ASP.NET MVC 3, but should also work in ASP.NET MVC 2.
from "man 1 passwd
":
--stdin
This option is used to indicate that passwd should read the new
password from standard input, which can be a pipe.
So in your case
adduser "$1"
echo "$2" | passwd "$1" --stdin
[Update] a few issues were brought up in the comments:
Your passwd
command may not have a --stdin
option: use the chpasswd
utility instead, as suggested by ashawley.
If you use a shell other than bash, "echo" might not be a builtin command,
and the shell will call /bin/echo
. This is insecure because the password
will show up in the process table and can be seen with tools like ps
.
In this case, you should use another scripting language. Here is an example in Perl:
#!/usr/bin/perl -w
open my $pipe, '|chpasswd' or die "can't open pipe: $!";
print {$pipe} "$username:$password";
close $pipe
display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.
Sample text:
Clinton said
Bush used crayons
Reagan forgot
Just omitting a Bush match:
$ perl -ne 'print if /^(Clinton|Reagan)/' textfile
Clinton said
Reagan forgot
Or if you really want to specify:
$ perl -ne 'print if /^(?!Bush)(Clinton|Reagan)/' textfile
Clinton said
Reagan forgot
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
As Commodore Jaeger alluded to, I don't think any of the other answers actually answer this question; the question asks how to repeat a string, not a character.
While the answer given by Commodore is correct, it is quite inefficient. Here is a faster implementation, the idea is to minimise copying operations and memory allocations by first exponentially growing the string:
#include <string>
#include <cstddef>
std::string repeat(std::string str, const std::size_t n)
{
if (n == 0) {
str.clear();
str.shrink_to_fit();
return str;
} else if (n == 1 || str.empty()) {
return str;
}
const auto period = str.size();
if (period == 1) {
str.append(n - 1, str.front());
return str;
}
str.reserve(period * n);
std::size_t m {2};
for (; m < n; m *= 2) str += str;
str.append(str.c_str(), (n - (m / 2)) * period);
return str;
}
We can also define an operator*
to get something closer to the Python version:
#include <utility>
std::string operator*(std::string str, std::size_t n)
{
return repeat(std::move(str), n);
}
On my machine this is around 10x faster than the implementation given by Commodore, and about 2x faster than a naive 'append n - 1 times' solution.
in PHP json_decode convert json data into PHP associated array
For Ex: $php-array= json_decode($json-data, true);
print_r($php-array);
If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !
Easiest modern method: Alt
+Enter
on
private static final long serialVersionUID = ;
IntelliJ will underline the space after the =
. put your cursor on it and hit alt
+Enter
(Option
+Enter
on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.
Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF']
.
When using $_SERVER['PHP_SELF']
it is very easy to inject malicious data by simply appending /<script>...
after the whatever.php
part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.
The best solution would be Ctrl+Alt+I.
This is also caused (on Windows at least) by text files that have UTF-8 with BOM encoding. Changing the encoding to regular UTF-8 immediately made Git see the file as type=text
In my case clean project and rebuild works, no need to disable instant run and restart.
The solution in UIKeyboardTypeNumberPad and missing return key works great but only if there are no other non-number pad text fields on the screen.
I took that code and turned it into an UIViewController that you can simply subclass to make number pads work. You will need to get the icons from the above link.
NumberPadViewController.h:
#import <UIKit/UIKit.h>
@interface NumberPadViewController : UIViewController {
UIImage *numberPadDoneImageNormal;
UIImage *numberPadDoneImageHighlighted;
UIButton *numberPadDoneButton;
}
@property (nonatomic, retain) UIImage *numberPadDoneImageNormal;
@property (nonatomic, retain) UIImage *numberPadDoneImageHighlighted;
@property (nonatomic, retain) UIButton *numberPadDoneButton;
- (IBAction)numberPadDoneButton:(id)sender;
@end
and NumberPadViewController.m:
#import "NumberPadViewController.h"
@implementation NumberPadViewController
@synthesize numberPadDoneImageNormal;
@synthesize numberPadDoneImageHighlighted;
@synthesize numberPadDoneButton;
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if ([super initWithNibName:nibName bundle:nibBundle] == nil)
return nil;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp3.png"];
self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown3.png"];
} else {
self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp.png"];
self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown.png"];
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Add listener for keyboard display events
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
// Add listener for all text fields starting to be edited
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldDidBeginEditing:)
name:UITextFieldTextDidBeginEditingNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
}
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextFieldTextDidBeginEditingNotification
object:nil];
[super viewWillDisappear:animated];
}
- (UIView *)findFirstResponderUnder:(UIView *)root {
if (root.isFirstResponder)
return root;
for (UIView *subView in root.subviews) {
UIView *firstResponder = [self findFirstResponderUnder:subView];
if (firstResponder != nil)
return firstResponder;
}
return nil;
}
- (UITextField *)findFirstResponderTextField {
UIResponder *firstResponder = [self findFirstResponderUnder:[self.view window]];
if (![firstResponder isKindOfClass:[UITextField class]])
return nil;
return (UITextField *)firstResponder;
}
- (void)updateKeyboardButtonFor:(UITextField *)textField {
// Remove any previous button
[self.numberPadDoneButton removeFromSuperview];
self.numberPadDoneButton = nil;
// Does the text field use a number pad?
if (textField.keyboardType != UIKeyboardTypeNumberPad)
return;
// If there's no keyboard yet, don't do anything
if ([[[UIApplication sharedApplication] windows] count] < 2)
return;
UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
// Create new custom button
self.numberPadDoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.numberPadDoneButton.frame = CGRectMake(0, 163, 106, 53);
self.numberPadDoneButton.adjustsImageWhenHighlighted = FALSE;
[self.numberPadDoneButton setImage:self.numberPadDoneImageNormal forState:UIControlStateNormal];
[self.numberPadDoneButton setImage:self.numberPadDoneImageHighlighted forState:UIControlStateHighlighted];
[self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
// Locate keyboard view and add button
NSString *keyboardPrefix = [[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2 ? @"<UIPeripheralHost" : @"<UIKeyboard";
for (UIView *subView in keyboardWindow.subviews) {
if ([[subView description] hasPrefix:keyboardPrefix]) {
[subView addSubview:self.numberPadDoneButton];
[self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
break;
}
}
}
- (void)textFieldDidBeginEditing:(NSNotification *)note {
[self updateKeyboardButtonFor:[note object]];
}
- (void)keyboardWillShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}
- (void)keyboardDidShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}
- (IBAction)numberPadDoneButton:(id)sender {
UITextField *textField = [self findFirstResponderTextField];
[textField resignFirstResponder];
}
- (void)dealloc {
[numberPadDoneImageNormal release];
[numberPadDoneImageHighlighted release];
[numberPadDoneButton release];
[super dealloc];
}
@end
Enjoy.
This is possibly unrelated directly to the question; but one mistake I just made myself, and I see in the OP, is the URL specification ssh://user@server:/GitRepos/myproject.git
- namely, you have both a colon :
, and a forward slash /
after it signifying an absolute path.
I then found Git clone, ssh: Could not resolve hostname – git , development – Nicolas Kuttler (as that was the error I was getting, on git
version 1.7.9.5), noting:
The problem with the command I used initially was that I tried to use an scp-like syntax.
... which was also my problem! So basically in git
with ssh
, you either use
ssh://[email protected]/absolute/path/to/repo.git/
- just a forward slash for absolute path on server[email protected]:relative/path/to/repo.git/
- just a colon (it mustn't have the ssh://
for relative path on server (relative to home dir of username
on server machine)Hope this helps someone,
Cheers!
Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.
From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:
I Set:
.Timeout=5000
.ReadWriteTimeout=32000
The connect and post time for the HttpWebRequest took 26ms
but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.
I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.
For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.
UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;
Use:
curl -s -L URL_TO_SCRIPT_HERE | bash
For example:
curl -s -L http://bitly/10hA8iC | bash
Provided the char array is null
terminated,
char chararray[10] = { 0 };
size_t len = strlen(chararray);
For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);
If you want it to download and install from your own server then use the following code
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
startActivity(intent);
Merging several answers from above into an easy to use function
function GetScriptIfNotLoaded(scriptLocationAndName)
{
var len = $('script[src*="' + scriptLocationAndName +'"]').length;
//script already loaded!
if (len > 0)
return;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
For adding unique index following are required:
1) table_name
2) index_name
3) columns on which you want to add index
ALTER TABLE `tablename`
ADD UNIQUE index-name
(`column1` ,`column2`,`column3`,...,`columnN`);
In your case we can create unique index as follows:
ALTER TABLE `votes`ADD
UNIQUE <votesuniqueindex>;(`user` ,`email`,`address`);
My script to delete files older than a specific year :
@REM _______ GENERATE A CMD TO DELETE FILES OLDER THAN A GIVEN YEAR
@REM _______ (given in _olderthanyear variable)
@REM _______ (you must LOCALIZE the script depending on the dir cmd console output)
@REM _______ (we assume here the following line's format "11/06/2017 15:04 58 389 SpeechToText.zip")
@set _targetdir=c:\temp
@set _olderthanyear=2017
@set _outfile1="%temp%\deleteoldfiles.1.tmp.txt"
@set _outfile2="%temp%\deleteoldfiles.2.tmp.txt"
@if not exist "%_targetdir%" (call :process_error 1 DIR_NOT_FOUND "%_targetdir%") & (goto :end)
:main
@dir /a-d-h-s /s /b %_targetdir%\*>%_outfile1%
@for /F "tokens=*" %%F in ('type %_outfile1%') do @call :process_file_path "%%F" %_outfile2%
@goto :end
:end
@rem ___ cleanup and exit
@if exist %_outfile1% del %_outfile1%
@if exist %_outfile2% del %_outfile2%
@goto :eof
:process_file_path %1 %2
@rem ___ get date info of the %1 file path
@dir %1 | find "/" | find ":" > %2
@for /F "tokens=*" %%L in ('type %2') do @call :process_line "%%L" %1
@goto :eof
:process_line %1 %2
@rem ___ generate a del command for each file older than %_olderthanyear%
@set _var=%1
@rem LOCALIZE HERE (char-offset,string-length)
@set _fileyear=%_var:~0,4%
@set _fileyear=%_var:~7,4%
@set _filepath=%2
@if %_fileyear% LSS %_olderthanyear% echo @REM %_fileyear%
@if %_fileyear% LSS %_olderthanyear% echo @del %_filepath%
@goto :eof
:process_error %1 %2
@echo RC=%1 MSG=%2 %3
@goto :eof
I would recommend reading this post. There are tons of ways to use existing HttpResponse as suggested, but if you want to take advantage of Web Api 2, then look at using some of the built-in IHttpActionResult options such as
return Ok()
or
return NotFound()
If the buffer is full, all strings that is buffered on it, they will be saved onto the disk. Buffers is used for avoiding from Big Deals! and overhead.
In BufferedWriter class that is placed in java libs, there is a one line like:
private static int defaultCharBufferSize = 8192;
If you do want to send data before the buffer is full, you do have control. Just Flush It. Calls to writer.flush() say, "send whatever's in the buffer, now!
reference book: https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208
pages:453
There is different ways to make dropdown menu using css. Here is simple code.
HTML Code
<label class="dropdown">
<div class="dd-button">
Dropdown
</div>
<input type="checkbox" class="dd-input" id="test">
<ul class="dd-menu">
<li>Dropdown 1</li>
<li>Dropdown 2</li>
</ul>
</label>
CSS Code
body {
color: #000000;
font-family: Sans-Serif;
padding: 30px;
background-color: #f6f6f6;
}
a {
text-decoration: none;
color: #000000;
}
a:hover {
color: #222222
}
/* Dropdown */
.dropdown {
display: inline-block;
position: relative;
}
.dd-button {
display: inline-block;
border: 1px solid gray;
border-radius: 4px;
padding: 10px 30px 10px 20px;
background-color: #ffffff;
cursor: pointer;
white-space: nowrap;
}
.dd-button:after {
content: '';
position: absolute;
top: 50%;
right: 15px;
transform: translateY(-50%);
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid black;
}
.dd-button:hover {
background-color: #eeeeee;
}
.dd-input {
display: none;
}
.dd-menu {
position: absolute;
top: 100%;
border: 1px solid #ccc;
border-radius: 4px;
padding: 0;
margin: 2px 0 0 0;
box-shadow: 0 0 6px 0 rgba(0,0,0,0.1);
background-color: #ffffff;
list-style-type: none;
}
.dd-input + .dd-menu {
display: none;
}
.dd-input:checked + .dd-menu {
display: block;
}
.dd-menu li {
padding: 10px 20px;
cursor: pointer;
white-space: nowrap;
}
.dd-menu li:hover {
background-color: #f6f6f6;
}
.dd-menu li a {
display: block;
margin: -10px -20px;
padding: 10px 20px;
}
.dd-menu li.divider{
padding: 0;
border-bottom: 1px solid #cccccc;
}
More css code example
There's
Arrays.fill(myArray, null);
Not that it does anything different than you'd do on your own (it just loops through every element and sets it to null). It's not native in that it's pure Java code that performs this, but it is a library function if maybe that's what you meant.
This of course doesn't allow you to resize the array (to zero), if that's what you meant by
"empty". Array sizes are fixed, so if you want the "new" array to have different dimensions you're best to just reassign the reference to a new array as the other answers demonstrate. Better yet, use a List
type like an ArrayList
which can have variable size.
I always use READ UNCOMMITTED now. It's fast with the least issues. When using other isolations you will almost always come across some Blocking issues.
As long as you use Auto Increment fields and pay a little more attention to inserts then your fine, and you can say goodbye to blocking issues.
You can make errors with READ UNCOMMITED but to be honest, it is very easy make sure your inserts are full proof. Inserts/Updates which use the results from a select are only thing you need to watch out for. (Use READ COMMITTED here, or ensure that dirty reads aren't going to cause a problem)
So go the Dirty Reads (Specially for big reports), your software will run smoother...
In version 2.1.1 this works :
$('#calendar').fullCalendar({
// your calendar settings...
});
$('#calendar').fullCalendar('gotoDate', '2014-05-01');
Documentation about moment time/date format : http://fullcalendar.io/docs/utilities/Moment/ Documentation about the upgrades in version 2 : https://github.com/arshaw/fullcalendar/wiki/Upgrading-to-v2
Based on Farhan Sahibole's answer:
header('Content-Disposition: attachment; filename=Image.png');
header('Content-Type: application/octet-stream'); // Downloading on Android might fail without this
ob_clean();
readfile($file);
This is all I needed for this to work. I stripped off anything that isn't required for this to work.
Key is to use ob_clean();
You can now use OrderedDict
in Python 2.7 as well:
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
... ('second', 2),
... ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
Here you have the what's new page for 2.7 version and the OrderedDict API.
SSH doesn't use the :
syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config
file and add:
Host git.host.de Port 4019
Then specify just git.host.de
without a port number.
While this is sort of a follow up to the previous answer, it adds a little (hopefully).
Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3
.
So if we think about that like this: move origin to 10, 3
, then draw rectangle at 0, 0
.
Then all we have to do is add a rotate in between.
Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.
We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).
I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.
var font, lineHeight, x, y;
x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';
// Right Aligned
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
The line this.context.fillText('right', 0, lineHeight / 2);
is basically 0, 0
, except we move slightly for the text to be centered near the point
Because when you access a static field, you should do so on the class (or in this case the enum). As in
MyUnits.MILLISECONDS;
Not on an instance as in
m.MILLISECONDS;
Edit To address the question of why: In Java, when you declare something as static
, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.
I think you'll have to import the project via the file->import wizard:
http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse
It's not the last step, but it will start you on your way.
I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).
import pickle
intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()
Test your pickle quickly. pickle is a part of standard python library and available by default.
In codeigniter we are able to store session values in a database.
In the config.php file make the sess_use_database variable true
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
and create a ci_session table in the database
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
For more details and reference, click here
Use single forward slash and always type the path manually. For example:
FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");
2.3.5 did not have input tap
, just input keyevent
and input text
You can use the monkeyrunner for it: (this is a copy of the answer at https://stackoverflow.com/a/18959385/1587329):
You might want to use monkeyrunner like this:
$ monkeyrunner
>>> from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
>>> device = MonkeyRunner.waitForConnection()
>>> device.touch(200, 400, MonkeyDevice.DOWN_AND_UP)
You can also do a drag, start activies etc. Have a look at the api for MonkeyDevice.
Add the following line:
request.UseDefaultCredentials = true;
This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.
It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
Hope this helps.
I was recently presented with this same challenge and stumbled on this thread but found a simpler solution using append...
var firstname = $('#firstname').val();
$('ol').append( '<li>' + firstname + '</li>' );
Store the firstname value and then use append
to add that value as an li
to the ol
. I hope this helps :)
$(dialogElement).empty();
$(dialogElement).remove();
this fixes it for real
If you want to UPDATE a tag, let's say it 1.0.0
git checkout 1.0.0
git ci -am 'modify some content'
git tag -f 1.0.0
git push origin --delete 1.0.0
git push origin 1.0.0
DONE
I will repeat what the others said, but will just try to make it simpler...
First, just create the Interface class
public interface PostTaskListener<K> {
// K is the type of the result object of the async task
void onPostTask(K result);
}
Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.
public static class LoadData extends AsyncTask<Void, Void, String> {
private PostTaskListener<String> postTaskListener;
protected LoadData(PostTaskListener<String> postTaskListener){
this.postTaskListener = postTaskListener;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null && postTaskListener != null)
postTaskListener.onPostTask(result);
}
}
Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:
...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
@Override
public void onPostTask(String result) {
//Your post execution task code
}
}
// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);
Done!
[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
string[] formats = { "MM/dd/yyyy" };
DateTime parsedDateTime;
return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
DateTimeStyles.None, out parsedDateTime);
}
Simply specify the date time formats that you wish to accept in the array named formats.
changing the Binding Type from wsHttpbinding to basichttp binding in the endpoint tag and from wsHttpbinding to mexhttpbinginding in metadata endpoint tag helped to overcome the error. Thank you...
It is usually a good idea to declare variables as unsigned
or size_t
if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type
when comparing with a std::string
's length).
Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:
unsigned u = GetSomeUnsignedValue();
int i = GetSomeSignedValue();
if (i >= 0)
{
// i is nonnegative, so it is safe to cast to unsigned value
if ((unsigned)i >= u)
iIsGreaterThanOrEqualToU();
else
iIsLessThanU();
}
else
{
iIsNegative();
}
JSON.stringify(data).length return string length not Object length, you can use Object.keys.
<% for(var i=0; i < Object.keys(data).length ; i++) {%>
I had the same problem with a Google Docs URL. Enclosing the URL in quotes did the trick for me:
wget "https://docs.google.com/spreadsheets/export?format=tsv&id=1sSi9f6m-zKteoXA4r4Yq-zfdmL4rjlZRt38mejpdhC23" -O sheet.tsv
You can this query:
pip install image
I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.
As devio says there is no way to simply edit a UDT if it's in use.
A work-round through SMS that worked for me was to generate a create script and make the appropriate changes; rename the existing UDT; run the create script; recompile the related sprocs and drop the renamed version.
Firebase.remove()
like probably most Firebase methods is asynchronous, thus you have to listen to events to know when something happened:
parent = ref.parent()
parent.on('child_removed', function (snapshot) {
// removed!
})
ref.remove()
According to Firebase docs it should work even if you lose network connection. If you want to know when the change has been actually synchronized with Firebase servers, you can pass a callback function to Firebase.remove
method:
ref.remove(function (error) {
if (!error) {
// removed!
}
}
I had the same problem. I am using Python and Eclipse on Windows. The code was running just fine, but eclipse show errors everywhere. After I changed the name of the folder 'Lib' to 'lib' (C:\Python27\lib), the problem was solved. It seems that if the capitalization of the letters doesn't match the one in the configuration file, this will sometimes cause problems (but it seems like not always, because the error checking was fine for long time before the problems suddenly appeared for no obvious reason).
Run these two commands from the terminal to set User email and Name
git config --global user.email "[email protected]"
git config --global user.name "your name"
You can use array_walk
to apply your preg_match
function to each element of the array.
In may case, I nedded to copy the gacutil.exe, gacutil.exe.config AND ALSO the gacutlrc.dll (from the 1033 directory)
Here is a quick way to convert the hash of connected sockets from a namespace into an array using ES6 generators (applies to socket.io >= v1.0.0):
io.on('connection', function(socket) {
var hash = io.of('/').connected
var list = null
hash[Symbol.iterator] = function*() {
// for..of loop to invoke Object.keys() default iterator
// to get the array values instead of the keys
for(var id of Object.keys(hash)) yield hash[id]
}
list = [...hash]
console.log(Array.isArray(list)) // true
})
If you get a
sudo: add-apt-repository: command not found
then you need to run the following command
sudo apt-get install software-properties-common python-software-properties
If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").
It makes a nice clean list of file names.
new string (str.OrderBy(c => c).ToArray())
Increase the width and height of view's frame with border width before adding the border:
float borderWidth = 2.0f
CGRect frame = self.frame;
frame.width += borderWidth;
frame.height += borderWidth;
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = 2.0f;
Try this.
20 4 * * *
Check the below Screenshot
Referred URL - https://www.lenar.io/jenkins-schedule-build-periodically/
try pcregrep
instead of regular grep
:
pcregrep -M "pattern1.*\n.*pattern2" filename
the -M
option allows it to match across multiple lines, so you can search for newlines as \n
.
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
Go to VCS>Git>Remotes then remove your remote url from the list and add again. Git will ask for a password after next git operation (push, pull, etc). NOTE: Don't forget to specify username in url or you will get auth error.
This:
https://github.com/jbtule/cdto#cd-to
It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.
Edit: See Sebastien Lorber's answer which fixes a bug in my implementation.
Use the onInput event, and optionally onBlur as a fallback. You might want to save the previous contents to prevent sending extra events.
I'd personally have this as my render function.
var handleChange = function(event){
this.setState({html: event.target.value});
}.bind(this);
return (<ContentEditable html={this.state.html} onChange={handleChange} />);
Which uses this simple wrapper around contentEditable.
var ContentEditable = React.createClass({
render: function(){
return <div
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable
dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
},
shouldComponentUpdate: function(nextProps){
return nextProps.html !== this.getDOMNode().innerHTML;
},
emitChange: function(){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
target: {
value: html
}
});
}
this.lastHtml = html;
}
});
It works for me when I define the complete border
property. (JSFiddle here)
.field_set{
border: 1px #F00 solid;
}?
the reason is the border-style
that is set to none
by default for fieldsets. You need to override that as well.
You can find the default Android menu icons here - link is broken now.
Update: You can find Material Design icons here.
I think you're looking for a method like this:
public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
var enum1 = seq1.GetEnumerator();
var enum2 = seq2.GetEnumerator();
while (enum1.MoveNext() && enum2.MoveNext())
{
yield return comparer(enum1.Current, enum2.Current);
}
}
It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.
This solution of course assumes that you want to compare the nth item of seq1
with the nth item in seq2
. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join
. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.
Edit:
Here's an example of how you might use the CompareSequences
method with the comparer function you originally posted.
// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;
foreach(var element in results)
{
Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}
Playing with the tsconfig.json You can also targeting es5 like this :
{
"compilerOptions": {
"experimentalDecorators": true,
"module": "commonjs",
"target": "es5"
}
...
I like Spyder, it has many tools, such as profiling, intelligent indentation helper and a good autocompletion support
Pyjnius.
Docs: http://pyjnius.readthedocs.org/en/latest/
Github: https://github.com/kivy/pyjnius
From the github page:
A Python module to access Java classes as Python classes using JNI.
PyJNIus is a "Work In Progress".
Quick overview
>>> from jnius import autoclass >>> autoclass('java.lang.System').out.println('Hello world') Hello world >>> Stack = autoclass('java.util.Stack') >>> stack = Stack() >>> stack.push('hello') >>> stack.push('world') >>> print stack.pop() world >>> print stack.pop() hello
You can use the function numpy.nonzero()
, or the nonzero()
method of an array
import numpy as np
A = np.array([[2,4],
[6,2]])
index= np.nonzero(A>1)
OR
(A>1).nonzero()
Output:
(array([0, 1]), array([1, 0]))
First array in output depicts the row index and second array depicts the corresponding column index.
Here is another simple way to do it
<a class="nav-link"
href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>
Where is @Model.ID
is a parameter
And here there is a second example.
<a class="nav-link"
href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2¶m3=ViewBag.P3'>Print</a>
If you set SELinux in permissive mode (command setenforce 0
) and it works (worked for me) then you can run restorecon (sudo restorecon -Rv /var/www/html/
) which set the correct context to the files in Apache directory permanently because setenforce is temporal. The context for Apache is httpd_sys_content_t
and you can verify it running the command ls -Z /var/www/html/
that outputs something like:
-rwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 index.html
In case the file does not have the right context, appear something like this:
drwxr-xr-x. root root unconfined_u:object_r:user_home_t:s0 tests
Hope it can help you.
PD: excuse me my English
You could use:
Dim MyForm As New Form1
MyForm.Show()
or rather:
MyForm.ShowDialog()
to open the form as a dialog box to ensure that user interacts with the new form or closes it.
I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)
Background image is not Set Perfect then his css is problem create so his css file change to below code
html { _x000D_
background-image: url("example.png"); _x000D_
background-repeat: no-repeat; _x000D_
background-position: 0% 0%;_x000D_
background-size: 100% 100%;_x000D_
}
_x000D_
%; background-size: 100% 100%;"
A file object is an instance of Blob but a blob object is not an instance of File
new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true
new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false
new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
console.log(blob);
};
reader.readAsArrayBuffer(file);
As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
file.arrayBuffer().then((arrayBuffer) => {
let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
console.log(blob);
});
If your environment supports async/await you can use a one-liner like below
let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));
Using JNA, supporting old and new JVM to get process id
public static long getProcessId(Process p){
long pid = -1;
try {
pid = p.pid();
} catch (NoSuchMethodError e) {
try
{
//for windows
if (p.getClass().getName().equals("java.lang.Win32Process") || p.getClass().getName().equals("java.lang.ProcessImpl")) {
Field f = p.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(p);
Kernel32 kernel = Kernel32.INSTANCE;
WinNT.HANDLE hand = new WinNT.HANDLE();
hand.setPointer(Pointer.createConstant(handl));
pid = kernel.GetProcessId(hand);
f.setAccessible(false);
}
//for unix based operating systems
else if (p.getClass().getName().equals("java.lang.UNIXProcess"))
{
Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
pid = f.getLong(p);
f.setAccessible(false);
}
}
catch(Exception ex)
{
pid = -1;
}
}
return pid;
}
I had the same problem and changed my configuration in application-test.properties to this:
#Test Properties
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
And my dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.198</version>
<scope>test</scope>
</dependency>
And the annotations used on test class:
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
public class CommentServicesIntegrationTests {
...
}
One thing I've noticed that I don't see in the documentation is using
background: url("image.png")
short hand like above if the image is not found it sends a 302 code instead of being ignored like it is if you use
background-image: url("image.png")
just remove s from the permission you are using sss you have to use ss
One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth
element normal way will not work.
example:
std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";
std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
if(index==k) break;
cout<<*itr++<<" ";
index++;
}
First give or check permissions like
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
If these two permissions are OK, then check your output streams are in correct format.
Example:
FileOutputStream fos=new FileOutputStream(Environment.getExternalStorageDirectory()+"/rahul1.jpg");
An optional parameter is just tagged with an attribute. This attribute tells the compiler to insert the default value for that parameter at the call-site.
The call obj2.TestMethod();
is replaced by obj2.TestMethod(false);
when the C# code gets compiled to IL, and not at JIT-time.
So in a way it's always the caller providing the default value with optional parameters. This also has consequences on binary versioning: If you change the default value but don't recompile the calling code it will continue to use the old default value.
On the other hand, this disconnect means you can't always use the concrete class and the interface interchangeably.
You already can't do that if the interface method was implemented explicitly.
const foo = 'bar';
console.log(!!foo); // Boolean: true
_x000D_
! negates (inverts) a value AND always returns/ produces a boolean. So !'bar' would yield false (because 'bar' is truthy => negated + boolean = false). With the additional ! operator, the value is negated again, so false becomes true.
Of course, Insert
or AddFirst
will do the trick, but you could always do:
myList.Reverse();
myList.Add(item);
myList.Reverse();
For those who are learning node/express (just like me): do not use wildcard routing if possible!
I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.
More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/
Try the following:
document.getElementById("successAndErrorMessages").innerHTML="someContent";
msdn link for detail : innerHTML Property
Here' a good tool from a documented and very famous npm library that does the xml <-> js conversions very well: differently from some (maybe all) of the above proposed solutions, it converts xml comments also.
var obj = {name: "Super", Surname: "Man", age: 23};
var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);
You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.
Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)
follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
Add authorization header and click pencil button to enter username and passwords
You can place your folder in the root of the ServletContext.
Then specify a relative or absolute path to this directory in application.yml:
spring:
resources:
static-locations: file:some_temp_files/
The resources in this folder will be available (for downloading, for example) at:
http://<host>:<port>/<context>/your_file.csv
I'm quite mechanical thinking. Here are the basics...
Swift 4 Swift 5
let t = "abracadabra"
let start1 = t.index(t.startIndex, offsetBy:0)
let end1 = t.index(t.endIndex, offsetBy:-5)
let start2 = t.index(t.endIndex, offsetBy:-5)
let end2 = t.index(t.endIndex, offsetBy:0)
let t2 = t[start1 ..< end1]
let t3 = t[start2 ..< end2]
//or a shorter form
let t4 = t[..<end1]
let t5 = t[start2...]
print("\(t2) \(t3) \(t)")
print("\(t4) \(t5) \(t)")
// result:
// abraca dabra abracadabra
The result is a substring, meaning that it is a part of the original string. To get a full blown separate string just use e.g.
String(t3)
String(t4)
This is what I use:
let mid = t.index(t.endIndex, offsetBy:-5)
let firstHalf = t[..<mid]
let secondHalf = t[mid...]
Inserting date in sql
insert
into tablename (timestamp_value)
values ('dd-mm-yyyy hh-mm-ss AM');
If suppose we wanted to insert system date
insert
into tablename (timestamp_value)
values (sysdate);
You can use a simple if
statement instead of continue. So instead of the way you have your code, you can try:
try(Stream<String> lines = Files.lines(path, StandardCharsets.ISO_8859_1)){
filteredLines = lines.filter(...).foreach(line -> {
...
if(!...) {
// Code you want to run
}
// Once the code runs, it will continue anyway
});
}
The predicate in the if statement will just be the opposite of the predicate in your if(pred) continue;
statement, so just use !
(logical not).
HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");
if the filename is generating dynamically then how to define filename here, it is generating through guid here.
start = datetime.now()
#code for which response time need to be measured.
end = datetime.now()
dif = end - start
dif_micro = dif.microseconds # time in microseconds
dif_millis = dif.microseconds / 1000 # time in millisseconds
This example let may highlight the differ between "at" and "asterix" while we using them. I declared two arrays "fruits" and "vegetables"
fruits=(apple pear plumm peach melon)
vegetables=(carrot tomato cucumber potatoe onion)
printf "Fruits:\t%s\n" "${fruits[*]}"
printf "Fruits:\t%s\n" "${fruits[@]}"
echo + --------------------------------------------- +
printf "Vegetables:\t%s\n" "${vegetables[*]}"
printf "Vegetables:\t%s\n" "${vegetables[@]}"
See the following result the code above:
Fruits: apple pear plumm peach melon
Fruits: apple
Fruits: pear
Fruits: plumm
Fruits: peach
Fruits: melon
+ --------------------------------------------- +
Vegetables: carrot tomato cucumber potatoe onion
Vegetables: carrot
Vegetables: tomato
Vegetables: cucumber
Vegetables: potatoe
Vegetables: onion
Added to Alister, you can edit the crontab usually (not always the case) by entering crontab -e in a ssh session on the server.
The stars represent (* means every of this unit):
[Minute] [Hour] [Day] [Month] [Day of week (0 =sunday to 6 =saturday)] [Command]
You could read some more about this here.