Your data
is a string of '[{}]'
at that point in time, you can eval
it like so:
function(data) {
data = eval( '(' + data + ')' )
}
However this method is far from secure, this will be a bit more work but the best practice is to parse it with Crockford's JSON parser: https://github.com/douglascrockford/JSON-js
Another method would be $.getJSON
and you'll need to set the dataType
to json for a pure jQuery reliant method.
You can pass this
to each block. See here: http://jsfiddle.net/yR7TZ/1/
{{#each this}}
<div class="row"></div>
{{/each}}
It looks like there is no difference, for
uses each
underneath.
$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
from (irb):4
Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment
for .. in ..
sets the iterator outside the scope of the loop, so
for a in [1,2]
puts a
end
leaves a
defined after the loop is finished. Where as each
doesn't. Which is another reason in favor of using each
, because the temp variable lives a shorter period.
Ok, this might be a little after the fact, but .promise() should also achieve what you're after.
An example from a project i'm working on:
$( '.panel' )
.fadeOut( 'slow')
.promise()
.done( function() {
$( '#' + target_panel ).fadeIn( 'slow', function() {});
});
:)
First I think you need to fix your lists, as the first node of a <ul>
must be a <li>
(stackoverflow ref). Once that is setup you can do this:
// note this array has outer scope
var phrases = [];
$('.phrase').each(function(){
// this is inner scope, in reference to the .phrase element
var phrase = '';
$(this).find('li').each(function(){
// cache jquery var
var current = $(this);
// check if our current li has children (sub elements)
// if it does, skip it
// ps, you can work with this by seeing if the first child
// is a UL with blank inside and odd your custom BLANK text
if(current.children().size() > 0) {return true;}
// add current text to our current phrase
phrase += current.text();
});
// now that our current phrase is completely build we add it to our outer array
phrases.push(phrase);
});
// note the comma in the alert shows separate phrases
alert(phrases);
Working jsfiddle.
One thing is if you get the .text()
of an upper level li
you will get all sub level text with it.
Keeping an array will allow for many multiple phrases to be extracted.
EDIT:
This should work better with an empty UL
with no LI
:
// outer scope
var phrases = [];
$('.phrase').each(function(){
// inner scope
var phrase = '';
$(this).find('li').each(function(){
// cache jquery object
var current = $(this);
// check for sub levels
if(current.children().size() > 0) {
// check is sublevel is just empty UL
var emptyULtest = current.children().eq(0);
if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
phrase += ' -BLANK- '; //custom blank text
return true;
} else {
// else it is an actual sublevel with li's
return true;
}
}
// if it gets to here it is actual li
phrase += current.text();
});
phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);
There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...
One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:
try{
$(sentences).each(function() {
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
}
catch (e)
{
alert(e)
}
Ok, let the thrashing begin.
Try this more succinct code:
Sub LoopOverEachColumn()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
End Sub
Private Sub ResizeColumns(WS As Worksheet)
Dim StrSize As String
Dim ColIter As Long
StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
For ColIter = 1 To 15
WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
Next ColIter
End Sub
If you want additional columns, just change 1 to 15
to 1 to X
where X
is the column index of the column you want, and append the column size you want to StrSize
.
For example, if you want P:P
to have a width of 25
, just add ;25
to StrSize
and change ColIter...
to ColIter = 1 to 16
.
Hope this helps.
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
A shorter answer from here, adapted to this question:
var arr = $('.requiredText');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
Just for completeness.
Use this:
$(function(){
$("tr.b_row").each(function(){
var a_href = $(this).find('div.cpt h2 a').attr('href');
alert ("Href is: "+a_href);
});
});
See a working demo: http://jsfiddle.net/usmanhalalit/4Ea4k/1/
You are indeed passing the first data item to the each function.
Pass data.programs to the each function instead. Change the code to as below:
<script>
$(document).ready(function() {
var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
$.each(data.programs, function(key,val) {
alert(key+val);
});
});
</script>
This works for me:
$.get("data.php", function(data){
var expected = ['justIn', 'recent', 'old'];
var outString = '';
$.each(expected, function(i, val){
var contentArray = data[val];
outString += '<ul><li><b>' + val + '</b>: ';
$.each(contentArray, function(i1, val2){
var textID = val2.textId;
var text = val2.text;
var textType = val2.textType;
outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
});
outString += '</li></ul>';
});
$('#contentHere').append(outString);
}, 'json');
This produces this output:
<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>
And looks like this:
Also, remember to set the contentType
as 'json'
$('#list option').each(function(intIndex){
//do stuff
});
$('.submit').filter(':checked').each(function() {
//This is same as 'continue'
if(something){
return true;
}
//This is same as 'break'
if(something){
return false;
}
});
One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.
For example:
HTML:
<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>
<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>
JS:
$( ".selected" ).each(function(index) {
$(this).on("click", function(){
// For the boolean value
var boolKey = $(this).data('selected');
// For the mammal value
var mammalKey = $(this).attr('id');
});
});
This is how it would be done in a loop in C++(11):
for (const auto& attack : m_attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
There is no for each
in C++. Another option is to use std::for_each with a suitable functor (this could be anything that can be called with an Attack*
as argument).
Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find
to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find
call's return value:
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> '+i+'<br />');
return item === word;
});
}
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';
var test = findXX('o322');
console.log('found word:', test);
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> ' + i + '<br />');
return item === word;
});
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
In jQuery just use:
$('#tblOne > tbody > tr').each(function() {...code...});
Using the children selector (>
) you will walk over all the children (and not all descendents), example with three rows:
$('table > tbody > tr').each(function(index, tr) {
console.log(index);
console.log(tr);
});
Result:
0
<tr>
1
<tr>
2
<tr>
In VanillaJS you can use document.querySelectorAll()
and walk over the rows using forEach()
[].forEach.call(document.querySelectorAll('#tblOne > tbody > tr'), function(index, tr) {
/* console.log(index); */
/* console.log(tr); */
});
Here is my solution and it's also working, when element shows into the viewport
var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
var firEvent = false,
objectPosTop = $('.go-counterTeaser').offset().top;
//when element shows at bottom
var elementViewInBottom = objectPosTop - winHeight;
$(window).on('scroll', function() {
var currentPosition = $(document).scrollTop();
//when element position starting in viewport
if (currentPosition > elementViewInBottom && firEvent === false) {
firEvent = true;
animationCounter();
}
});
}
//counter function will animate by using external js also add seprator "."
function animationCounter(){
$('.numberBlock h2').each(function () {
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator('.');
var counterValv = $(this).text();
$(this).animateNumber(
{
number: counterValv,
numberStep: comma_separator_number_step
}
);
});
}
https://jsfiddle.net/uosahmed/frLoxm34/9/
Try this, replacing .myClassName
with the actual name of the class (but keep the period at the beginning).
$('.myClassName').each(function() {
alert( this.id );
});
So if the class is "test", you'd do $('.test').each(func...
.
This is the specific form of .each()
that iterates over a jQuery object.
The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t
.
Using that form of $.each()
, you would need to do it like this:
$.each($('.myClassName'), function() {
alert( this.id );
});
...which will have the same result as the example above.
Today 2020.03.06 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6
for-in
(A,B) are fast (or fastest) for all browsers for big and small objectsfor-of
(H) solution is fast on chrome for small and big objectsi
(J,K) are quite fast on all browsers for small objects (for firefox also fast for big ojbects but medium fast on other browsers)Performance tests was performed for
Below snippets presents used solutions
function A(obj,s='') {_x000D_
for (let key in obj) if (obj.hasOwnProperty(key)) s+=key+'->'+obj[key] + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function B(obj,s='') {_x000D_
for (let key in obj) s+=key+'->'+obj[key] + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function C(obj,s='') {_x000D_
const map = new Map(Object.entries(obj));_x000D_
for (let [key,value] of map) s+=key+'->'+value + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function D(obj,s='') {_x000D_
let o = { _x000D_
...obj,_x000D_
*[Symbol.iterator]() {_x000D_
for (const i of Object.keys(this)) yield [i, this[i]]; _x000D_
}_x000D_
}_x000D_
for (let [key,value] of o) s+=key+'->'+value + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function E(obj,s='') {_x000D_
let o = { _x000D_
...obj,_x000D_
*[Symbol.iterator]() {yield *Object.keys(this)}_x000D_
}_x000D_
for (let key of o) s+=key+'->'+o[key] + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function F(obj,s='') {_x000D_
for (let key of Object.keys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function G(obj,s='') {_x000D_
for (let [key, value] of Object.entries(obj)) s+=key+'->'+value+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function H(obj,s='') {_x000D_
for (let key of Object.getOwnPropertyNames(obj)) s+=key+'->'+obj[key]+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function I(obj,s='') {_x000D_
for (const key of Reflect.ownKeys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function J(obj,s='') {_x000D_
let keys = Object.keys(obj);_x000D_
for(let i = 0; i < keys.length; i++){_x000D_
let key = keys[i];_x000D_
s+=key+'->'+obj[key]+' ';_x000D_
}_x000D_
return s;_x000D_
}_x000D_
_x000D_
function K(obj,s='') {_x000D_
var keys = Object.keys(obj), len = keys.length, i = 0;_x000D_
while (i < len) {_x000D_
let key = keys[i];_x000D_
s+=key+'->'+obj[key]+' ';_x000D_
i += 1;_x000D_
}_x000D_
return s;_x000D_
}_x000D_
_x000D_
function L(obj,s='') {_x000D_
Object.keys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
return s;_x000D_
}_x000D_
_x000D_
function M(obj,s='') {_x000D_
Object.entries(obj).forEach(([key, value]) => s+=key+'->'+value+' ');_x000D_
return s;_x000D_
}_x000D_
_x000D_
function N(obj,s='') {_x000D_
Object.getOwnPropertyNames(obj).forEach(key => s+=key+'->'+obj[key]+' ');_x000D_
return s;_x000D_
}_x000D_
_x000D_
function O(obj,s='') {_x000D_
Reflect.ownKeys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
return s;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
let log = (name,f) => console.log(`${name} ${f(p)}`)_x000D_
_x000D_
log('A',A);_x000D_
log('B',B);_x000D_
log('C',C);_x000D_
log('D',D);_x000D_
log('E',E);_x000D_
log('F',F);_x000D_
log('G',G);_x000D_
log('H',H);_x000D_
log('I',I);_x000D_
log('J',J);_x000D_
log('K',K);_x000D_
log('L',L);_x000D_
log('M',M);_x000D_
log('N',N);_x000D_
log('O',O);
_x000D_
This snippet only presents choosen solutions
_x000D_
And here are result for small objects on chrome
Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()
$.each(json, function (key, data) {
console.log(key)
$.each(data, function (index, data) {
console.log('index', data)
})
})
Demo: Fiddle
A few miscellaneous thoughts on this topic:
values
returns aliases which means that modifying them will modify the contents of the hash. This is by design but may not be what you want in some circumstances.each
. This is not true for keys
as each
is an iterator while keys
returns a list.Don't think of statelessness like "sending all your stuff to the server again and again". No way. There will be state, always - database itself is a kind of state after all, you're a registered user, so any set of client-side info won't be valid without the server side. Technically, you're never truly stateless.
Some mean "send the password each time", that's just plain stupid. Some say "nah of course not, send a token instead" - lo and behold, PHP session is doing almost exactly that. It sends a session id which is a kind of token and it helps you reach your personal stuff without resending u/pw every time. It's also quite reliable and well tested. And yes, convenient, which can turn into a drawback, see next paragraph.
A shared storage is a must. Server needs to know at least if someone's logged in or not. (And if you bother the database every time you need to decide this, you're practically doomed.) Shared storages need to be a lot faster than the database. This brings the temptation: okay, I have a very fast storage, why not do everything there? - and that's where things go nasty in the other way.
In VB.NET there's a vbCrLf constant for linebreaks:
Dim s As String = "your string".Replace(vbCrLf, "")
@Zelazny7's answer works, but if you want to keep ties you could do:
df[which(df$Amount == min(df$Amount)), ]
For example with the following data frame:
df <- data.frame(Name = c("A", "B", "C", "D", "E"),
Amount = c(150, 120, 175, 160, 120))
df[which.min(df$Amount), ]
# Name Amount
# 2 B 120
df[which(df$Amount == min(df$Amount)), ]
# Name Amount
# 2 B 120
# 5 E 120
Edit: If there are NAs in the Amount
column you can do:
df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]
In Yii2 we need to return()
the result from the action.I think you need to add a return
in front of your redirect.
return $this->redirect(['user/index']);
Another easy way to do this is by using the following syntax to iterate through the object, keeping access to the key and value:
for(var key in object){
console.log(key + ' - ' + object[key])
}
so for yours:
for(var key in obj){
console.log(key + ' - ' + obj[key])
}
In bootstrap 4 use:
<ul class="nav navbar-nav ml-auto">
This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.
Since there are some answers about how to use optional modifier and @objc attribute to define optional requirement protocol, I will give a sample about how to use protocol extensions define optional protocol.
Below code is Swift 3.*.
/// Protocol has empty default implementation of the following methods making them optional to implement:
/// `cancel()`
protocol Cancelable {
/// default implementation is empty.
func cancel()
}
extension Cancelable {
func cancel() {}
}
class Plane: Cancelable {
//Since cancel() have default implementation, that is optional to class Plane
}
let plane = Plane()
plane.cancel()
// Print out *United Airlines can't cancelable*
Please notice protocol extension methods can't invoked by Objective-C code, and worse is Swift team won't fix it. https://bugs.swift.org/browse/SR-492
There are two different ways you can add/override spring properties on the command line.
It's important that the -D parameters are before your application.jar otherwise they are not recognized.
java -jar -Dspring.profiles.active=prod application.jar
java -jar application.jar --spring.profiles.active=prod --spring.config.location=c:\config
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
In php it's very easy
html page
Male<input type="radio" name="radio" value="male"><br/>_x000D_
Female<input type="radio" name="radio" value="female"><br/>_x000D_
Others<input type="radio" name="radio" value="other"><br/>_x000D_
<input type="submit" value="submit">
_x000D_
Take value from form to php
$radio=$_POST['radio'];<br/>
use php if(isset($_POST['submit']))<br/>
{<br/>
echo "you selected".$radio."thank u";<br/>
}
Jupyter under the WinPython environment has a batch file in the scripts
folder called:
make_working_directory_be_not_winpython.bat
You need to edit the following line in it:
echo WINPYWORKDIR = %%HOMEDRIVE%%%%HOMEPATH%%\Documents\WinPython%%WINPYVER%%\Notebooks>>"%winpython_ini%"
replacing the Documents\WinPython%%WINPYVER%%\Notebooks
part with your folder address.
Notice that the %%HOMEDRIVE%%%%HOMEPATH%%\
part will identify the root and user folders (i.e. C:\Users\your_name\
) which will allow you to point different WinPython installations on separate computers to the same cloud storage folder (e.g. OneDrive), accessing and working with the same files from different machines. I find that very useful.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder
function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id
and the return value of document.getElementById
. If you get undefined
for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null
in the second.
The third case would happen if your web page looks like this, trying to run AddBorder
while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload
event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
I am quite benefited with http://stackoverflow.com. I was wandering from hours for automatic login and submit from vb application to another web site. Due to help of this site I am able to complete my task
I have to login following web php page.
<HTML>
<body>
<div align="center"><img src="banner.png" height="80px" /></div>
<script type="text/javascript">
$(document).ready(function(){
$("#login").validate();
$("#login_container").css({'position': 'absolute',
'top' : (($(window).height()/2) - $("#login_container").height()/2)+'px'});
$("#login_container").css({'left' : (($(window).width()/2) - $("#login_container").width()/2)+'px'});
});
</script>
<div id="login_container">
<form name="login" id="login" action="?q=login" method="post">
<table>
<tr><td>Username</td><td><input type="text" name="name" class="required"/></td></tr>
<tr><td>Password</td><td><input type="password" name="password" class="required"/></td></tr>
<tr><td></td><td><input type="submit" name="subimt" value="Login" /></td></tr>
</table>
</form>
</div>
</body>
</html>
For automatic Login and clicking I wrote following VB.Net Code. In form1
I placed a button and a Webbrowser control
Imports System.IO
Imports System.Windows.Forms
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Navigate("http://xyz.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
WebBrowser1.Document.GetElementById("name").SetAttribute("Value", "bharatlal")
WebBrowser1.Document.GetElementById("password").SetAttribute("Value", "mahato")
WebBrowser1.Document.GetElementById("subimt").Focus()
WebBrowser1.Document.GetElementById("subimt").InvokeMember("click")
End Sub
End Class
As Artem Bilan said, this problem occures because MappingJackson2HttpMessageConverter
supports response with application/json content-type only. If you can't change server code, but can change client code(I had such case), you can change content-type header with interceptor:
restTemplate.getInterceptors().add((request, body, execution) -> {
ClientHttpResponse response = execution.execute(request,body);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response;
});
If this error arises when manipulating a file that was just opened, check to see if you opened it in 'rb'
mode
Do you have multiple mongodb nodes in a replica set?
I found (I am using via Robomongo gui mongo shell, I guess same applies in other cases) that the correct remove syntax, i.e.
db.test_users.remove({"_id": ObjectId("4d512b45cc9374271b02ec4f")})
...does not work unless you are connected to the primary node of the replica set.
You have declared your function as friend
. It's not a member of the class. You should remove Matrix::
from the implementation. friend
means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix
class which is wrong.
I have solved a similar problem by first importing the text into an excel spreadsheet, then using the Substitute function to replace both the single and double quotes as required by SQL Server, eg. SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""")
In my case, I had many rows (each a line of data to be cleaned then inserted) and had the spreadsheet automatically generate insert queries for the text once the substitution had been done eg. ="INSERT INTO [dbo].[tablename] ([textcolumn]) VALUES ('" & SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""") & "')"
I hope that helps.
Try changing it to:
queryDate = '2009-11-01';
$('#datePicker').datepicker({defaultDate: new Date (queryDate)});
sudo apt-get install curl-devel
sudo apt-get install libcurl-dev
(will install the default alternative)
OR
sudo apt-get install libcurl4-openssl-dev
(the OpenSSL variant)
OR
sudo apt-get install libcurl4-gnutls-dev
(the gnutls variant)
More IntelliJ 13+ Shortcuts for Terminal
Mac OS X:
alt ?F12
cmd ?shift ?A then type Terminal
then hit Enter
shift ?shift ?shift ?shift ? then type Terminal
then hit Enter
Windows:
altF12 press Enter
ctrlshift ?A start typing Terminal
then hit Enter
shift ?shift ? then type Terminal
then hit Enter
A good rule of thumb is "open DLLs, closed EXEs", that is:
When you build an EXE as AnyCPU, all you're doing is deferring the decision on what process bitness to use to the OS, which will JIT the EXE to its liking. That is, an x64 OS will create a 64-bit process, an x86 OS will create an 32-bit process.
Building DLLs as AnyCPU makes them compatible to either process.
For more on the subtleties of assembly loading, see here. The executive summary reads something like:
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
name
attribute points to the column containing the asociation, i.e. column name of the foreign keyreferencedColumnName
attribute points to the related column in asociated/referenced entity, i.e. column name of the primary keyYou are not required to fill the referencedColumnName
if the referenced entity has single column as PK, because there is no doubt what column it references (i.e. the Address
single column ID).
@ManyToOne
@JoinColumn(name="ADDR_ID")
public Address getAddress() { return address; }
However if the referenced entity has PK that spans multiple columns the order in which you specify @JoinColumn
annotations has significance. It might work without the referencedColumnName
specified, but that is just by luck. So you should map it like this:
@ManyToOne
@JoinColumns({
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
public Address getAddress() { return address; }
or in case of ManyToMany
:
@ManyToMany
@JoinTable(
name="CUST_ADDR",
joinColumns=
@JoinColumn(name="CUST_ID"),
inverseJoinColumns={
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
}
)
Two queries generated by Hibernate of the same join table mapping, both without referenced column specified. Only the order of @JoinColumn
annotations were changed.
/* load collection Client.emails */
select
emails0_.id_client as id1_18_1_,
emails0_.rev as rev18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_
from client_email emails0_
inner join email email1_ on emails0_.id_email=email1_.id_email
where emails0_.id_client='2' and
emails0_.rev='18'
/* load collection Client.emails */
select
emails0_.rev as rev18_1_,
emails0_.id_client as id2_18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_
from client_email emails0_
inner join email email1_ on emails0_.id_email=email1_.id_email
where emails0_.rev='2' and
emails0_.id_client='18'
We are querying a join table to get client's emails. The {2, 18}
is composite ID of Client. The order of column names is determined by your order of @JoinColumn
annotations. The order of both integers is always the same, probably sorted by hibernate and that's why proper alignment with join table columns is required and we can't or should rely on mapping order.
The interesting thing is the order of the integers does not match the order in which they are mapped in the entity - in that case I would expect {18, 2}
. So it seems the Hibernate is sorting the column names before it use them in query. If this is true and you would order your @JoinColumn
in the same way you would not need referencedColumnName
, but I say this only for illustration.
Properly filled referencedColumnName
attributes result in exactly same query without the ambiguity, in my case the second query (rev = 2
, id_client = 18
).
java.lang.Integer
is not a super class of BigInteger
. Both BigInteger
and Integer
do inherit from java.lang.Number
, so you could cast to a java.lang.Number
.
See the java docs http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Number.html
I think it would be handy to use Session.Clear()
rather than using Session.Abandon()
.
Because the values still exist in session after calling later but are removed after calling the former.
There is also an 'E' status
E = File existed before update
This can happen if you have manually created a folder that would have been created by performing an update.
As an appendix to Clint's answer, you can simplify PackageResource
using contextlib.contextmanager
:
@contextlib.contextmanager
def packageResource():
class Package:
...
package = Package()
yield package
package.cleanup()
Alternatively, though probably not as Pythonic, you can override Package.__new__
:
class Package(object):
def __new__(cls, *args, **kwargs):
@contextlib.contextmanager
def packageResource():
# adapt arguments if superclass takes some!
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
yield package
package.cleanup()
def __init__(self, *args, **kwargs):
...
and simply use with Package(...) as package
.
To get things shorter, name your cleanup function close
and use contextlib.closing
, in which case you can either use the unmodified Package
class via with contextlib.closing(Package(...))
or override its __new__
to the simpler
class Package(object):
def __new__(cls, *args, **kwargs):
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
return contextlib.closing(package)
And this constructor is inherited, so you can simply inherit, e.g.
class SubPackage(Package):
def close(self):
pass
$(function(){ _x000D_
$('.bordered').css({_x000D_
"border":"1px solid #EFEFEF",_x000D_
"margin":"0 auto",_x000D_
"width":"80%"_x000D_
});_x000D_
_x000D_
$('h1').css({_x000D_
"margin-left":"10px"_x000D_
});_x000D_
_x000D_
$('#myParagraph').css({_x000D_
"margin-left":"10px",_x000D_
"font-family":"sans-serif"_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
<h1>Header</h1>_x000D_
<p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
I am developing an app to version 2.2, API version would in the 8th ... had the same error and the error told me it was to google maps API, all we did was change my ADV for my project API 2.2 and also for the API.
This worked for me and found the library API needed.
It's easier to use the timestamp for this things since Tweepy gets both
import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))
You can use this as well:
SELECT RTRIM (
XMLAGG (XMLELEMENT (e, country_name || ',')).EXTRACT ('//text()'),
',')
country_name
FROM countries;
There is a pretty good list at linuxappfinder.com.
My personal preference for LaTeX on Linux has been the KDE-based editor Kile.
How to mock void methods with mockito - there are two options:
doAnswer
- If we want our mocked void method to do something (mock the behavior despite being void).doThrow
- Then there is Mockito.doThrow()
if you want to throw an exception from the mocked void method.Following is an example of how to use it (not an ideal usecase but just wanted to illustrate the basic usage).
@Test
public void testUpdate() {
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 1 && arguments[0] != null && arguments[1] != null) {
Customer customer = (Customer) arguments[0];
String email = (String) arguments[1];
customer.setEmail(email);
}
return null;
}
}).when(daoMock).updateEmail(any(Customer.class), any(String.class));
// calling the method under test
Customer customer = service.changeEmail("[email protected]", "[email protected]");
//some asserts
assertThat(customer, is(notNullValue()));
assertThat(customer.getEmail(), is(equalTo("[email protected]")));
}
@Test(expected = RuntimeException.class)
public void testUpdate_throwsException() {
doThrow(RuntimeException.class).when(daoMock).updateEmail(any(Customer.class), any(String.class));
// calling the method under test
Customer customer = service.changeEmail("[email protected]", "[email protected]");
}
}
You could find more details on how to mock and test void methods with Mockito in my post How to mock with Mockito (A comprehensive guide with examples)
The documentation on how to do this can be found on MSDN. The key extract is this:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a
WM_SETTINGCHANGE
message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.
Note that your application will need elevated admin rights in order to be able to modify this key.
You indicate in the comments that you would be happy to modify just the per-user environment. Do this by editing the values in HKEY_CURRENT_USER\Environment. As before, make sure that you broadcast a WM_SETTINGCHANGE
message.
You should be able to do this from your Java application easily enough using the JNI registry classes.
It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.
e.g.
System.out.println("printing \"this\" in quotes");
outputs
printing "this" in quotes
I like the answer but I think it would be better that you create a global scope function that will allow you to set the scope variable needed.
So in the globalController create
$scope.setScopeVariable = function(variable, value){
$scope[variable] = value;
}
and then in your html file call it
{{setScopeVariable('myVar', 'whatever')}}
This will then allow you to use $scope.myVar in your respective controller
The only time I factor in extra time for testing is if I'm unfamiliar with the testing technology I'll be using (e.g. using Selenium tests for the first time). Then I factor in maybe 10-20% for getting up to speed on the tools and getting the test infrastructure in place.
Otherwise testing is just an innate part of development and doesn't warrant an extra estimate. In fact, I'd probably increase the estimate for code done without tests.
EDIT: Note that I'm usually writing code test-first. If I have to come in after the fact and write tests for existing code that's going to slow things down. I don't find that test-first development slows me down at all except for very exploratory (read: throw-away) coding.
On my Mobo (ASRock A320M-HD with Ryzen 3 2200G) I have to:
SR-IOV support: enabled
IOMMU: enabled
SVM: enabled
On the OS enable Hyper V.
Probably every answer provided above is right, but my answer is specific to use of hashCode()
method, to prove the points like, String... once created can't be modified and modifications will results in new value at different memory location.
public class ImmutabilityTest {
private String changingRef = "TEST_STRING";
public static void main(String a[]) {
ImmutabilityTest dn = new ImmutabilityTest();
System.out.println("ChangingRef for TEST_STRING OLD : "
+ dn.changingRef.hashCode());
dn.changingRef = "NEW_TEST_STRING";
System.out.println("ChangingRef for NEW_TEST_STRING : "
+ dn.changingRef.hashCode());
dn.changingRef = "TEST_STRING";
System.out.println("ChangingRef for TEST_STRING BACK : "
+ dn.changingRef.hashCode());
dn.changingRef = "NEW_TEST_STRING";
System.out.println("ChangingRef for NEW_TEST_STRING BACK : "
+ dn.changingRef.hashCode());
String str = new String("STRING1");
System.out.println("String Class STRING1 : " + str.hashCode());
str = new String("STRING2");
System.out.println("String Class STRING2 : " + str.hashCode());
str = new String("STRING1");
System.out.println("String Class STRING1 BACK : " + str.hashCode());
str = new String("STRING2");
System.out.println("String Class STRING2 BACK : " + str.hashCode());
}
}
ChangingRef for TEST_STRING OLD : 247540830
ChangingRef for NEW_TEST_STRING : 970356767
ChangingRef for TEST_STRING BACK : 247540830
ChangingRef for NEW_TEST_STRING BACK : 970356767
String Class STRING1 : -1163776448
String Class STRING2 : -1163776447
String Class STRING1 BACK : -1163776448
String Class STRING2 BACK : -1163776447
I've chmoded my keypair to 600 in order to get into my personal instance last night,
And this is the way it is supposed to be.
From the EC2 documentation we have "If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you." The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.
The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.
Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.
Any problems you are having are client side, so be sure to include local OS information with any follow up questions!
As has been pointed out ... in a select
box, the .val()
attribute will give you the value of the selected option. If the selected option does not have a value attribute it will default to the display value of the option (which is what the examples on the jQuery documentation of .val
show.
you want to use .text()
of the selected option:
$('#Crd option:selected').text()
i did find something like this, helps get rid of hardcoded tempdata tags
public class AccountController : Controller
{
[HttpGet]
public ActionResult Index(IndexPresentationModel model)
{
return View(model);
}
[HttpPost]
public ActionResult Save(SaveUpdateModel model)
{
// save the information
var presentationModel = new IndexPresentationModel();
presentationModel.Message = model.Message;
return this.RedirectToAction(c => c.Index(presentationModel));
}
}
You can try this
- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
while ([str rangeOfString:@" "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
}
return str;
}
Hope this will help you out.
You can find a complete and very simple java class for sending emails using Google(gmail) account here, Send email message using java application
It uses following properties
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
I know this is too late for sure, but, this could help someone as well.
In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).
Make sure that you can copy from the command prompt,
MySQL
SELECT r.name,
GROUP_CONCAT(a.name SEPARATOR ',')
FROM RESOURCES r
JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name
**
MS SQL Server
SELECT r.name,
STUFF((SELECT ','+ a.name
FROM APPLICATIONS a
JOIN APPLICATIONRESOURCES ar ON ar.app_id = a.id
WHERE ar.resource_id = r.id
GROUP BY a.name
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '')
FROM RESOURCES r
GROUP BY deptno;
Oracle
SELECT r.name,
LISTAGG(a.name SEPARATOR ',') WITHIN GROUP (ORDER BY a.name)
FROM RESOURCES r
JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name;
From the Oracle Reference:
The default locale of your application is determined in three ways. First, unless you have explicitly changed the default, the
Locale.getDefault()
method returns the locale that was initially determined by the Java Virtual Machine (JVM) when it first loaded. That is, the JVM determines the default locale from the host environment. The host environment's locale is determined by the host operating system and the user preferences established on that system.Second, on some Java runtime implementations, the application user can override the host's default locale by providing this information on the command line by setting the
user.language
,user.country
, anduser.variant
system properties.Third, your application can call the
Locale.setDefault(Locale)
method. The setDefault(Locale aLocale) method lets your application set a systemwide (actually VM-wide) resource. After you set the default locale with this method, subsequent calls to Locale.getDefault() will return the newly set locale.
The bootstrap docs says about this:
Requires custom widths Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.
The default width of 100% as all form elements gets when they got the class form-control
didn't apply if you use the form-inline
class on your form.
You could take a look at the bootstrap.css (or .less, whatever you prefer) where you will find this part:
.form-inline {
// Kick in the inline
@media (min-width: @screen-sm-min) {
// Inline-block all the things for "inline"
.form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
// In navbar-form, allow folks to *not* use `.form-group`
.form-control {
display: inline-block;
width: auto; // Prevent labels from stacking above inputs in `.form-group`
vertical-align: middle;
}
// Input groups need that 100% width though
.input-group > .form-control {
width: 100%;
}
[...]
}
}
Maybe you should take a look at input-groups, since I guess they have exactly the markup you want to use (working fiddle here):
<div class="row">
<div class="col-lg-12">
<div class="input-group input-group-lg">
<input type="text" class="form-control input-lg" id="search-church" placeholder="Your location (City, State, ZIP)">
<span class="input-group-btn">
<button class="btn btn-default btn-lg" type="submit">Search</button>
</span>
</div>
</div>
</div>
Using async/await
async changeHandler(event) {
await this.setState({ yourName: event.target.value });
console.log(this.state.yourName);
}
Your site is serving a 500 Internal Server Error
.
This can be caused by a number of things, such as:
EDIT
As you have highlighted it is a permission issue. You need to ensure that your files are executable by the web server user
Please see below article for some guidance on proper file permissions. https://www.digitalocean.com/community/questions/proper-permissions-for-web-server-s-directory
In addition to the answer given by @l0b0 I just had the situation where I needed to both keep any trailing newlines output by the script and check the script's return code. And the problem with l0b0's answer is that the 'echo x' was resetting $? back to zero... so I managed to come up with this very cunning solution:
RESULTX="$(./myscript; echo x$?)"
RETURNCODE=${RESULTX##*x}
RESULT="${RESULTX%x*}"
Swift 2.0:
Implement viewForHeaderInSection, like so:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
if sectionTitle == "" {
return nil
}
let title: UILabel = UILabel()
title.text = sectionTitle
title.textColor = UIColor(red: 0.0, green: 0.54, blue: 0.0, alpha: 0.8)
title.backgroundColor = UIColor.clearColor()
title.font = UIFont.boldSystemFontOfSize(15)
return title
}
Implement willDisplayHeaderView, like so:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView {
view.backgroundView?.backgroundColor = UIColor.blueColor()
view.textLabel!.backgroundColor = UIColor.clearColor()
view.textLabel!.textColor = UIColor.whiteColor()
view.textLabel!.font = UIFont.boldSystemFontOfSize(15)
}
}
Remember: If you're using static cells, the first section header is padded higher than other section headers due to the top of the UITableView; to fix this:
Implement heightForHeaderInSection, like so:
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30.0 // Or whatever height you want!
}
The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.
Those CORS headers do not support *
as value, the only way is to replace *
with this:
Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With
.htaccess
Example (CORS Included):<IfModule mod_headers.c>
Header unset Connection
Header unset Time-Zone
Header unset Keep-Alive
Header unset Access-Control-Allow-Origin
Header unset Access-Control-Allow-Headers
Header unset Access-Control-Expose-Headers
Header unset Access-Control-Allow-Methods
Header unset Access-Control-Allow-Credentials
Header set Connection keep-alive
Header set Time-Zone "Asia/Jerusalem"
Header set Keep-Alive timeout=100,max=500
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
Header set Access-Control-Expose-Headers "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
Header set Access-Control-Allow-Methods "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
Header set Access-Control-Allow-Credentials "true"
Header set DNT "0"
Header set Accept-Ranges "bytes"
Header set Vary "Accept-Encoding"
Header set X-UA-Compatible "IE=edge,chrome=1"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set X-Xss-Protection "1; mode=block"
</IfModule>
Why Access-Control-Allow-Headers
, Access-Control-Expose-Headers
, Access-Control-Allow-Methods
values are super long?
Those do not support the *
syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)
Why do you use Header unset ______
syntax?
GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)
Is it safe for me to use 'as-is'?
Well.. mostly the answer would be YES since the .htaccess
is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods
lines. Also Connection
, Time-Zone
, Keep-Alive
and DNT
, Accept-Ranges
, Vary
, X-UA-Compatible
, X-Frame-Options
, X-Content-Type-Options
and X-Xss-Protection
are just a suggestion I'm using for my online-service.. feel free to remove those too...
taken from my comment above
For relative imports see the documentation. A relative import is when you import from a module relative to that module's location, instead of absolutely from sys.path
.
As for import *
, Python 2 allowed star imports within functions, for instance:
>>> def f():
... from math import *
... print sqrt
A warning is issued for this in Python 2 (at least recent versions). In Python 3 it is no longer allowed and you can only do star imports at the top level of a module (not inside functions or classes).
I tried to do something like this, but I still got an IndexOutOfBoundsException.
I got a ConcurrentAccessException
This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either
use a collection which is designed for concurrent access.
lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)
find a away to avoid needing to copy the original list.
Borrowing, slightly enhancing and simplifying from this Blog post the following simple SQL statement seems to do the job quite well:
SELECT DISTINCT (:val) "Search Value", TABLE_NAME "Table", COLUMN_NAME "Column"
FROM cols,
TABLE (XMLSEQUENCE (DBMS_XMLGEN.GETXMLTYPE(
'SELECT "' || COLUMN_NAME || '" FROM "' || TABLE_NAME || '" WHERE UPPER("'
|| COLUMN_NAME || '") LIKE UPPER(''%' || :val || '%'')' ).EXTRACT ('ROWSET/ROW/*')))
ORDER BY "Table";
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
String surname = sc.nextLine();
Statement statement = connection.createStatement();
String query = "INSERT INTO STUDENT VALUES("+'"name"'+","+'"surname"'+")";
statement.executeQuery();
Do not miss to add '"----"' when concat the string.
Avoid using any interval based methods and use MutationObserver targeting a parent div
of dynamically loaded div
for better efficiency.
Here's the simple snippet:
HTML:
<div class="parent-static-div">
<div class="dynamic-loaded-div">
this div is loaded after DOM ready event
</div>
</div>
JS:
var observer = new MutationObserver(function (mutationList, obsrvr) {
var div_to_check = document.querySelector(".dynamic-loaded-div"); //get div by class
// var div_to_check = document.getElementById('div-id'); //get div by id
console.log("checking for div...");
if (div_to_check) {
console.log("div is loaded now"); // DO YOUR STUFF!
obsrvr.disconnect(); // stop observing
return;
}
});
var parentElement = document.querySelector("parent-static-div"); // use parent div which is already present in DOM to maximise efficiency
// var parentElement = document // if not sure about parent div then just use whole 'document'
// start observing for dynamic div
observer.observe(parentElement, {
// for properties details: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
childList: true,
subtree: true,
});
You got different things here:
First:
this
"
keyword). ref: angular.service vs angular.factory
Second:
Keep in mind all providers in AngularJS (value, constant, services, factories) are singletons!
Third:
Using one or the other (service or factory) is about code style. But, the common way in AngularJS is to use factory.
Why ?
Because "The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate "private" variables. This is very useful as we can hide implementation details of a given service."
(ref: http://www.amazon.com/Mastering-Web-Application-Development-AngularJS/dp/1782161821).
Service : Could be useful for sharing utility functions that are useful to invoke by simply appending ()
to the injected function reference. Could also be run with injectedArg.call(this)
or similar.
Factory : Could be useful for returning a ‘class’ function that can then be new`ed to create instances.
So, use a factory when you have complex logic in your service and you don't want expose this complexity.
In other cases if you want to return an instance of a service just use service.
But you'll see with time that you'll use factory in 80% of cases I think.
For more details: http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/
UPDATE :
Excellent post here : http://iffycan.blogspot.com.ar/2013/05/angular-service-or-factory.html
"If you want your function to be called like a normal function, use factory. If you want your function to be instantiated with the new operator, use service. If you don't know the difference, use factory."
UPDATE :
AngularJS team does his work and give an explanation: http://docs.angularjs.org/guide/providers
And from this page :
"Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions."
label, input {
vertical-align: middle;
}
I'm just align the vertical midpoint of the boxes with the baseline of the parent box plus half the x-height (en.wikipedia.org/wiki/X-height) of the parent.
Console.WriteLine(curr.ToString("HH:mm"));
Your code looks fine, but there are a couple of things to be aware of:
Post::find($id);
acts upon the primary key, if you have set your primary key in your model to something other than id
by doing:
protected $primaryKey = 'slug';
then find
will search by that key instead.
Laravel also expects the id
to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:
public $incrementing = false;
Completely reset?
Delete the .git
directory locally.
Recreate the git repostory:
$ cd (project-directory)
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'
Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.
$ git remote add origin <url>
$ git push --force --set-upstream origin master
This works on Windows
Then you'll be able to see all modules within those paths from your scripts.
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1 Phone Number: output of string2
Some readable python:
def JoeCalimar(l):
masterList = []
for i in l:
for j in l:
masterList.append(1.*i/j)
pos = masterList.index(min(masterList))
a = pos/len(masterList)
b = pos%len(masterList)
return (l[a],l[b])
Let me know if something is not clear.
Try This and you can adjust date formate accordingly:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var myDate= dd + '-' + mm + '-' + yyyy;
Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.
Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.
Syntax
ALTER TRIGGER trigger Name DISABLE;
ALTER TRIGGER trigger_Name ENABLE;
Maybe it is just my Java and C background showing, but I prefer CamelCase (CapCase) over punctuation in the name. My workgroup uses such names, probably to match the names of the app or service the repository contains.
Step 1: Change build.grade
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
dependencies {
...
compile 'com.android.support:multidex:1.0.0'
}
Step 2: Setting on the Application class
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MultiDex.install(this);
}
}
Step 3: Change grade.properties
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
It will work!. Thanks.
Just so you know the iPhone 6 lies about it's min-width. It thinks it is 320 instead of 375 it is suppose to be.
@media only screen and (max-device-width: 667px)
and (-webkit-device-pixel-ratio: 2) {
}
This was the only thing I could get to work to target the iPhone 6. The 6+ works fine the using this method:
@media screen and (min-device-width : 414px)
and (max-device-height : 736px) and (max-resolution: 401dpi)
{
}
Better you copy and move them to your own resources. Some resources might not be available on previous Android versions. Here is a link with all drawables available on each Android version thanks to @fiXedd
Sample code for case: @throw([NSException exceptionWithName:...
- (void)parseError:(NSError *)error
completionBlock:(void (^)(NSString *error))completionBlock {
NSString *resultString = [NSString new];
@try {
NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];
if(!errorData.bytes) {
@throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
}
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
options:NSJSONReadingAllowFragments
error:&error];
resultString = dictFromData[@"someKey"];
...
} @catch (NSException *exception) {
NSLog( @"Caught Exception Name: %@", exception.name);
NSLog( @"Caught Exception Reason: %@", exception.reason );
resultString = exception.reason;
} @finally {
completionBlock(resultString);
}
}
Using:
[self parseError:error completionBlock:^(NSString *error) {
NSLog(@"%@", error);
}];
Another more advanced use-case:
- (void)parseError:(NSError *)error completionBlock:(void (^)(NSString *error))completionBlock {
NSString *resultString = [NSString new];
NSException* customNilException = [NSException exceptionWithName:@"NilException"
reason:@"object is nil"
userInfo:nil];
NSException* customNotNumberException = [NSException exceptionWithName:@"NotNumberException"
reason:@"object is not a NSNumber"
userInfo:nil];
@try {
NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];
if(!errorData.bytes) {
@throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
}
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
options:NSJSONReadingAllowFragments
error:&error];
NSArray * array = dictFromData[@"someArrayKey"];
for (NSInteger i=0; i < array.count; i++) {
id resultString = array[i];
if (![resultString isKindOfClass:NSNumber.class]) {
[customNotNumberException raise]; // <====== HERE is just the same as: @throw customNotNumberException;
break;
} else if (!resultString){
@throw customNilException; // <======
break;
}
}
} @catch (SomeCustomException * sce) {
// most specific type
// handle exception ce
//...
} @catch (CustomException * ce) {
// most specific type
// handle exception ce
//...
} @catch (NSException *exception) {
// less specific type
// do whatever recovery is necessary at his level
//...
// rethrow the exception so it's handled at a higher level
@throw (SomeCustomException * customException);
} @finally {
// perform tasks necessary whether exception occurred or not
}
}
I did a SQL query in a large number of OR (350). Postgres do it 437.80ms.
Now use IN:
23.18ms
The reason for the error is you upgraded your numpy library of which there are some functionalities from scipy that are required by the current version for it to run which may not be found in scipy. Just upgrade your scipy library using python -m pip install scipy --upgrade. I was facing the same error and this solution worked on my python 3.5.
Found a nice solution to this problem elsewhere, no messing around with tags on the button:
- (void)buttonPressedAction:(id)sender {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
// do stuff with the indexPath...
}
As Yaron mentioned, there isn't any difference between where
and filter
.
filter
is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.
We can use explain()
to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name
and person_country
columns. All of the following code snippets will return the same Physical Plan below:
df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()
These all return this Physical Plan:
== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
+- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>
The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.
I was getting same error while using WebServiceTemplate spring ws [err] org.springframework.ws.client.WebServiceTransportException: Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'. [415] [err] at org.springframework.ws.client.core.WebServiceTemplate.handleError(WebServiceTemplate.java:665). The WSDL which i was using has soap1.2 protocol and by default the protocol is soap1.1 . When i changed the protocol using below code, it was working
MessageFactory msgFactory = MessageFactory.newInstance(javax.xml.soap.SOAPConstants.SOAP_1_2_PROTOCOL);
SaajSoapMessageFactory saajSoapMessageFactory = new SaajSoapMessageFactory(msgFactory);
saajSoapMessageFactory.setSoapVersion(SoapVersion.SOAP_12);
getWebServiceTemplate().setMessageFactory(saajSoapMessageFactory);
Probably a bit late but this is worth a mention:
Environment.GetCommandLineArgs()[0];
Or more correctly to get just the directory path:
System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
Edit:
Quite a few people have pointed out that GetCommandLineArgs
is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof' GetCommandLineArgs
, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.
FYI: This method is the same as @SuRa but is a little simpler. Btw: I use VS Code version 1.43.0
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date2));
long diff = d2.getTime() - d1.getTime();
System.out.println("Difference between " + d1 + " and "+ d2+" is "
+ (diff / (1000 * 60 * 60 * 24)) + " days.");
The same thing happened to me and i found that i forgot to put the " at the end of the
#import "CPDConstants.h
so instead
#import "CPDConstants.h"
Use .height()
like this:
var result = $("#myDiv").height();
There's also .innerHeight()
and .outerHeight()
depending on exactly what you want.
You can test it here, play with the padding/margins/content to see how it changes around.
For VBA you need to initialise in two lines.
Sub TestArray()
Dim myArray
myArray = Array(1, 2, 4, 8)
End Sub
If I understand clearly, you want to do this programatically. Then, you could use the onTouchEvent method of View
, and create a MotionEvent
with the coordinates you need.
Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.
Define the following tag on the top of your web page:
<!DOCTYPE html>
A simple way to calculate Median in MySQL
set @ct := (select count(1) from station);
set @row := 0;
select avg(a.val) as median from
(select * from table order by val) a
where (select @row := @row + 1)
between @ct/2.0 and @ct/2.0 +1;
Try this, this works for my code name is a String:
cursor = rdb.query(true, TABLE_PROFILE, new String[] { ID,
REMOTEID, FIRSTNAME, LASTNAME, EMAIL, GENDER, AGE, DOB,
ROLEID, NATIONALID, URL, IMAGEURL },
LASTNAME + " like ?", new String[]{ name+"%" }, null, null, null, null);
If you're using PaperClip, downloading from a URL is now handled automatically.
Assuming you've got something like:
class MyModel < ActiveRecord::Base
has_attached_file :image, ...
end
On your model, just specify the image as a URL, something like this (written in deliberate longhand):
@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)
You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.
Paperclip will take it from there.
source: paperclip documentation
If you just want the date:
SELECT MIN(date) as EarliestDate
FROM YourTable
WHERE id = 2
If you want all of the information:
SELECT TOP 1 id, name, score, date
FROM YourTable
WHERE id = 2
ORDER BY Date
Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.
simply use:
@JsonFormat(pattern="10/04/2019")
or you can use pattern as you like for e.g: ('-' in place of '/')
It is best practice to NOT use UNDERSCORES before any variable name or parameter name in C++
Names beginning with an underscore or a double underscore are RESERVED for the C++ implementers. Names with an underscore are reserved for the library to work.
If you have a read at the C++ Coding Standard, you will see that in the very first page it says:
"Don't overlegislate naming, but do use a consistent naming convention: There are only two must-dos: a) never use "underhanded names," ones that begin with an underscore or that contain a double underscore;" (p2 , C++ Coding Standards, Herb Sutter and Andrei Alexandrescu)
More specifically, the ISO working draft states the actual rules:
In addition, some identifiers are reserved for use by C ++ implementations and shall not be used otherwise; no diagnostic is required. (a) Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use. (b) Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
It is best practice to avoid starting a symbol with an underscore in case you accidentally wander into one of the above limitations.
You can see it for yourself why such use of underscores can be disastrous when developing a software:
Try compiling a simple helloWorld.cpp program like this:
g++ -E helloWorld.cpp
You will see all that happens in the background. Here is a snippet:
ios_base::iostate __err = ios_base::iostate(ios_base::goodbit);
try
{
__streambuf_type* __sb = this->rdbuf();
if (__sb)
{
if (__sb->pubsync() == -1)
__err |= ios_base::badbit;
else
__ret = 0;
}
You can see how many names begin with double underscore!
Also if you look at virtual member functions, you will see that *_vptr is the pointer generated for the virtual table which automatically gets created when you use one or more virtual member functions in your class! But that's another story...
If you use underscores you might get into conflict issues and you WILL HAVE NO IDEA what's causing it, until it's too late.
Maybe worth mentioning that when I had this problem I followed bia.migueis's advice - move everything out of the plugins folder - and the workspace would open again, minus a lot of my configuration. But then after that, I copied/overwrote all the original files back into the plugins folder and opened the workspace again: it still worked and the settings I'd had before seemed to be intact.
Benchmark.
I'd start ramping up the number of threads for an application, starting at 1, and then go to something like 100, run three-five trials for each number of threads, and build yourself a graph of operation speed vs. number of threads.
You should that the four thread case is optimal, with slight rises in runtime after that, but maybe not. It may be that your application is bandwidth limited, ie, the dataset you're loading into memory is huge, you're getting lots of cache misses, etc, such that 2 threads are optimal.
You can't know until you test.
This is a full working example :
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public void callWebService(String soapAction, String soapEnvBody) throws IOException {
// Create a StringEntity for the SOAP XML.
String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
StringEntity stringEntity = new StringEntity(body, "UTF-8");
stringEntity.setChunked(true);
// Request parameters and other properties.
HttpPost httpPost = new HttpPost("http://example.com?soapservice");
httpPost.setEntity(stringEntity);
httpPost.addHeader("Accept", "text/xml");
httpPost.addHeader("SOAPAction", soapAction);
// Execute and get the response.
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String strResponse = null;
if (entity != null) {
strResponse = EntityUtils.toString(entity);
}
}
sudo mysql
enter your (LINUX) account password
grant create on *.* to user@localhost;
FLUSH PRIVILEGES;
I recommend that you use the standard packages email
and smtplib
together to send email. Please look at the following example (reproduced from the Python documentation). Notice that if you follow this approach, the "simple" task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
with open(textfile, 'rb') as fp:
# Create a text/plain message
msg = MIMEText(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
For sending email to multiple destinations, you can also follow the example in the Python documentation:
# Import smtplib for the actual sending function
import smtplib
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'
# Assume we know that the image files are all in PNG format
for file in pngfiles:
# Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type.
with open(file, 'rb') as fp:
img = MIMEImage(fp.read())
msg.attach(img)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()
As you can see, the header To
in the MIMEText
object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the sendmail
function must be a list of strings (each string is an email address).
So, if you have three email addresses: [email protected]
, [email protected]
, and [email protected]
, you can do as follows (obvious sections omitted):
to = ["[email protected]", "[email protected]", "[email protected]"]
msg['To'] = ",".join(to)
s.sendmail(me, to, msg.as_string())
the ",".join(to)
part makes a single string out of the list, separated by commas.
From your questions I gather that you have not gone through the Python tutorial - it is a MUST if you want to get anywhere in Python - the documentation is mostly excellent for the standard library.
I'd set up your HTML like so:
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />
Then use the following code:
<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function(event) {
window.location.href = this.id + '.html';
};
}
</script>
That assigns an onclick
event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id
attribute plus the .html
extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.
I just had a similar problem, but I was using LINQ extension methods on a list rather than query syntax. The casting to a Nullable trick works there as well:
int max = list.Max(i => (int?)i.MyCounter) ?? 0;
Sure! You can remove blue border also from all HTML elements using *
*{
outline-color: transparent;
outline-style: none;
}
And
*{
outline: none;
}
Sometimes npm uninstall -g packageName
doesn’t work.
In this case you can delete package manually.
On Mac, go to folder /usr/local/lib/node_modules
and delete the folder with the package you want. That's it. Check your list of globally installed packages with this command:
npm list -g --depth=0
My team really got sick of trying to find the tenant ID for our O365 and Azure projects. The devs, the support team, the sales team, everyone needs it at some point and never remembers how to do it.
So we've built this small site in the same vein as whatismyip.com. Hope you find it useful!
How to find my Microsoft 365, Azure or SharePoint Online tenant ID?
Faced this exact issue. The problem resolved when i changed the Service="Namespace.ServiceName" tag in the Markup (right click xxxx.svc and select View Markup in visual studio) to match the namespace i used for my xxxx.svc.cs file
Had the same issue. Check with sublime.log_input(True) command on the console to see what keys are being detected with the CTRL+/ and SHIFT+CTRL+/ shorcuts. Then replace the shortcuts with those. (Changing / for keypad_divide worked for me)
If the server's certificate is self-signed, then this is working as designed and you will have to import the server's certificate into your keystore.
Assuming the server certificate is signed by a well-known CA, this is happening because the set of CA certificates available to a modern browser is much larger than the limited set that is shipped with the JDK/JRE.
The EasySSL solution given in one of the posts you mention just buries the error, and you won't know if the server has a valid certificate.
You must import the proper Root CA into your keystore to validate the certificate. There's a reason you can't get around this with the stock SSL code, and that's to prevent you from writing programs that behave as if they are secure but are not.
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.
Android code - Main.java
package test12.tt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test12Activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt1 = (TextView) findViewById(R.id.sm);
new Thread(new Runnable() {
public void run(){
txt1.setText("Thread!!");
}
}).start();
}
}
Android application xml - main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id = "@+id/sm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
index[hash(input)%2]
would result in a collision for half of all possible hashes and a range of values. index[hash(input)%prime]
results in a collision of <2 of all possible hashes. Fixing the divisor to the table size also ensures that the number cannot be greater than the table.
subprocess: The
subprocess
module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
http://docs.python.org/library/subprocess.html
Usage:
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
In simple terms, inside a then
handler function:
A) When x
is a value (number, string, etc):
return x
is equivalent to return Promise.resolve(x)
throw x
is equivalent to return Promise.reject(x)
B) When x
is a Promise that is already settled (not pending anymore):
return x
is equivalent to return Promise.resolve(x)
, if the Promise was already resolved.return x
is equivalent to return Promise.reject(x)
, if the Promise was already rejected.C) When x
is a Promise that is pending:
return x
will return a pending Promise, and it will be evaluated on the subsequent then
. Read more on this topic on the Promise.prototype.then() docs.
Yet another reason may be that your entity class has several properties named somhow /.*id/i
- so ending with ID case insensitive AND elementary type AND there is no [Key]
attribute.
EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.
See my case:
public class MyTest, IMustHaveTenant
{
public long Id { get; set; }
public int TenantId { get; set; }
[MaxLength(32)]
public virtual string Signum{ get; set; }
public virtual string ID { get; set; }
public virtual string ID_Other { get; set; }
}
don't ask - lecacy code. The Id
was even inherited, so I could not use [Key]
(just simplifying the code here)
But here EF is totally confused.
What helped was using modelbuilder this in DBContext class.
modelBuilder.Entity<MyTest>(f =>
{
f.HasKey(e => e.Id);
f.HasIndex(e => new { e.TenantId });
f.HasIndex(e => new { e.TenantId, e.ID_Other });
});
the index on PK is implicit.
Your return function is in line of def function(main function), you must give one tab to it. And Use
%%debug
instead of
%debug
to debug the whole cell not only line. Hope, maybe this will help you.
Initialise here..
SharedPreferences msharedpref = getSharedPreferences("msh",
MODE_PRIVATE);
Editor editor = msharedpref.edit();
store data...
editor.putString("id",uida); //uida is your string to be stored
editor.commit();
finish();
fetch...
SharedPreferences prefs = this.getSharedPreferences("msh", Context.MODE_PRIVATE);
uida = prefs.getString("id", "");
Prints all the rows with NA data:
tmp <- data.frame(c(1,2,3),c(4,NA,5));
tmp[round(which(is.na(tmp))/ncol(tmp)),]
The XLSB format is also dedicated to the macros embeded in an hidden workbook file located in excel startup folder (XLSTART).
A quick & dirty test with a xlsm or xlsb in XLSTART folder:
Measure-Command { $x = New-Object -com Excel.Application ;$x.Visible = $True ; $x.Quit() }
0,89s with a xlsb (binary) versus 1,3s with the same content in xlsm format (xml in a zip file) ... :)
My solution would be to use filter after the map.
This should support every JS data type.
example:
const notUndefined = anyValue => typeof anyValue !== 'undefined'
const noUndefinedList = someList
.map(// mapping condition)
.filter(notUndefined); // by doing this,
//you can ensure what's returned is not undefined
You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
Here is the cleanest way to do this:
<p ng-show="{{foo === undefined}}">Show this if $scope.foo === undefined</p>
No need to create a helper function in the controller!
If you want to checkout all the files 'anywhere'
git checkout -- $(git rev-parse --show-toplevel)
Here is a fast and highly readable way to get the min date value
Note: This is a Deterministic Function, so to improve performance further we might as well apply WITH SCHEMABINDING to the return value.
Create a function
CREATE FUNCTION MinDate()
RETURNS DATETIME WITH SCHEMABINDING
AS
BEGIN
RETURN CONVERT(DATETIME, -53690)
END
Call the function
dbo.MinDate()
Example 1
PRINT dbo.MinDate()
Example 2
PRINT 'The minimimum date allowed in an SQL database is ' + CONVERT(VARCHAR(MAX), dbo.MinDate())
Example 3
SELECT * FROM Table WHERE DateValue > dbo.MinDate()
Example 4
SELECT dbo.MinDate() AS MinDate
Example 5
DECLARE @MinDate AS DATETIME = dbo.MinDate()
SELECT @MinDate AS MinDate
For people who find this when attempting to run tests because via npm test
or ng test
using Karma or whatever else. Your .spec module needs a special router testing import to be able to build.
import { RouterTestingModule } from '@angular/router/testing';
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent],
});
http://www.kirjai.com/ng2-component-testing-routerlink-routeroutlet/
I came up with this simple and straight-forward (i hope so) code example which should explain itself!
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* function header definitions */
char* getString(); //<- with malloc (good practice)
char * getStringNoMalloc(); //<- without malloc (fails! don't do this!)
void getStringCallByRef(char* reference); //<- callbyref (good practice)
/* the main */
int main(int argc, char*argv[]) {
//######### calling with malloc
char * a = getString();
printf("MALLOC ### a = %s \n", a);
free(a);
//######### calling without malloc
char * b = getStringNoMalloc();
printf("NO MALLOC ### b = %s \n", b); //this doesnt work, question to yourself: WHY?
//HINT: the warning says that a local reference is returned. ??!
//NO free here!
//######### call-by-reference
char c[100];
getStringCallByRef(c);
printf("CALLBYREF ### c = %s \n", c);
return 0;
}
//WITH malloc
char* getString() {
char * string;
string = malloc(sizeof(char)*100);
strcat(string, "bla");
strcat(string, "/");
strcat(string, "blub");
printf("string : '%s'\n", string);
return string;
}
//WITHOUT malloc (watch how it does not work this time)
char* getStringNoMalloc() {
char string[100] = {};
strcat(string, "bla");
strcat(string, "/");
strcat(string, "blub");
//INSIDE this function "string" is OK
printf("string : '%s'\n", string);
return string; //but after returning.. it is NULL? :)
}
// ..and the call-by-reference way to do it (prefered)
void getStringCallByRef(char* reference) {
strcat(reference, "bla");
strcat(reference, "/");
strcat(reference, "blub");
//INSIDE this function "string" is OK
printf("string : '%s'\n", reference);
//OUTSIDE it is also OK because we hand over a reference defined in MAIN
// and not defined in this scope (local), which is destroyed after the function finished
}
When compiling it, you get the [intended] warning:
me@box:~$ gcc -o example.o example.c
example.c: In function ‘getStringNoMalloc’:
example.c:58:16: warning: function returns address of local variable [-Wreturn-local-addr]
return string; //but after returning.. it is NULL? :)
^~~~~~
...basically what we are discussing here!
running my example yields this output:
me@box:~$ ./example.o
string : 'bla/blub'
MALLOC ### a = bla/blub
string : 'bla/blub'
NO MALLOC ### b = (null)
string : 'bla/blub'
CALLBYREF ### c = bla/blub
Theory:
This has been answered very nicely by User @phoxis. Basically think about it this way: Everything inbetween { and } is local scope, thus by the C-Standard is "undefined" outside. By using malloc you take memory from the HEAP (programm scope) and not from the STACK (function scope) - thus its 'visible' from outside. The second correct way to do it is call-by-reference. Here you define the var inside the parent-scope, thus it is using the STACK (because the parent scope is the main()).
Summary:
3 Ways to do it, One of them false. C is kind of to clumsy to just have a function return a dynamically sized String. Either you have to malloc and then free it, or you have to call-by-reference. Or use C++ ;)
You could actually put the value = to the text and then do
$j(document).ready(function(){
$j("select#select_2").change(function(){
val = $j("#select_2 option:selected").html();
alert(val);
});
});
Or what I did on a similar case was
<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
with you're options here
</select>
With this second option you should have a undefined. Give me feedback if it worked :)
Patrick
There are two approaches: shmget
and mmap
. I'll talk about mmap
, since it's more modern and flexible, but you can take a look at man shmget
(or this tutorial) if you'd rather use the old-style tools.
The mmap()
function can be used to allocate memory buffers with highly customizable parameters to control access and permissions, and to back them with file-system storage if necessary.
The following function creates an in-memory buffer that a process can share with its children:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
void* create_shared_memory(size_t size) {
// Our memory buffer will be readable and writable:
int protection = PROT_READ | PROT_WRITE;
// The buffer will be shared (meaning other processes can access it), but
// anonymous (meaning third-party processes cannot obtain an address for it),
// so only this process and its children will be able to use it:
int visibility = MAP_SHARED | MAP_ANONYMOUS;
// The remaining parameters to `mmap()` are not important for this use case,
// but the manpage for `mmap` explains their purpose.
return mmap(NULL, size, protection, visibility, -1, 0);
}
The following is an example program that uses the function defined above to allocate a buffer. The parent process will write a message, fork, and then wait for its child to modify the buffer. Both processes can read and write the shared memory.
#include <string.h>
#include <unistd.h>
int main() {
char parent_message[] = "hello"; // parent process will write this message
char child_message[] = "goodbye"; // child process will then write this one
void* shmem = create_shared_memory(128);
memcpy(shmem, parent_message, sizeof(parent_message));
int pid = fork();
if (pid == 0) {
printf("Child read: %s\n", shmem);
memcpy(shmem, child_message, sizeof(child_message));
printf("Child wrote: %s\n", shmem);
} else {
printf("Parent read: %s\n", shmem);
sleep(1);
printf("After 1s, parent read: %s\n", shmem);
}
}
If the server is running as the foreground process in a terminal, this can be done by pressing
Ctrl-C
Another way to cleanly shut down a running server is to use the shutdown command,
> use admin
> db.shutdownServer();
Otherwise, a command like kill can be used to send the signal. If mongod has 10014 as its PID, the command would be
kill -2 10014
It isn't valid to have the same ID twice, that's why #name
only finds the first one.
You can try:
$("#form2 input").val('Hello World!');
Or,
$("#form2 input[name=name]").val('Hello World!');
If you're stuck with an invalid page and want to select all #name
s, you can use the attribute selector on the id:
$("input[id=name]").val('Hello World!');
Current date using momment.js in DD-MM-YYYY format
const currentdate=moment().format("DD-MM-YYYY");
console.log(currentdate)
I want to chime in here even though this question has already been answered correctly by @pscl in case anyone else runs into the same issue I did. Out of the 4 methods give I chose to use the es6 syntax with arrow functions due to it's conciseness and lack of dependence on external libraries:
Using Array.prototype.filter with ES6 Arrow Functions
removeItem(index) {
this.setState((prevState) => ({
data: prevState.data.filter((_, i) => i != index)
}));
}
As you can see I made a slight modification to ignore the type of index (!==
to !=
) because in my case I was retrieving the index from a string field.
Another helpful point if you're seeing weird behavior when removing an element on the client side is to NEVER use the index of an array as the key for the element:
// bad
{content.map((content, index) =>
<p key={index}>{content.Content}</p>
)}
When React diffs with the virtual DOM on a change, it will look at the keys to determine what has changed. So if you're using indices and there is one less in the array, it will remove the last one. Instead, use the id's of the content as keys, like this.
// good
{content.map(content =>
<p key={content.id}>{content.Content}</p>
)}
The above is an excerpt from this answer from a related post.
Happy Coding Everyone!
You can always tell EF to do this with conventions in the Context class in the OnModelCreating function as follows:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// <... other configurations ...>
// modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
// modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
// Configure Decimal to always have a precision of 18 and a scale of 4
modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
modelBuilder.Conventions.Add(new DecimalPropertyConvention(18, 4));
base.OnModelCreating(modelBuilder);
}
This only applies to Code First EF fyi and applies to all decimal types mapped to the db.
Create AMI -> Boot AMI on large instance.
More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html
You can do this all from the admin console too at aws.amazon.com
Go for the simplest and shortest if you can -- DISTINCT seems to be more what you are looking for only because it will give you EXACTLY the answer you need and only that!
Simple utility method:
public static boolean isBetween(int value, int min, int max)
{
return((value > min) && (value < max));
}
This worked for me for cardView and will work the same for listview inside adapter calss, within onBindViewHolder()
function
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return false;
}
});
It's also possible to customise your bootstrap build by using:
http://twitter.github.com/bootstrap/customize.html
All the plugins are included by default.
You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).
With primitives you guarantee that you will not pass null values.
You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
Use Boolean when you need an object, eg:
When you want start a new activity and finish the current activity you can do this:
API 11 or greater
Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
API 10 or lower
Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(IntentCompat.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
I hope this can help somebody =)
Don't enter the password with command. Just enter,
mysqldump -u <username> -p <db_name> > <backup_file>.sql
Then you will get a prompt to enter password.
I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.
Here's my reason why ...
I have populated a JavaFX ComboBox with the values of an Enum. I have an interface, Identifiable (specifying one method: identify), that allows me to specify how any object identifies itself to my application for searching purposes. This interface enables me to scan lists of any type of objects (whichever field the object may use for identity) for an identity match.
I'd like to find a match for an identity value in my ComboBox list. In order to use this capability on my ComboBox containing the Enum values, I must be able to implement the Identifiable interface in my Enum (which, as it happens, is trivial to implement in the case of an Enum).
I was able to get this to work by adding it to the body tag. Was nicer for me because I don't have anything on the html element.
body {
overflow-y: scroll;
}
jQuery has an AjaxSetup()
function that allows you to register global ajax handlers such as beforeSend
and complete
for all ajax calls as well as allow you to access the xhr
object to do the progress that you are looking for
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.
easiest way to clear form
<form #myForm="ngForm" (submit)="addPost();"> ... </form>
then in .ts file you need to access local variable of template i.e
@ViewChild('myForm') mytemplateForm : ngForm; //import { NgForm } from '@angular/forms';
for resetting values and state(pristine,touched..) do the following
addPost(){
this.newPost = {
title: this.mytemplateForm.value.title,
body: this.mytemplateForm.value.body
}
this._postService.addPost(this.newPost);
this.mytemplateForm.reset(); }
This is most cleanest way to clear the form
@magi182's solution is solid, but it lacks the ability to set a maximum width. I think a maximum width of 640px is necessary because otherwhise the youtube thumbnail looks pixelated.
My solution with two wrappers works like a charm for me:
.videoWrapperOuter {
max-width:640px;
margin-left:auto;
margin-right:auto;
}
.videoWrapperInner {
float: none;
clear: both;
width: 100%;
position: relative;
padding-bottom: 50%;
padding-top: 25px;
height: 0;
}
.videoWrapperInner iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div class="videoWrapperOuter">
<div class="videoWrapperInner">
<iframe src="//www.youtube.com/embed/C6-TWRn0k4I"
frameborder="0" allowfullscreen></iframe>
</div>
</div>
I also set the padding-bottom in the inner wrapper to 50 %, because with @magi182's 56 %, a black bar on top and bottom appeared.
You can also use the tag, this works in divs and everything else:
<center><form></form></center>
This link will help you with the tag:
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>
_x000D_
You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:
1 In Web.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
Internet or network address: your proxy address
User name: your user name
Password: you pass
This configuration worked for me, without change the code.
If your MySQL server runs on default settings, you don't need to specify that.
Default MySQL port is 3306.
[updated to show mysql_error() usage]
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die('Error connecting to mysql: '.mysql_error());
random.sample implement it.
>>> random.sample([1, 2, 3, 4, 5], 3) # Three samples without replacement
[4, 1, 5]
ThomasH has already added a good answer, but I want to show what happens:
>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, 3, 4, 4]
I guess Python parses the list comprehension from left to right. This means, the first for
loop that occurs will be executed first.
The second "problem" of this is that b
gets "leaked" out of the list comprehension. After the first successful list comprehension b == [3, 4]
.
▲
is the Unicode black up-pointing triangle (?) while ▼
is the black down-pointing triangle (?).
You can just plug the characters (copied from the web) into this site for a lookup.
Use let...of instead of let...in !!
If you're new to Angular (>2.x) and possibly migrating from Angular1.x, most likely you're confusing in
with of
. As andreas has mentioned in the comments below for ... of
iterates over values
of an object while for ... in
iterates over properties
in an object. This is a new feature introduced in ES2015.
Simply replace:
<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">
with
<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">
So, you must replace in
with of
inside ngFor
directive to get the values.
I implemented a function similar to the momentjs method subtract.
function addDate(dt, amount, dateType) {
switch (dateType) {
case 'days':
return dt.setDate(dt.getDate() + amount) && dt;
case 'weeks':
return dt.setDate(dt.getDate() + (7 * amount)) && dt;
case 'months':
return dt.setMonth(dt.getMonth() + amount) && dt;
case 'years':
return dt.setFullYear( dt.getFullYear() + amount) && dt;
}
}
example:
let dt = new Date();
dt = addDate(dt, -1, 'months');// use -1 to subtract
export enum dateAmountType {
DAYS,
WEEKS,
MONTHS,
YEARS,
}
export function addDate(dt: Date, amount: number, dateType: dateAmountType): Date {
switch (dateType) {
case dateAmountType.DAYS:
return dt.setDate(dt.getDate() + amount) && dt;
case dateAmountType.WEEKS:
return dt.setDate(dt.getDate() + (7 * amount)) && dt;
case dateAmountType.MONTHS:
return dt.setMonth(dt.getMonth() + amount) && dt;
case dateAmountType.YEARS:
return dt.setFullYear( dt.getFullYear() + amount) && dt;
}
}
example:
let dt = new Date();
dt = addDate(dt, -1, 'months'); // use -1 to subtract
I also made some unit-tests for this function using Jasmine:
it('addDate() should works properly', () => {
for (const test of [
{ amount: 1, dateType: dateAmountType.DAYS, expect: '2020-04-13'},
{ amount: -1, dateType: dateAmountType.DAYS, expect: '2020-04-11'},
{ amount: 1, dateType: dateAmountType.WEEKS, expect: '2020-04-19'},
{ amount: -1, dateType: dateAmountType.WEEKS, expect: '2020-04-05'},
{ amount: 1, dateType: dateAmountType.MONTHS, expect: '2020-05-12'},
{ amount: -1, dateType: dateAmountType.MONTHS, expect: '2020-03-12'},
{ amount: 1, dateType: dateAmountType.YEARS, expect: '2021-04-12'},
{ amount: -1, dateType: dateAmountType.YEARS, expect: '2019-04-12'},
]) {
expect(formatDate(addDate(new Date('2020-04-12'), test.amount, test.dateType))).toBe(test.expect);
}
});
To use this test you need this function:
// get format date as 'YYYY-MM-DD'
export function formatDate(date: Date): string {
const d = new Date(date);
let month = '' + (d.getMonth() + 1);
let day = '' + d.getDate();
const year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [year, month, day].join('-');
}
This is the shortest, most practical I can comeup with without importing extra modules.
text = "hello cruel world. This is a sample text"
d = dict.fromkeys(text, 0)
for c in text: d[c] += 1
print d['a'] would output 2
And it's also fast.
Always use latest SDK version to build:
compileSdkVersion 23
It does not affect runtime behavior, but give you latest programming features.
Use Array.prototype.map()
with an arrow function:
const arrayColumn = (arr, n) => arr.map(x => x[n]);_x000D_
_x000D_
const twoDimensionalArray = [_x000D_
[1, 2, 3],_x000D_
[4, 5, 6],_x000D_
[7, 8, 9],_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 0));
_x000D_
Note: Array.prototype.map()
and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.
It is txtName.BackColor = System.Drawing.Color.Red;
one can also use txtName.BackColor = Color.Aqua;
which is the same as txtName.BackColor = System.Color.Aqua;
Only Problem with System.color is that it does not contain a definition for some basic colors especially white, which is important cause usually textboxes are white;
You can use the properties tab in eclipse to set various values.
here are all the possible values
Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
I believe that Notepad++ has this feature.
Edit (for newer versions)
Install the "XML Tools" plugin (Menu Plugins, Plugin Manager)
Then run: Menu Plugins, Xml Tools, Pretty Print (XML only - with line breaks)
Original answer (for older versions of Notepad++)
Notepad++ menu: TextFX -> HTML Tidy -> Tidy: Reindent XML
This feature however wraps XMLs and that makes it look 'unclean'. To have no wrap,
C:\Program Files\Notepad++\plugins\Config\tidy\TIDYCFG.INI
, [Tidy: Reindent XML]
and add wrap:0
so that it looks like this: [Tidy: Reindent XML] input-xml: yes indent:yes wrap:0
In your example you are comparing the string objects, not their content.
Your comparison should be :
if (s.equals("/quit"))
Or if s
string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))
It may be easier. Try to think like this:
:
// 'www.dev.yyy.com'
// 'xxx.foo.pl'
var url = "xxx.foo.pl";
switch (url.match(/\..*.\./)[0]){
case ".dev.yyy." :
console.log("xxx.dev.yyy.com");break;
case ".some.":
console.log("xxx.foo.pl");break;
} //end switch
You can create the vector idnat2
without if
and ifelse
.
The function replace
can be used to replace all occurrences of "colony"
with "overseas"
:
idnat2 <- replace(idbp, idbp == "colony", "overseas")
You are getting an authentication error because the username and password in your config file is setup wrong.
Change this:
'username' => env('[email protected]'),
'password' => env('MyPassword'),
To this:
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
The env
method checks your .env file. In your .env file you call these MAIL_USERNAME
, so that's what you need to pass to the env
method.
One troubleshooting tip: add dd(Config::get('mail'));
so that you can see the actual generated config. This will help you spot issues like this, and know exactly what information Laravel is going to try and use. So you may want to stop that in your test route temporarily to examine what you have:
Route::get('test', function()
{
dd(Config::get('mail'));
});
npm install font-awesome --save
add ~/ before path
@import "~/font-awesome/scss/font-awesome.scss";
Or perhaps something like this?
let win = {_x000D_
'location': {_x000D_
'path': 'http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla'_x000D_
}_x000D_
}_x000D_
if (win.location.path.match('__firebase_request_key').length) {_x000D_
let key = win.location.path.split('__firebase_request_key=')[1]_x000D_
console.log(key)_x000D_
}
_x000D_
Here, Apple Documentation has explained the difference between weak and strong property using various examples :
Here, In this blog author has collected all the properties in same place. It will help to compare properties characteristics :
http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html
If you have an object and wish to become JObject you can use:
JObject o = (JObject)JToken.FromObject(miObjetoEspecial);
like this :
Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};
JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}
You're in replace mode. Press the Insert
key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.
I dont know but none of the above worked for me, Then i used this and it worked :
In form's serialized array it is stored as key value pair
We pushed the new value or values here in form variable and then we can pass this variable directly now.
var form = $('form.sigPad').serializeArray();
var uniquekey = {
name: "uniquekey",
value: $('#UniqueKey').val()
};
form.push(uniquekey);
As delnan pointed out, the match
keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the String.matches
method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:
word.matches("[a-cA-C].*")
You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" (.
means "any character" and *
means "zero or more times", so ".*" is any string).
There is an insightful blog post about it.
See https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/.
I paraphrase its content below.
In python 2 which was not as strongly typed regarding the encoding of strings you could perform operations on differently encoded strings, and succeed. E.g. the following would return True
.
u'Toshio' == 'Toshio'
That would hold for every (normal, unprefixed) string that was encoded in sys.getdefaultencoding()
, which defaulted to ascii
, but not others.
The default encoding was meant to be changed system-wide in site.py
, but not somewhere else. The hacks (also presented here) to set it in user modules were just that: hacks, not the solution.
Python 3 did changed the system encoding to default to utf-8 (when LC_CTYPE is unicode-aware), but the fundamental problem was solved with the requirement to explicitly encode "byte"strings whenever they are used with unicode strings.
Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different
Table structure
CREATE TABLE ITEMS (
N INTEGER NOT NULL,
S TEXT NOT NULL
);
INSERT INTO ITEMS
SELECT
(random()*1000000)::integer AS n,
md5(random()::text) AS s
FROM
generate_series(1,1000000);
CREATE INDEX N_INDEX ON ITEMS(N);
Performing JOIN
with GROUP BY
in subquery without LATERAL
EXPLAIN
SELECT
I.*
FROM ITEMS I
INNER JOIN (
SELECT
COUNT(1), n
FROM ITEMS
GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);
The results
Merge Join (cost=0.87..637500.40 rows=23 width=37)
Merge Cond: (i.n = items.n)
-> Index Scan using n_index on items i (cost=0.43..101.28 rows=23 width=37)
Index Cond: (n = ANY ('{243477,997947}'::integer[]))
-> GroupAggregate (cost=0.43..626631.11 rows=861418 width=12)
Group Key: items.n
-> Index Only Scan using n_index on items (cost=0.43..593016.93 rows=10000000 width=4)
Using LATERAL
EXPLAIN
SELECT
I.*
FROM ITEMS I
INNER JOIN LATERAL (
SELECT
COUNT(1), n
FROM ITEMS
WHERE N = I.N
GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);
Results
Nested Loop (cost=9.49..1319.97 rows=276 width=37)
-> Bitmap Heap Scan on items i (cost=9.06..100.20 rows=23 width=37)
Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
-> Bitmap Index Scan on n_index (cost=0.00..9.05 rows=23 width=0)
Index Cond: (n = ANY ('{243477,997947}'::integer[]))
-> GroupAggregate (cost=0.43..52.79 rows=12 width=12)
Group Key: items.n
-> Index Only Scan using n_index on items (cost=0.43..52.64 rows=12 width=4)
Index Cond: (n = i.n)
My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)
you gave the following example in your question:
colnames(merger)[,1]<-"Date"
the problem is the comma: colnames() returns a vector, not a matrix, so the solution is:
colnames(merger)[1]<-"Date"
select @EmpID = ID from dbo.Employee
Or
set @EmpID =(select id from dbo.Employee)
Note that the select query might return more than one value or rows. so you can write a select query that must return one row.
If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable
DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..
As table type variable do not exist in Oracle and others, you would have to define it:
DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;
-- Then to declare a TABLE variable of this type: variable_name type_name;
-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text'
;
-- Where 'n' is the index value
System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();
Substitute the right encoding above: e.g.
System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();
self
is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main()
, you first have to instantiate an object of your class and call the function on the object.
Further, your function setavalue
should be in __init___
, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name
class ;)
class Name:
def __init__(self):
self.myname = "harry"
def printaname(self):
print "Name", self.myname
def main(self):
self.printaname()
if __name__ == "__main__":
objName = Name()
objName.main()
Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.
Select table--> Design--> change value in Data Type shown in following Fig.
Save tables design.
Sometimes you just need to recreate new device
And to complement Rich's recursive answer, a non-recursive method.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1)
with Set oFolder = queue(queue.Count)
and replace queue.Remove(1)
with queue.Remove(queue.Count)
, and probably rename the variable...)
A lot of focus in the suggestions above on inventing ways in runtime to pass in variables, set them and clear them and so on..? But to test things 'structurally', I guess you want to have different test suites for different scenarios? Pretty much like when you want to run your 'heavier' integration test builds, whereas in most cases you just want to skip them. But then you don't try and 'invent ways to set stuff in runtime', rather you just tell maven what you want? It used to be a lot of work telling maven to run specific tests via profiles and such, if you google around people would suggest doing it via springboot (but if you haven't dragged in the springboot monstrum into your project, it seems a horrendous footprint for 'just running JUnits', right?). Or else it would imply loads of more or less inconvenient POM XML juggling which is also tiresome and, let's just say it, 'a nineties move', as inconvenient as still insisting on making 'spring beans out of XML', showing off your ultimate 600 line logback.xml or whatnot...?
Nowadays, you can just use Junit 5 (this example is for maven, more details can be found here JUnit 5 User Guide 5)
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.7.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
and then
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
and then in your favourite utility lib create a simple nifty annotation class such as
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@EnabledIfEnvironmentVariable(named = "MAVEN_CMD_LINE_ARGS", matches = "(.*)integration-testing(.*)")
public @interface IntegrationTest {}
so then whenever your cmdline options contain -Pintegration-testing for instance, then and only then will your @IntegrationTest annotated test-class/method fire. Or, if you don't want to use (and setup) a specific maven profile but rather just pass in 'trigger' system properties by means of
mvn <cmds> -DmySystemPop=mySystemPropValue
and adjust your annotation interface to trigger on that (yes, there is also a @EnabledIfSystemProperty). Or making sure your shell is set up to contain 'whatever you need' or, as is suggested above, actually going through 'the pain' adding system env via your POM XML.
Having your code internally in runtime fiddle with env or mocking env, setting it up and then possibly 'clearing' runtime env to change itself during execution just seems like a bad, perhaps even dangerous, approach - it's easy to imagine someone will always sooner or later make a 'hidden' internal mistake that will go unnoticed for a while, just to arise suddenly and bite you hard in production later..? You usually prefer an approach entailing that 'given input' gives 'expected output', something that is easy to grasp and maintain over time, your fellow coders will just see it 'immediately'.
Well long 'answer' or maybe rather just an opinion on why you'd prefer this approach (yes, at first I just read the heading for this question and went ahead to answer that, ie 'How to test code dependent on environment variables using JUnit').
Brackets are used around identifiers, so your code will look for the field %'%
in the Header
table. You want to use a string insteaed. To put an apostrophe in a string literal you use double apostrophes.
SELECT *
FROM Header WHERE userID LIKE '%''%'
I use this function to get payload , header , exp(Expiration Time), iat (Issued At) based on this answer
function parseJwt(token) {
try {
// Get Token Header
const base64HeaderUrl = token.split('.')[0];
const base64Header = base64HeaderUrl.replace('-', '+').replace('_', '/');
const headerData = JSON.parse(window.atob(base64Header));
// Get Token payload and date's
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
const dataJWT = JSON.parse(window.atob(base64));
dataJWT.header = headerData;
// TODO: add expiration at check ...
return dataJWT;
} catch (err) {
return false;
}
}
const jwtDecoded = parseJwt('YOUR_TOKEN') ;
if(jwtDecoded)
{
console.log(jwtDecoded)
}
The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?
1) Download instantclient (http://www.oracle.com/technetwork/topics/winsoft-085727.html)
2) Unzip the ZIP file (eg c:\oracle\instantclient).
3) Include the above path in the PATH.
4) Create the registry key:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]
5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_INSTANTCLIENT]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE\KEY_INSTANTCLIENT]
6) Now create at least three string values ??in the above key:
NLS_LANG = BRAZILIAN PORTUGUESE_BRAZIL.WE8MSWIN1252
(complete list here: http://docs.oracle.com/cd/B19306_01/install.102/b14317/gblsupp.htm)ORACLE_HOME = c:\oracle\instantclient
(the same folder in PATH)ORACLE_HOME_NAME = MY_INSTANTCLIENT
(choose any name)For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":
The registry keys are now displayed for selecting the oracle client:
Yes I think You can get it download and separately its Help files from: vbdecompiler.org Site. and there is a Video on YouTube which explains how to Use it to Get the Code from an exe file and Save it. I hope that I helped.
In my case, I was getting this exact error running on port 443, and (for reasons I won't go into here) switching to a different port was not an option. In order to get IIS Express to work on port 443, I had to run this command...
C:\Program Files\IIS Express>IisExpressAdminCmd.exe setupsslUrl -url:https://localhost:443/ -UseSelfSigned
Much thanks to Robert Muehsig for originally posting this solution here.
Consider using the E.164 format. For full international support, you'd need a VARCHAR of 15 digits.
See Twilio's recommendation for more information on localization of phone numbers.
"This is my string with date in specified format $($theDate.ToString('u'))"
or
"This is my string with date in specified format $(Get-Date -format 'u')"
The sub-expression ($(...)
) can include arbitrary expressions calls.
MSDN Documents both standard and custom DateTime
format strings.
I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.
SELECT Column1
FROM TableA a
WHERE NOT EXISTS ( SELECT Column1
FROM Tableb b
WHERE a.Column1 = b.Column1
)
I had the same problem and I solved it using the lib
option in tsconfig.json
. As said by basarat in his answer, a .d.ts
file is implicitly included by TypeScript depending on the compile target
option but this behaviour can be changed with the lib
option.
You can specify additional definition files to be included without changing the targeted JS version. For examples this is part of my current compilerOptions
for [email protected] and it adds support for es2015
features without installing anything else:
"compilerOptions": {
"experimentalDecorators": true,
"lib": ["es5", "dom", "es6", "dom.iterable", "scripthost"],
"module": "commonjs",
"moduleResolution": "node",
"noLib": false,
"target": "es5",
"types": ["node"]
}
For the complete list of available options check the official doc.
Note also that I added "types": ["node"]
and installed npm install @types/node
to support require('some-module')
in my code.
Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.
For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:
For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.
In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.
May be it's too late but the following code works fine
document.getElementById('alrt').innerHTML='<b>Please wait, Your download will start soon!!!</b>';
setTimeout(function() {document.getElementById('alrt').innerHTML='';},5000);
<div id='alrt' style="fontWeight = 'bold'"></div>
After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it
I'm using the change-case extension and it works fine. I defined the shortcuts:
{
"key": "ctrl+shift+u",
"command": "extension.changeCase.upper",
"when": "editorTextFocus"
},
{
"key": "ctrl+u",
"command": "extension.changeCase.lower",
"when": "editorTextFocus"
},
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});