I went for a simpler approach:
HTML
<div class="box">
<h1 class="text">OK THEN LETS GO</h1>
<hr class="line" />
</div>
CSS
.box {
align-items: center;
background: #ff7777;
display: flex;
height: 100vh;
justify-content: center;
}
.line {
border: 5px solid white;
display: block;
width: 100vw;
}
.text {
background: #ff7777;
color: white;
font-family: sans-serif;
font-size: 2.5rem;
padding: 25px 50px;
position: absolute;
}
Result
For create mysql where conditions from array
$sWheres = array('item1' => 'object1',
'item2' => 'object2',
'item3' => 1,
'item4' => array(4,5),
'item5' => array('object3','object4'));
$sWhere = '';
if(!empty($sWheres)){
$sWhereConditions = array();
foreach ($sWheres as $key => $value){
if(!empty($value)){
if(is_array($value)){
$value = array_filter($value); // For remove blank values from array
if(!empty($value)){
array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'
$sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));
}
}else{
$sWhereConditions[] = sprintf("%s='%s'", $key, $value);
}
}
}
if(!empty($sWhereConditions)){
$sWhere .= "(".implode(' AND ', $sWhereConditions).")";
}
}
echo $sWhere; // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))
As mentioned in the comments, the Starting Guide is the place to start with Java 11 and JavaFX 11.
The key to work as you did before Java 11 is to understand that:
JavaFX project
If you create a regular JavaFX default project in IntelliJ (without Maven or Gradle) I'd suggest you download the SDK from here. Note that there are jmods as well, but for a non modular project the SDK is preferred.
These are the easy steps to run the default project:
/Users/<user>/Downloads/javafx-sdk-11/lib/
. Once you do this you will notice that the JavaFX classes are now recognized in the editor.Before you run the default project, you just need to add these to the VM options:
--module-path /Users/<user>/Downloads/javafx-sdk-11/lib --add-modules=javafx.controls,javafx.fxml
Run
Maven
If you use Maven to build your project, follow these steps:
Add the JavaFX 11 dependencies.
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11</version>
</dependency>
</dependencies>
Once you do this you will notice that the JavaFX classes are now recognized in the editor.
You will notice that Maven manages the required dependencies for you: it will add javafx.base and javafx.graphics for javafx.controls, but most important, it will add the required classifier based on your platform. In my case, Mac.
This is why your jars org.openjfx:javafx-controls:11
are empty, because there are three possible classifiers (windows, linux and mac platforms), that contain all the classes and the native implementation.
In case you still want to go to your .m2 repo and take the dependencies from there manually, make sure you pick the right one (for instance .m2/repository/org/openjfx/javafx-controls/11/javafx-controls-11-mac.jar
)
Replace default maven plugins with those from here.
Run mvn compile javafx:run
, and it should work.
Similar works as well for Gradle projects, as explained in detail here.
EDIT
The mentioned Getting Started guide contains updated documentation and sample projects for IntelliJ:
JavaFX 11 without Maven/Gradle, see non-modular sample or modular sample projects.
JavaFX 11 with Maven, see non-modular sample or modular sample projects.
JavaFX 11 with Gradle, see non-modular sample or modular sample projects.
BR is an inline element, not a block element.
So, you need:
br.Underline{
border-bottom:1px dashed black;
display: block;
}
Otherwise, browsers that are a little pickier about such things will refuse to apply borders to your BR elements, since inline elements don't have borders, padding, or margins.
1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file.
There you go!
Is this what you are looking for?
Option Explicit
Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal col As Integer)
Dim lLastRow As Long
Dim iHeader As Integer
With ActiveSheet.ListObjects(strTableName)
'find the last row of the list
lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.Count
'shift from an extra row if list has header
If .Sort.Header = xlYes Then
iHeader = 1
Else
iHeader = 0
End If
End With
'add the data a row after the end of the list
ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = strData
End Sub
It handles both cases whether you have header or not.
$(document).ready(function () {_x000D_
$(document).mousemove(function () {_x000D_
$('#myList').css('display', 'block');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$("#hidebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
var fileArray1 = document.getElementsByClassName('file-input');_x000D_
for (var i = 0; i < fileArray1.length; i++) {_x000D_
var files = fileArray1[i].files;_x000D_
for (var j = 0; j < files.length; j++) {_x000D_
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");_x000D_
}_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) != '') {_x000D_
$('#unselect').css('display', 'block');_x000D_
$('#divforfile').css('color', 'green');_x000D_
$('#attach').css('color', 'green');_x000D_
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');_x000D_
_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) == '') {_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
$('#displayFileNames').append('Nessun File Selezionato');_x000D_
};_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
function choosefiles(obj) {_x000D_
$(obj).hide();_x000D_
$('#myList').css('display', 'none');_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#unselect').css('display', 'none');_x000D_
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");_x000D_
$('#displayFileNames').html('');_x000D_
}_x000D_
_x000D_
$(document).ready(function () {_x000D_
$('#unselect').click(function () {_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
$('#myFileInput').val('');_x000D_
document.getElementById('upload-form').reset(); _x000D_
$('#unselect').css('display', 'none');_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
_x000D_
});_x000D_
});
_x000D_
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
<style>_x000D_
.divs {_x000D_
position: absolute;_x000D_
display: inline-block;_x000D_
background-color: #fff;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
height: 2%;_x000D_
width: 15%;_x000D_
opacity: 0;_x000D_
background: #00f;_x000D_
z-index: 100;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
</style>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>_x000D_
_x000D_
<div class="divs" id="divforfile" style="color:black">_x000D_
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />_x000D_
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>_x000D_
</div>_x000D_
</form>_x000D_
<br />_x000D_
</div>_x000D_
<br /> _x000D_
<div>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>_x000D_
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">_x000D_
<span style="color:red">×</span>_x000D_
</button>_x000D_
<div id="displayFileNames">_x000D_
</div>_x000D_
<ul id="myList"></ul>_x000D_
</div>
_x000D_
This is my fully functional customerized file upload/Attachment using jquery & javascript (Visual studio). This will be useful !
Code will be available at the comment section !
Link : https://youtu.be/It38OzMAeig
Enjoy :)
$(document).ready(function () {_x000D_
$(document).mousemove(function () {_x000D_
$('#myList').css('display', 'block');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$("#hidebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
var fileArray1 = document.getElementsByClassName('file-input');_x000D_
for (var i = 0; i < fileArray1.length; i++) {_x000D_
var files = fileArray1[i].files;_x000D_
for (var j = 0; j < files.length; j++) {_x000D_
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");_x000D_
}_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) != '') {_x000D_
$('#unselect').css('display', 'block');_x000D_
$('#divforfile').css('color', 'green');_x000D_
$('#attach').css('color', 'green');_x000D_
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');_x000D_
_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) == '') {_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
$('#displayFileNames').append('Nessun File Selezionato');_x000D_
};_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
function choosefiles(obj) {_x000D_
$(obj).hide();_x000D_
$('#myList').css('display', 'none');_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#unselect').css('display', 'none');_x000D_
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");_x000D_
$('#displayFileNames').html('');_x000D_
}_x000D_
_x000D_
$(document).ready(function () {_x000D_
$('#unselect').click(function () {_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
$('#myFileInput').val('');_x000D_
document.getElementById('upload-form').reset(); _x000D_
$('#unselect').css('display', 'none');_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
_x000D_
});_x000D_
});
_x000D_
<style>_x000D_
.divs {_x000D_
position: absolute;_x000D_
display: inline-block;_x000D_
background-color: #fff;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
height: 2%;_x000D_
width: 15%;_x000D_
opacity: 0;_x000D_
background: #00f;_x000D_
z-index: 100;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
</style>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
_x000D_
<div>_x000D_
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>_x000D_
_x000D_
<div class="divs" id="divforfile" style="color:black">_x000D_
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />_x000D_
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>_x000D_
</div>_x000D_
</form>_x000D_
<br />_x000D_
</div>_x000D_
<br /> _x000D_
<div>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>_x000D_
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">_x000D_
<span style="color:red">×</span>_x000D_
</button>_x000D_
<div id="displayFileNames">_x000D_
</div>_x000D_
<ul id="myList"></ul>_x000D_
</div>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
$(document).mousemove(function () {_x000D_
$('#myList').css('display', 'block');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$("#hidebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
var fileArray1 = document.getElementsByClassName('file-input');_x000D_
for (var i = 0; i < fileArray1.length; i++) {_x000D_
var files = fileArray1[i].files;_x000D_
for (var j = 0; j < files.length; j++) {_x000D_
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");_x000D_
}_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) != '') {_x000D_
$('#unselect').css('display', 'block');_x000D_
$('#divforfile').css('color', 'green');_x000D_
$('#attach').css('color', 'green');_x000D_
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');_x000D_
_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) == '') {_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
$('#displayFileNames').append('Nessun File Selezionato');_x000D_
};_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
function choosefiles(obj) {_x000D_
$(obj).hide();_x000D_
$('#myList').css('display', 'none');_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#unselect').css('display', 'none');_x000D_
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");_x000D_
$('#displayFileNames').html('');_x000D_
}_x000D_
_x000D_
$(document).ready(function () {_x000D_
$('#unselect').click(function () {_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
$('#myFileInput').val('');_x000D_
document.getElementById('upload-form').reset(); _x000D_
$('#unselect').css('display', 'none');_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
_x000D_
});_x000D_
});
_x000D_
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
<style>_x000D_
.divs {_x000D_
position: absolute;_x000D_
display: inline-block;_x000D_
background-color: #fff;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
height: 2%;_x000D_
width: 15%;_x000D_
opacity: 0;_x000D_
background: #00f;_x000D_
z-index: 100;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
</style>
_x000D_
<div>_x000D_
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>_x000D_
_x000D_
<div class="divs" id="divforfile" style="color:black">_x000D_
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />_x000D_
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>_x000D_
</div>_x000D_
</form>_x000D_
<br />_x000D_
</div>_x000D_
<br /> _x000D_
<div>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>_x000D_
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">_x000D_
<span style="color:red">×</span>_x000D_
</button>_x000D_
<div id="displayFileNames">_x000D_
</div>_x000D_
<ul id="myList"></ul>_x000D_
</div>
_x000D_
For a search routine you should look to use Find
, AutoFilter
or variant array approaches. Range loops are nomally too slow, worse again if they use Select
The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2
which you can then further process
Option Explicit
Const strText As String = "%"
Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
With Application
lAppCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
If Not cel1 Is Nothing Then
Set rng2 = cel1
strFirstAddress = cel1.Address
Do
Set cel1 = rng1.FindNext(cel1)
Set rng2 = Union(rng2, cel1)
Loop While strFirstAddress <> cel1.Address
End If
If Not rng2 Is Nothing Then
For Each cel2 In rng2
Debug.Print cel2.Address & " contained " & strText
Next
Else
MsgBox "No " & strText
End If
With Application
.ScreenUpdating = True
.Calculation = lAppCalc
End With
End Sub
This works for me:
.network-connections-icon {
background-image: url(url);
background-size: 100%;
width: 56px;
height: 56px;
margin: 0 auto;
}
Use '›'
›
-> single right angle quote. For single left angle quote, use ‹
In case you wish to keep the current version of angular, you can visit this version compatibility checker to check which version of angular-material is best for your current angular version. You can also check peer dependencies of angular-material using angular-material compatibility.
Try this for multiple text fileds (using class selector):
var checking = function(event){_x000D_
var data = this.value;_x000D_
if((event.charCode>= 48 && event.charCode <= 57) || event.charCode== 46 ||event.charCode == 0){_x000D_
if(data.indexOf('.') > -1){_x000D_
if(event.charCode== 46)_x000D_
event.preventDefault();_x000D_
}_x000D_
}else_x000D_
event.preventDefault();_x000D_
};_x000D_
_x000D_
function addListener(list){_x000D_
for(var i=0;i<list.length;i++){_x000D_
list[i].addEventListener('keypress',checking);_x000D_
}_x000D_
}_x000D_
var classList = document.getElementsByClassName('number');_x000D_
addListener(classList);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Page Title</title>_x000D_
</head>_x000D_
<body>_x000D_
<input type="text" class="number" value="" /><br><br>_x000D_
<input type="text" class="number" value="" /><br><br>_x000D_
<input type="text" class="number" value="" /><br><br>_x000D_
<input type="text" class="number" value="" /><br><br>_x000D_
</body>_x000D_
</html>
_x000D_
The problem is that you compiled the code with java 13 (class file 57), and the java runtime is set to java 8 (class file 52).
Assuming you have the JRE 13 installed in your local system, you could change your runtime from 52 to 57. That you can do with the plugin Choose Runtime. To install it go to File/Settings/Plugins
Once installed go to Help/Find Action, type "runtime" and select the jre 13 from the dropdown menu.
You have to specify the folder where you are saving it and it has to exist, in other case it will throw an error.
var s = txt.CreateTextFile("c:\\11.txt", true);
I think we should go with StringBuilder append approach. Reason being :
The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects.
With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.
This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:
Math.max(input, 0);
If you need to ensure a minimum value, usually you'd do
var number = Number(input);
if (number < 0) number = 0;
Math.max(..., 0)
saves you from writing two statements.
std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K
and V
.
Also bear in mind that std::sort
requires a strict weak ordeing comparison, and <=
does not satisfy that. You would need, for example, a less-than comparison <
for K
and V
. With that in place, all you need is
std::vector<pair<K,V>> items;
std::sort(items.begin(), items.end());
If you really need to provide your own comparison function, then you need something along the lines of
template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
return lhs.first < rhs.first;
}
So you´re repeating lots of code within every exception-switch? Sounds like extracting a method would be god idea, doesn´t it?
So your code comes down to this:
MyClass instance;
try { instance = ... }
catch(Exception1 e) { Reset(instance); }
catch(Exception2 e) { Reset(instance); }
catch(Exception) { throw; }
void Reset(MyClass instance) { /* reset the state of the instance */ }
I wonder why no-one noticed that code-duplication.
From C#6 you furthermore have the exception-filters as already mentioned by others. So you can modify the code above to this:
try { ... }
catch(Exception e) when(e is Exception1 || e is Exception2)
{
Reset(instance);
}
I had similar issue on MacBook Pro, I just followed the below link and issue got resolved. https://projectlombok.org/setup/eclipse
Steps followed:-
Yes, because in your case they use the same representation.
The bit pattern 0xFFFFFFFF
happens to look like -1 when interpreted as a 32b signed integer and as 4294967295 when interpreted as a 32b unsigned integer.
It's the same as char c = 65
. If you interpret it as a signed integer, it's 65. If you interpret it as a character it's a
.
As R and pmg point out, technically it's undefined behavior to pass arguments that don't match the format specifiers. So the program could do anything (from printing random values to crashing, to printing the "right" thing, etc).
The standard points it out in 7.19.6.1-9
If a conversion speci?cation is invalid, the behavior is unde?ned. If any argument is not the correct type for the corresponding conversion speci?cation, the behavior is unde?ned.
You can do this in one query if you're willing to change its name:
ALTER TABLE table_name
DROP FOREIGN KEY `fk_name`,
ADD CONSTRAINT `fk_name2` FOREIGN KEY (`remote_id`)
REFERENCES `other_table` (`id`)
ON DELETE CASCADE;
This is useful to minimize downtime if you have a large table.
So, let's say you have this table:
CREATE TABLE YourTable(Col1 VARCHAR(10))
And you want to change Col1
to VARCHAR(20)
. What you need to do is this:
ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)
That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5)
, then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE
will fail.
IEEE 754 defines 1.0 / 0.0
as Infinity and -1.0 / 0.0
as -Infinity and 0.0 / 0.0
as NaN.
By the way, floating point values also have -0.0
and so 1.0/ -0.0
is -Infinity
.
Integer arithmetic doesn't have any of these values and throws an Exception instead.
To check for all possible values (e.g. NaN, 0.0, -0.0) which could produce a non finite number you can do the following.
if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
throw new ArithmeticException("Not finite");
• August, 2011: Microsoft deprecates OLE DB (Microsoft is Aligning with ODBC for Native Relational Data Access)
• October, 2017: Microsoft undeprecates OLE DB (Announcing the new release of OLE DB Driver for SQL Server)
I would suggest using originalUrl instead of URL:
var url = req.protocol + '://' + req.get('host') + req.originalUrl;
See the description of originalUrl here: http://expressjs.com/api.html#req.originalUrl
In our system, we do something like this, so originalUrl is important to us:
foo = express();
express().use('/foo', foo);
foo.use(require('/foo/blah_controller'));
blah_controller looks like this:
controller = express();
module.exports = controller;
controller.get('/bar/:barparam', function(req, res) { /* handler code */ });
So our URLs have the format:
www.example.com/foo/bar/:barparam
Hence, we need req.originalUrl in the bar controller get handler.
If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.
s = set()
if number1 not in s:
s.add(number1)
if number2 not in s:
s.add(number2)
...
s = sorted(s) #Now a list in ascending order
Use cURL:
*/5 * * * * curl http://example.com/check/
I found this solution to be quite handy. It uses the -or
option in find
:
find . -name \*.tex -or -name "*.png" -or -name "*.pdf"
It will find the files with extension tex
, png
, and pdf
.
This is an extension to BigJim's brilliant answer.
In my case I had a NodeBase
class with a Children
dictionary, and I needed a way to generically do O(1) lookups from the children. I was attempting to return a private dictionary field in the getter of Children
, so obviously I wanted to avoid expensive copying/iterating. Therefore I used Bigjim's code to cast the Dictionary<whatever specific type>
to a generic Dictionary<NodeBase>
:
// Abstract parent class
public abstract class NodeBase
{
public abstract IDictionary<string, NodeBase> Children { get; }
...
}
// Implementing child class
public class RealNode : NodeBase
{
private Dictionary<string, RealNode> containedNodes;
public override IDictionary<string, NodeBase> Children
{
// Using a modification of Bigjim's code to cast the Dictionary:
return new IDictionary<string, NodeBase>().CastDictionary<string, RealNode, NodeBase>();
}
...
}
This worked well. However, I eventually ran into unrelated limitations and ended up creating an abstract FindChild()
method in the base class that would do the lookups instead. As it turned out this eliminated the need for the casted dictionary in the first place. (I was able to replace it with a simple IEnumerable
for my purposes.)
So the question you might ask (especially if performance is an issue prohibiting you from using .Cast<>
or .ConvertAll<>
) is:
"Do I really need to cast the entire collection, or can I use an abstract method to hold the special knowledge needed to perform the task and thereby avoid directly accessing the collection?"
Sometimes the simplest solution is the best.
I use a CSS fix rather than JS to workaround my round cornered layer with transparent PNG inside
Try
.ie .whateverDivWrappingTheImage img { background: #ffaabb; /* this should be the background color matching your design actually */ filter: chroma(#ffaabb); /* and this should match whatever value you put in background-color */ }
This may require more work on ie9 or later.
The simplest solution to run two Python processes concurrently is to run them from a bash file, and tell each process to go into the background with the &
shell operator.
python script1.py &
python script2.py &
For a more controlled way to run many processes in parallel, look into the Supervisor project, or use the multiprocessing module to orchestrate from inside Python.
The answers above didn't work for me. I found a very good article for Favicon, explaining:
So I created Favicon using FavIcon from Pics
. Put it in folder (named favicon) and add this code in <head>
tag:
<link rel="shortcut icon" href="favicon/favicon.ico">
<link rel="icon" type="image/gif" href="favicon/animated_favicon1.gif">
Now there is no error and I see my Favicon:
Predicate<T>
is a functional construct providing a convenient way of basically testing if something is true of a given T
object.
For example suppose I have a class:
class Person {
public string Name { get; set; }
public int Age { get; set; }
}
Now let's say I have a List<Person> people
and I want to know if there's anyone named Oscar in the list.
Without using a Predicate<Person>
(or Linq, or any of that fancy stuff), I could always accomplish this by doing the following:
Person oscar = null;
foreach (Person person in people) {
if (person.Name == "Oscar") {
oscar = person;
break;
}
}
if (oscar != null) {
// Oscar exists!
}
This is fine, but then let's say I want to check if there's a person named "Ruth"? Or a person whose age is 17?
Using a Predicate<Person>
, I can find these things using a LOT less code:
Predicate<Person> oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate<Person> ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate<Person> seventeenYearOldFinder = (Person p) => { return p.Age == 17; };
Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventeenYearOldFinder);
Notice I said a lot less code, not a lot faster. A common misconception developers have is that if something takes one line, it must perform better than something that takes ten lines. But behind the scenes, the Find
method, which takes a Predicate<T>
, is just enumerating after all. The same is true for a lot of Linq's functionality.
So let's take a look at the specific code in your question:
Predicate<int> pre = delegate(int a){ return a % 2 == 0; };
Here we have a Predicate<int> pre
that takes an int a
and returns a % 2 == 0
. This is essentially testing for an even number. What that means is:
pre(1) == false;
pre(2) == true;
And so on. This also means, if you have a List<int> ints
and you want to find the first even number, you can just do this:
int firstEven = ints.Find(pre);
Of course, as with any other type that you can use in code, it's a good idea to give your variables descriptive names; so I would advise changing the above pre
to something like evenFinder
or isEven
-- something along those lines. Then the above code is a lot clearer:
int firstEven = ints.Find(evenFinder);
You specify the escape character. Documentation here:
http://msdn.microsoft.com/en-us/library/ms179859.aspx
You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.
Here is a little example :
/* Create the comboBox */
QComboBox *_comboBox = new QComboBox;
/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");
/* Populate the comboBox */
_comboBox->addItems(stringsList);
/* Create the label */
QLabel *label = new QLabel;
/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
label->setText("Text2 not found !");
else
label->setText(QString("Text2's index is ")
.append(QString::number(_comboBox->findText("Text2"))));
/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);
Numeric precision refers to the maximum number of digits that are present in the number.
ie 1234567.89 has a precision of 9
Numeric scale refers to the maximum number of decimal places
ie 123456.789 has a scale of 3
Thus the maximum allowed value for decimal(5,2) is 999.99
I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info
I normally use the fontawesome font(http://fontawesome.io/icon/check/), you can use it in html files:
<i class="fa fa-check"></i>
or in css:
content: "\f00c";
font-family: FontAwesome;
I've seen this error too when the code stopped at the line:
Dim myNode As MSXML2.IXMLDOMNode
I found out that I had to add "Microsoft XML, v6.0" via Tools > Preferences.
Then it worked for me.
I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:
protected boolean displaySensitiveInformation() {
return false;
}
You will often see something like the above method that overrides a method in the base class. This is an important implementation detail of this class -- we don't want sensitive information to be displayed.
Suppose this method is changed in the parent class to
protected boolean displaySensitiveInformation(Context context) {
return true;
}
This change will not cause any compile time errors or warnings - but it completely changes the intended behavior of the subclass.
To answer your question: you should use the @Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.
For the go up, you just need to use scrollTop
instead of scrollBottom
:
$("#upClick").on("click", function () {
scrolled = scrolled - 300;
$(".cover").stop().animate({
scrollTop: scrolled
});
});
Also, use the .stop() method to stop the currently-running animation on the cover
div. When .stop()
is called on an element, the currently-running animation (if any) is immediately stopped.
The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing
2<SPACE>
As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))
public class Locomotive {
Locomotive() { main("hi");}
public static void main(String[] args) {
System.out.print("2 ");
}
public static void main(String args) {
System.out.print("3 " + args);
}
}
I found the problem, here's the script of the slow and fast versions of the stored procedure:
dbo.ViewOpener__RenamedForCruachan__Slow.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
dbo.ViewOpener__RenamedForCruachan__Fast.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:
Slow: SET ANSI_NULLS OFF
Fast: SET ANSI_NULLS ON
This answer also could be made to make sense, since the view does have a join clause that says:
(table.column IS NOT NULL)
So there is some NULL
s involved.
The explanation is further proved by returning to Query Analizer, and running
SET ANSI_NULLS OFF
.
DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'
.
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
And the query is slow.
So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off
, rather than ANSI_NULLS on
, which is QA's default.
Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS
option in the stored procedure dialog:
Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....
I had a similar issue when I checked out a web project from a github repo on my eclipse. src/main/java was directly inside the project root in Package Explorer. My expectation was that src/main/java be visible inside a source folder "Java Resources". There were few things which I did to achieve this.
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,
$this->db->where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate
$this->db->or_where_in()
ex : $this->db->where_in('id', array('1','2','3'));
You can and should never assume that $_SERVER['HTTP_REFERER']
will be present.
If you control the previous page, you can pass the URL as a parameter "site.com/page2.php?prevUrl=".urlencode("site.com/page1.php")
.
If you don't control the page, then there is nothing you can do.
Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.
inside templateHTML.html:
<form action="#" method="get">
<input type="text" value="8" name="mytextbox" size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
inside view.py:
import mypythoncode
def request_page(request):
if(request.GET.get('mybtn')):
mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')
You don't need a generate bock if you want all the bits of temp
assigned in the same always block.
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
for (integer c=0; c<ROWBITS; c=c+1) begin: test
temp[c] <= 1'b0;
end
end
Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
temp <= '0; // fill with 0
end
end
Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.
If one wants to split string while keeping separators by regex without capturing group:
def finditer_with_separators(regex, s):
matches = []
prev_end = 0
for match in regex.finditer(s):
match_start = match.start()
if (prev_end != 0 or match_start > 0) and match_start != prev_end:
matches.append(s[prev_end:match.start()])
matches.append(match.group())
prev_end = match.end()
if prev_end < len(s):
matches.append(s[prev_end:])
return matches
regex = re.compile(r"[\(\)]")
matches = finditer_with_separators(regex, s)
If one assumes that regex is wrapped up into capturing group:
def split_with_separators(regex, s):
matches = list(filter(None, regex.split(s)))
return matches
regex = re.compile(r"([\(\)])")
matches = split_with_separators(regex, s)
Both ways also will remove empty groups which are useless and annoying in most of the cases.
It is also possible to round negative integers
// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply: c * a
// 2.) if c is negative: (c>0? subtract half of the dividend
// (b>>1) is bit shift right = (b/2)
// if c is positive: else add half of the dividend
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)
Extended from a tip somewhere else in here. Sorry, missed from where.
/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>
int main () {
//rounding negative int
// doing something like d = c * 3/4
int a=3;
int b=4;
int c=-5;
int d;
int s=c;
int e=c+10;
for(int f=s; f<=e; f++) {
printf("%d\t",f);
double cd=f, ad=a, bd=b , dd;
// d = c * 3/4 with double
dd = cd * ad / bd;
printf("%.2f\t",dd);
printf("%.1f\t",dd);
printf("%.0f\t",dd);
// try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
// doing div before mul on purpose
dd =(double)c * ((double)a / (double)b);
printf("%.2f\t",dd);
c=f;
// d = c * 3/4 with integer rounding
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
printf("%d\t",d);
puts("");
}
return 0;
}
/* test output
in 2f 1f 0f cast int
-5 -3.75 -3.8 -4 -3.75 -4
-4 -3.00 -3.0 -3 -3.75 -3
-3 -2.25 -2.2 -2 -3.00 -2
-2 -1.50 -1.5 -2 -2.25 -2
-1 -0.75 -0.8 -1 -1.50 -1
0 0.00 0.0 0 -0.75 0
1 0.75 0.8 1 0.00 1
2 1.50 1.5 2 0.75 2
3 2.25 2.2 2 1.50 2
4 3.00 3.0 3 2.25 3
5 3.75 3.8 4 3.00
// by the way evolution:
// Is there any decent small integer library out there for that by now?
Do you need the second batch file to run asynchronously? Typically one batch file runs another synchronously with the call
command, and the second one would share the first one's window.
You can use start /b
second.bat to launch a second batch file asynchronously from your first that shares your first one's window. If both batch files write to the console simultaneously, the output will be overlapped and probably indecipherable. Also, you'll want to put an exit
command at the end of your second batch file, or you'll be within a second cmd
shell once everything is done.
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
I think I have come up with a quite shorter solution.. Hope it helps someone.
cbind.na<-function(df1, df2){
#Collect all unique rownames
total.rownames<-union(x = rownames(x = df1),y = rownames(x=df2))
#Create a new dataframe with rownames
df<-data.frame(row.names = total.rownames)
#Get absent rownames for both of the dataframe
absent.names.1<-setdiff(x = rownames(df1),y = rownames(df))
absent.names.2<-setdiff(x = rownames(df2),y = rownames(df))
#Fill absents with NAs
df1.fixed<-data.frame(row.names = absent.names.1,matrix(data = NA,nrow = length(absent.names.1),ncol=ncol(df1)))
colnames(df1.fixed)<-colnames(df1)
df1<-rbind(df1,df1.fixed)
df2.fixed<-data.frame(row.names = absent.names.2,matrix(data = NA,nrow = length(absent.names.2),ncol=ncol(df2)))
colnames(df2.fixed)<-colnames(df2)
df2<-rbind(df2,df2.fixed)
#Finally cbind into new dataframe
df<-cbind(df,df1[rownames(df),],df2[rownames(df),])
return(df)
}
If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
finds: [] _x000D_
},_x000D_
methods: {_x000D_
addFind: function () {_x000D_
this.finds.push({ value: 'def' });_x000D_
},_x000D_
deleteFind: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.finds.splice(index, 1);_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Finds</h1>_x000D_
<div v-for="(find, index) in finds">_x000D_
<input v-model="find.value">_x000D_
<button @click="deleteFind(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addFind">_x000D_
New Find_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
Stop the service that is using that port.
sudo service NAMEOFSERVICE stop
I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.
First, define this function to use:
const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T
before T extends object
you break the no-use-before-define
rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>
).
Anyways, with those modifications you can just use it like this:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
getKeyValue(user, "name")
Which, again, I find to be a bit more readable.
Yes - their performance characteristics differ significantly. It would probably be better to call them SortedList
and SortedTree
as that reflects the implementation more closely.
Look at the MSDN docs for each of them (SortedList
, SortedDictionary
) for details of the performance for different operations in different situtations. Here's a nice summary (from the SortedDictionary
docs):
The
SortedDictionary<TKey, TValue>
generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this, it is similar to theSortedList<TKey, TValue>
generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:
SortedList<TKey, TValue>
uses less memory thanSortedDictionary<TKey, TValue>
.
SortedDictionary<TKey, TValue>
has faster insertion and removal operations for unsorted data, O(log n) as opposed to O(n) forSortedList<TKey, TValue>
.If the list is populated all at once from sorted data,
SortedList<TKey, TValue>
is faster thanSortedDictionary<TKey, TValue>
.
(SortedList
actually maintains a sorted array, rather than using a tree. It still uses binary search to find elements.)
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
To receive the new commits
git fetch
Reset
You can reset the commit for a local branch using git reset
.
To change the commit of a local branch:
git reset origin/master --hard
Be careful though, as the documentation puts it:
Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.
If you want to actually keep whatever changes you've got locally - do a --soft
reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).
Rebase
You can replay your local commits on top of any other commit/branch using git rebase
:
git rebase -i origin/master
This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.
If the commits you removed (with git push -f
) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.
Use the help git command --help
for more details and examples on any of the above (or other) commands.
Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z]
or [0-9-]
), OR escape it (e.g. [a-z\-0-9]
) in order to add "hyphen" to your class.
It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.
(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]
) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)
Great question!
#include"stdio.h"
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int i;
srand(time(&t));
for(i=1;i<=10;i++)
printf("%c\t",rand()%10);
getch();
}
Use the same function (cor
) on a data frame, e.g.:
> cor(VADeaths)
Rural Male Rural Female Urban Male Urban Female
Rural Male 1.0000000 0.9979869 0.9841907 0.9934646
Rural Female 0.9979869 1.0000000 0.9739053 0.9867310
Urban Male 0.9841907 0.9739053 1.0000000 0.9918262
Urban Female 0.9934646 0.9867310 0.9918262 1.0000000
Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:
> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
mpg cyl disp hp drat wt qsec vs am gear carb
mpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
cyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
disp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
hp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
drat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
wt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
qsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
vs 0.6640389 -0.8108118 -0.7104159 -0.7230967 0.44027846 -0.5549157 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
am 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953 -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
gear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870 -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
carb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059 -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
the method TextView.setTextSize(int unit , float size);
takes two parameters .
Try this :
text.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
UPDATE:
Now the setTextSize(float size)
will set the text size automatically in "scaled pixel
" units. no need to mention the COMPLEX_UNIT_SP manually.
Refer to the documentation.
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
There are three parts:
You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:
#!path/to/interpretter
To find the path to your python interpretter on your machine you can run the command:
which python
This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:
#!/usr/bin/python
You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:
chmod +x myscript.py
The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:
echo $PATH
This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:
which <commandname>
Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:
export PATH=/my/directory/with/pythonscript:$PATH
Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile
For Kotlin devs: To allow Hibernate to inherit from the @Entity types that you want to be lazy-loadable they have to be inheritable/open
, which they in Kotlin by default are not. To work around this issue we can make use of the all-open
compiler plugin and instruct it to also handle the JPA annotations by adding this to our build.gradle
:
allOpen {
annotation("javax.persistence.Entity")
annotation("javax.persistence.MappedSuperclass")
annotation("javax.persistence.Embeddable")
}
If you are using Kotlin and Spring like me, you are most probably also using the kotlin-jpa
/no-args
and kotlin-spring
/all-open
compiler plugins already. However, you will still need to add the above lines, as that combination of plugins neither makes such classes open
.
Read the great article of Léo Millon for further explanations.
In C#
Random random = new Random((int)DateTime.Now.Ticks);
OrderedDictionary od = new OrderedDictionary();
od.Add("abc", 1);
od.Add("def", 2);
od.Add("ghi", 3);
od.Add("jkl", 4);
int randomIndex = random.Next(od.Count);
Console.WriteLine(od[randomIndex]);
// Can access via index or key value:
Console.WriteLine(od[1]);
Console.WriteLine(od["def"]);
From Android P, defining the READ_PHONE_STATE permission in AndroidManifest only, will not work. We have to actually request for the permission. Below code works for me:
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
Log.d(TAG,Build.getSerial());
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
} else {
//not granted
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Add this permissions in AndroidManifest.xml
<uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission android:name = "android.permission.READ_PHONE_STATE" />
Hope this helps.
Thank You, MJ
It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.
see this link:
http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server
somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...
If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.
I had this error too , and finally this codes worked for me in dot net core 3.1
first install svcutil in command prompt : dotnet tool install --global dotnet-svcutil
Then close command prompt and open it again.
Then create the Reference.cs in command prompt :
dotnet-svcutil http://YourService.com/SayHello.svc
(It needs an enter key and UserName and Password)
Add a folder named Connected Services to project root.
Copy Reference.cs file to Connected Services folder.
Add these 4 lines to Reference.cs after lines where creating BasicHttpBinding and setting MaxBufferSize :
result.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
result.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
result.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
result.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
Use this service in your Controller :
public async Task<string> Get()
{
try
{
var client = new EstelamClient();
client.ClientCredentials.UserName.UserName = "YourUserName";
client.ClientCredentials.UserName.Password = "YourPassword";
var res = await client.EmployeeCheckAsync("service parameters");
return res.ToString();
}
catch (Exception ex)
{
return ex.Message + " ************ stack : " + ex.StackTrace;
}
}
Do not forget install these packages in .cshtml :
<PackageReference Include="System.ServiceModel.Duplex" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Http" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.NetTcp" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Security" Version="4.6.*" />
Bash supports all sorts of wildcards and expansions.
Your exact case would be handled by brace expansion, like so:
$ rm -rf abc.log.2012-03-{14,27,28}
The above would expand to a single command with all three arguments, and be equivalent to typing:
$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28
It's important to note that this expansion is done by the shell, before rm
is even loaded.
For ejected create-react-app projects
I just solved my case adding the following lines to my webpack.config.js
:
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
/* INSERT START */
require.resolve('@babel/preset-env'),
require.resolve('@babel/preset-react'),
{
'plugins': ['@babel/plugin-proposal-class-properties']
}
/* INSERTED END */
],
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.
Right-click on the table in SSMS, 'Design' it, and click on the id column. In the properties, set the identity to be seeded @ e.g. 1 and to have increment of 1 - save and you're done.
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
git reset --hard 1258f0d0aae
But be careful, if the descendant commits between 1258f0d0aae
and HEAD
are not referenced in other branches it'll be tedious (but not impossible) to recover them, so you'd better to create a "backup" branch at current HEAD
, checkout master
, and reset to the commit you want.
Also, be sure that you don't have uncommitted changes before a reset --hard
, they will be truly lost (no way to recover).
This is what I came up with:
$(document).ready(function(){_x000D_
_x000D_
$(".fc-event").each(function(){_x000D_
_x000D_
console.log(this.attributes['data'].nodeValue) _x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>_x000D_
<div id='external-events'>_x000D_
<h4>Booking</h4>_x000D_
<div class='fc-event' data='00:30:00' >30 Mins</div>_x000D_
<div class='fc-event' data='00:45:00' >45 Mins</div>_x000D_
</div>
_x000D_
Occasionally when a disk runs out of space, the message "transaction log for database XXXXXXXXXX is full due to 'LOG_BACKUP'" will be returned when an update SQL statement fails. Check your diskspace :)
That is quite simpler way to do it:
ls -l | tr -s " " " " | cut -d " " -f 5,9 | sort -n -r | head -n 1***
And you'll get this: 8445 examples.desktop
To answer your question:
In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.
You can define a variable with:
ARG myvalue=3
Spaces around the equal character are not allowed.
And use it later with:
RUN echo $myvalue > /test
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
Align to the center, using display: inline-block
and text-align: center
.
.outerdiv_x000D_
{_x000D_
height:100px;_x000D_
width:500px;_x000D_
background: red;_x000D_
margin: 0 auto;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
height:40px;_x000D_
width: 100px;_x000D_
margin: 2px;_x000D_
box-sizing: border-box;_x000D_
background: green;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
<div class="innerdiv"></div>_x000D_
<div class="innerdiv"></div>_x000D_
</div>
_x000D_
Align to the center using display: flex
and justify-content: center
.outerdiv_x000D_
{_x000D_
height:100px;_x000D_
width:500px;_x000D_
background: red;_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
height:40px;_x000D_
width: 100px;_x000D_
margin: 2px;_x000D_
box-sizing: border-box;_x000D_
background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
<div class="innerdiv"></div>_x000D_
<div class="innerdiv"></div>_x000D_
</div>
_x000D_
Align to the center vertically and horizontally using display: flex
, justify-content: center
and align-items:center
.
.outerdiv_x000D_
{_x000D_
height:100px;_x000D_
width:500px;_x000D_
background: red;_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
justify-content: center;_x000D_
align-items:center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
height:40px;_x000D_
width: 100px;_x000D_
margin: 2px;_x000D_
box-sizing: border-box;_x000D_
background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
<div class="innerdiv"></div>_x000D_
<div class="innerdiv"></div>_x000D_
</div>
_x000D_
You can also use following Node.js module to do it with ease:
https://www.npmjs.com/package/mssql-to-csv
var mssqlExport = require('mssql-to-csv')
// All config options supported by https://www.npmjs.com/package/mssql
var dbconfig = {
user: 'username',
password: 'pass',
server: 'servername',
database: 'dbname',
requestTimeout: 320000,
pool: {
max: 20,
min: 12,
idleTimeoutMillis: 30000
}
};
var options = {
ignoreList: ["sysdiagrams"], // tables to ignore
tables: [], // empty to export all the tables
outputDirectory: 'somedir',
log: true
};
mssqlExport(dbconfig, options).then(function(){
console.log("All done successfully!");
process.exit(0);
}).catch(function(err){
console.log(err.toString());
process.exit(-1);
});
private <A, B> Map<B, A> invertMap(Map<A, B> map) {
Map<B, A> reverseMap = new HashMap<>();
for (Map.Entry<A, B> entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
return reverseMap;
}
It's important to remember that put
replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.
Do not use list as variable name. You can take a look at the following code too:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
Or in-place editing:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
What I found out is that MS Access will reject --Not Like "BB*"-- if not enclosed in PARENTHESES, unlike --Like "BB*"-- which is ok without parentheses.
I tested these on MS Access 2010 and are all valid:
Like "BB"
(Like "BB")
(Not Like "BB")
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
Try this in cmd:
cd address_of_sumatrapdf.exe_file && sumatrapdf.exe
Where you should put the address of your .exe file instead of adress_of_sumatrapdf.exe_file.
@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).
If you need authentication with SSO (Single Sign On) with Microsoft Windows user account. You may give a try to https://github.com/jlguenego/node-expose-sspi.
It will give you a req.sso
object which contains all client user information (login, display name, sid, groups).
const express = require("express");
const { sso, sspi } = require("node-expose-sspi");
sso.config.debug = false;
const app = express();
app.use(sso.auth());
app.use((req, res, next) => {
res.json({
sso: req.sso
});
});
app.listen(3000, () => console.log("Server started on port 3000"));
Disclaimer: I am the author of node-expose-sspi.
For Bootstrap 4 simply remove the 'data-ride="carousel"' from the carousel div. This removes auto play at load time.
To enable the auto play again you would still have to use the "play" call in javascript.
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
I was having this same issue - I am using Selectize with Rails and wanted to Selectize an association field - I wanted the name of the associated record to show up in the dropdown, but I needed the value of each option to be the id of the record, since Rails uses the value
to set associations.
I solved this by setting a coffeescript var of @valueAttr
to the id
of each object and a var of @dataAttr
to the name
of the record. Then I went through each option and set:
opts.labelField = @dataAttr
opts.valueField = @valueAttr
It helps to see the full diff: https://github.com/18F/C2/pull/912/files
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
-moz-transform: scale(-1, 1);
-webkit-transform: scale(-1, 1);
-o-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
transform: scale(-1, 1);
The two parameters are X axis, and Y axis, -1 will be a mirror, but you can scale to any size you like to suit your needs. Upside down and backwards would be (-1, -1)
.
If you're interested in the best option available for cross browser support back in 2011, see my older answer.
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
When posting form data with an HTML form, be sure the input
tags have name
attributes, otherwise they won't be present in request.form
.
@app.route('/', methods=['GET', 'POST'])
def index():
print(request.form)
return """
<form method="post">
<input type="text">
<input type="text" id="txt2">
<input type="text" name="txt3" id="txt3">
<input type="submit">
</form>
"""
ImmutableMultiDict([('txt3', 'text 3')])
Only the txt3
input had a name
, so it's the only key present in request.form
.
I like ggplot
too.
Here's one example:
df1 = data.frame(
date_id = c('2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04'),
nation = c('China', 'USA', 'China', 'USA'),
value = c(4.0, 5.0, 6.0, 5.5))
ggplot(df1, aes(date_id, value, group=nation, colour=nation))+geom_line()+xlab(label='dates')+ylab(label='value')
You have to give width:100%
to parent to center
the text.
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
If you also need to centre align vertically, give height:100%
and align-itens: center
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
width:100%;
height: 100%;
}
You can also combine the p3p.xml and policy.xml files as such:
/home/ubuntu/sites/shared/w3c/p3p.xml
<META xmlns="http://www.w3.org/2002/01/P3Pv1">
<POLICY-REFERENCES>
<POLICY-REF about="#policy1">
<INCLUDE>/</INCLUDE>
<COOKIE-INCLUDE/>
</POLICY-REF>
</POLICY-REFERENCES>
<POLICIES>
<POLICY discuri="" name="policy1">
<ENTITY>
<DATA-GROUP>
<DATA ref="#business.name"></DATA>
<DATA ref="#business.contact-info.online.email"></DATA>
</DATA-GROUP>
</ENTITY>
<ACCESS>
<nonident/>
</ACCESS>
<!-- if the site has a dispute resolution procedure that it follows, a DISPUTES-GROUP should be included here -->
<STATEMENT>
<PURPOSE>
<current/>
<admin/>
<develop/>
</PURPOSE>
<RECIPIENT>
<ours/>
</RECIPIENT>
<RETENTION>
<indefinitely/>
</RETENTION>
<DATA-GROUP>
<DATA ref="#dynamic.clickstream"/>
<DATA ref="#dynamic.http"/>
</DATA-GROUP>
</STATEMENT>
</POLICY>
</POLICIES>
</META>
I found the easiest way to add a header is proxy through Apache and use mod_headers, as such:
<VirtualHost *:80>
ServerName mydomain.com
DocumentRoot /home/ubuntu/sites/shared/w3c/
ProxyRequests off
ProxyPass /w3c/ !
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
ProxyPreserveHost on
Header add p3p 'P3P:policyref="/w3c/p3p.xml", CP="NID DSP ALL COR"'
</VirtualHost>
So we proxy all requests except those to /w3c/p3p.xml to our application server.
You can test it all with the W3C validator
here's how I promote all worksheet names to global names. YMMV
For Each wsh In ActiveWorkbook.Worksheets
For Each n In wsh.Names
' Get unqualified range name
Dim s As String
s = Split(n.Name, "!")(UBound(Split(n.Name, "!")))
' Add to "Workbook" scope
n.RefersToRange.Name = s
' Remove from "Worksheet" scope
Call n.Delete
Next n
Next wsh
In some contexts using a ' character beforehand will work, but if you save to CSV and load again this is impossible.
'01/01/2010 14:30:00
I had the same problem, here is my solution:
<form method="post" class="form-inline form-horizontal" role="form">
<label class="control-label col-sm-5" for="jbe"><i class="icon-envelope"></i> Email me things like this: </label>
<div class="input-group col-sm-7">
<input class="form-control" type="email" name="email" placeholder="[email protected]"/>
<span class="input-group-btn">
<button class="btn btn-primary" type="submit">Submit</button>
</span>
</div>
</form>
here is the Demo
select substr(orderno,1,2) from shipment;
You may want to have a look at the documentation too.
Simply Try this
@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })
But if you want a default value or no option value then you must have to try this one, because String.Empty
will select that no value for you which will work as a -select-
as default option
@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, String.Empty, new { @class="dropdown" })
feel free to use this tool https://github.com/rooty0/ffmpeg_video_cutter I wrote awhile ago Pretty much that's cli front-end for ffmpeg... you just need to create a yaml what you want to cut out... something like this
cut_method: delete # we're going to delete following video fragments from a video
timeframe:
- from: start # waiting for people to join the conference
to: 4m
- from: 10m11s # awkward silence
to: 15m50s
- from: 30m5s # Off-Topic Discussion
to: end
and then just run a tool to get result
You have to use HorizontalContentAlignment="Center" and! Width="Auto".
Okay, I found spencerlyon2's answer working. However, in case anybody would find himself/herself not knowing what to do with that one line, I had to do it this way:
beingsaved = plt.figure()
# Some scatter plots
plt.scatter(X_1_x, X_1_y)
plt.scatter(X_2_x, X_2_y)
beingsaved.savefig('destination_path.eps', format='eps', dpi=1000)
No worries, Agreed with the above answers:
But for Private project, please follow the steps for Gitlab:
You will be asked to type your project name
This action can lead to data loss. To prevent accidental actions we ask you to confirm your intention. Please type 'sample_project' to proceed or close this modal to cancel.
Now your project is deleted successfully.
You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct()
you'll get an error).
Therefore you'd have to create an initialize()
function and call it in each method:
<?php
class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
You can try using Descriptor, to limit the size
class fixedSizeArray(object):
def __init__(self, arraySize=5):
self.arraySize = arraySize
self.array = [None] * self.arraySize
def __repr__(self):
return str(self.array)
def __get__(self, instance, owner):
return self.array
def append(self, index=None, value=None):
print "Append Operation cannot be performed on fixed size array"
return
def insert(self, index=None, value=None):
if not index and index - 1 not in xrange(self.arraySize):
print 'invalid Index or Array Size Exceeded'
return
try:
self.array[index] = value
except:
print 'This is Fixed Size Array: Please Use the available Indices'
arr = fixedSizeArray(5)
print arr
arr.append(100)
print arr
arr.insert(1, 200)
print arr
arr.insert(5, 300)
print arr
OUTPUT:
[None, None, None, None, None]
Append Operation cannot be performed on fixed size array
[None, None, None, None, None]
[None, 200, None, None, None]
This is Fixed Size Array: Please Use the available Indices
[None, 200, None, None, None]
The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.
Connection refused means that the port you are trying to connect to is not actually open.
So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.
A common mistake is not specifying the port number when binding or connecting in network byte order...
I faced the same issue, and I changed the workspace to new location, and it worked. I hope this helps :)
You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.
In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.
int result_num;
bool flag;
cout << "Number Divisors\n";
for (int number = 1; number <= 35; number++)
{
flag = false;
cout << setw(3) << number << setw(14);
for (int i = 1; i <= number; i++)
{
result_num = number % i;
if (result_num == 0 && flag == true)
{
cout << "," << i;
}
if (result_num == 0 && flag == false)
{
cout << i;
}
flag = true;
}
cout << endl;
}
cout << "Press enter to continue.....";
cin.ignore();
return 0;
}
I haven't tried using Lombok yet - it is/was next on my list, but it sounds as if Java 8 has caused significant problems for it, and remedial work was still in progress as of a week ago. My source for that is https://code.google.com/p/projectlombok/issues/detail?id=451 .
For what it's worth, the source code for Stream.Close
explains why there are two methods:
// Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup now.
In short, Close
is only there because it predates Dispose
, and it can't be deleted for compatibility reasons.
Use a regular expression validator instead. This will work on the client side using JavaScript, but also when JavaScript is disabled (as the length check will be performed on the server as well).
The following example checks that the entered value is between 0 and 100 characters long:
<asp:RegularExpressionValidator runat="server" ID="valInput"
ControlToValidate="txtInput"
ValidationExpression="^[\s\S]{0,100}$"
ErrorMessage="Please enter a maximum of 100 characters"
Display="Dynamic">*</asp:RegularExpressionValidator>
There are of course more complex regexs you can use to better suit your purposes.
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
For Windows & Mac Users, there is another pretty easy and friendly way to change the mapping port:
download kitematic
go to the settings page of the container, on the ports tab, you can directly modify the published port there.
start the container again
You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/
IE Driver is also available in the following site:
In a discussion, Simon clearly mentioned that:
While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.
Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for number_of_windows_to_be(2)
and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo().window(newly_opened)
as required. Here is a solution where you can open http://www.google.co.in
in the initial TAB and https://www.yahoo.com
in the adjacent TAB:
Code Block:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://www.google.co.in")
print("Initial Page Title is : %s" %driver.title)
windows_before = driver.current_window_handle
print("First Window Handle is : %s" %windows_before)
driver.execute_script("window.open('https://www.yahoo.com')")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != windows_before][0]
driver.switch_to_window(new_window)
print("Page Title after Tab Switching is : %s" %driver.title)
print("Second Window Handle is : %s" %new_window)
Console Output:
Initial Page Title is : Google
First Window Handle is : CDwindow-B2B3DE3A222B3DA5237840FA574AF780
Page Title after Tab Switching is : Yahoo
Second Window Handle is : CDwindow-D7DA7666A0008ED91991C623105A2EC4
Browser Snapshot:
You can find the java based discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium
Don't think so. I've always had to write them or use someone else's work to get that info. Has to be reflection as far as i'm aware.
EDIT:
Check this out. I was investigating some debugging on long object graphs and noticed this when i Add Watches, VS throws in this class: Mscorlib_CollectionDebugView<>
. It's an internal type for displaying collections nicely for viewing in the watch windows/code debug modes. Now coz it's internal you can reference it, but u can use Reflector to copy (from mscorlib) the code and have your own (the link above has a copy/paste example). Looks really useful.
run cmd
Enter wmic baseboard get product,version,serialnumber
Press the enter key. The result you see under serial number column is your motherboard serial number
For me the Target > Build Settings > Packaging > Product Name was set to the same thing as another value referenced in a .plist file which was custom to my app. Eventually due to our build process this creates duplicate files.
As highlighted by Tilendor in Jon Skeet's answer, streams have a CopyTo
method since .NET 4.
var fileStream = File.Create("C:\\Path\\To\\File");
myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
myOtherObject.InputStream.CopyTo(fileStream);
fileStream.Close();
Or with the using
syntax:
using (var fileStream = File.Create("C:\\Path\\To\\File"))
{
myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
myOtherObject.InputStream.CopyTo(fileStream);
}
Following should do the trick:
BigDecimal d = new BigDecimal(10);
int i = d.intValue();
To Method onBindViewHolder
Write This Code
holder.remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Cursor del=dbAdapter.ExecuteQ("delete from TblItem where Id="+values.get(position).getId());
values.remove(position);
notifyDataSetChanged();
}
});
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
For cross Python 2/3 compatibility, you can use input
via the six
library:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )
Use git stash save NAME
to save.
Then... you can use this script to choose which to apply (or pop):
#!/usr/bin/env ruby
#git-stash-pick by Dan Rosenstark
# can take a command, default is apply
command = ARGV[0]
command = "apply" if !command
ARGV.clear
stashes = []
stashNames = []
`git stash list`.split("\n").each_with_index { |line, index|
lineSplit = line.split(": ");
puts "#{index+1}. #{lineSplit[2]}"
stashes[index] = lineSplit[0]
stashNames[index] = lineSplit[2]
}
print "Choose Stash or ENTER to exit: "
input = gets.chomp
if input.to_i.to_s == input
realIndex = input.to_i - 1
puts "\n\nDoing #{command} to #{stashNames[realIndex]}\n\n"
puts `git stash #{command} #{stashes[realIndex]}`
end
I like being able to see the names of the stashes and choose. Also I use Zshell and frankly didn't know how to use some of the Bash aliases above ;)
Note: As Kevin says, you should use tags and cherry-picks instead.
When your second thread is non-Daemon, your application's primary main thread cannot quit because its exit criteria is being tied to the exit also of non-Daemon thread(s). Threads cannot be forcibly killed in python, therefore your app will have to really wait for the non-Daemon thread(s) to exit. If this behavior is not what you want, then set your second thread as daemon so that it won't hold back your application from exiting.
You're grouping with BillDate
, but the bill dates are different for each account so your rows are not being grouped. If you think about it, that doesn't even make sense - they are different bills, and have different dates. The same goes for the Bill
- you're attempting to sum bills for an account, why would you group by that?
If you leave BillDate
and Bill
off of the select and group by clauses you'll get the correct results.
SELECT AccountNumber, SUM(Bill)
FROM Table1
GROUP BY AccountNumber
Here on a openSuse 12.3 the solution was installing the 32-bit version of libaio in addition. Oracle seems to need this now, although on 12.1 it run without the 32-bit version.
Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.
For the OP's question it sounds like you require two specific files to exist. Just use a tally:
IF EXIST somefile.txt (
set /a file1_status=1
)
IF EXIST someotehrfile.txt (
set /a file2_status=1
)
set /a file_status_result=file1_status + file2_status
if %file_status_result% equ 2 (
goto somefileexists
)
goto exit
:somefileexists
IF EXIST someotherfile.txt SET var=...
:exit
My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.
I would add this to the LI's CSS
.list-item
{
float: left;
clear: left;
}
Factory Design Pattern
The factory design pattern is characterized by
You can observe few things when you question yourself as below
These are handled by Dependency injection.
Dependency injection
You can have different ways in which you can inject dependency. For simplicity lets go with Interface Injection
In DI ,container creates the needed instances, and "injects" them into the object.
Thus eliminates the static instantiation.
Example:
public class MyClass{
MyInterface find= null;
//Constructor- During the object instantiation
public MyClass(MyInterface myInterface ) {
find = myInterface ;
}
public void myMethod(){
find.doSomething();
}
}
What I did was compare the iframe scrollWidth until it changed size while i incrementally set the IFrame Height. And it worked fine for me. You can adjust the increment to whatever is desired.
<script type="text/javascript">
function AdjustIFrame(id) {
var frame = document.getElementById(id);
var maxW = frame.scrollWidth;
var minW = maxW;
var FrameH = 100; //IFrame starting height
frame.style.height = FrameH + "px"
while (minW == maxW) {
FrameH = FrameH + 100; //Increment
frame.style.height = FrameH + "px";
minW = frame.scrollWidth;
}
}
</script>
<iframe id="RefFrame" onload="AdjustIFrame('RefFrame');" class="RefFrame"
src="http://www.YourUrl.com"></iframe>
Most of the time unreachable commits are in the reflog. So, the first thing to try is to look at the reflog using the command git reflog
(which display the reflog for HEAD
).
Perhaps something easier if the commit was part of a specific branch still existing is to use the command git reflog name-of-my-branch
. It works also with a remote, for example if you forced push (additional advice: always prefer git push --force-with-lease
instead that better prevent mistakes and is more recoverable).
If your commits are not in your reflog (perhaps because deleted by a 3rd party tool that don't write in the reflog), I successfully recovered a branch by reseting my branch to the sha of the commit found using a command like that (it creates a file with all the dangling commits):
git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\ -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt
If you should use it more than one time (or want to save it somewhere), you could also create an alias with that command...
git config --global alias.rescue '!git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\ -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt'
and use it with git rescue
To investigate found commits, you could display each commit using some commands to look into them.
To display the commit metadata (author, creation date and commit message):
git cat-file -p 48540dfa438ad8e442b18e57a5a255c0ecad0560
To see also the diffs:
git log -p 48540dfa438ad8e442b18e57a5a255c0ecad0560
Once you found your commit, then create a branch on this commit with:
git branch commit_rescued 48540dfa438ad8e442b18e57a5a255c0ecad0560
For the ones that are under Windows and likes GUIs, you could easily recover commits (and also uncommited staged files) with GitExtensions by using the feature Repository
=> Git maintenance
=> Recover lost objects...
A similar command to easily recover staged files deleted: https://stackoverflow.com/a/58853981/717372
You want to set its 'Format' property to be time and add a spin button control to it:
yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;
In Java terms, Scala's Seq
would be Java's List
, and Scala's List
would be Java's LinkedList
.
Note that Seq
is a trait
, which is equivalent to Java's interface
, but with the equivalent of up-and-coming defender methods. Scala's List
is an abstract class that is extended by Nil
and ::
, which are the concrete implementations of List
.
So, where Java's List
is an interface
, Scala's List
is an implementation.
Beyond that, Scala's List
is immutable, which is not the case of LinkedList
. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).
Scala's List
is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector
is a better choice than List
, but habit is hard to break.
Seq
is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq
, collection.mutable.Seq
and collection.immutable.Seq
, and it is the latter one that is the "default" imported into scope.
There's also GenSeq
and ParSeq
. The latter methods run in parallel where possible, while the former is parent to both Seq
and ParSeq
, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.
The distance estimate provided by iOS is based on the ratio of the beacon signal strength (rssi) over the calibrated transmitter power (txPower). The txPower is the known measured signal strength in rssi at 1 meter away. Each beacon must be calibrated with this txPower value to allow accurate distance estimates.
While the distance estimates are useful, they are not perfect, and require that you control for other variables. Be sure you read up on the complexities and limitations before misusing this.
When we were building the Android iBeacon library, we had to come up with our own independent algorithm because the iOS CoreLocation source code is not available. We measured a bunch of rssi measurements at known distances, then did a best fit curve to match our data points. The algorithm we came up with is shown below as Java code.
Note that the term "accuracy" here is iOS speak for distance in meters. This formula isn't perfect, but it roughly approximates what iOS does.
protected static double calculateAccuracy(int txPower, double rssi) {
if (rssi == 0) {
return -1.0; // if we cannot determine accuracy, return -1.
}
double ratio = rssi*1.0/txPower;
if (ratio < 1.0) {
return Math.pow(ratio,10);
}
else {
double accuracy = (0.89976)*Math.pow(ratio,7.7095) + 0.111;
return accuracy;
}
}
Note: The values 0.89976, 7.7095 and 0.111 are the three constants calculated when solving for a best fit curve to our measured data points. YMMV
time = Time.now.to_s
time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")
for increment decrement month use << >> operators
examples
datetime_month_before = DateTime.parse(time) << 1
datetime_month_before = DateTime.now << 1
In my case I'm using C# OracleCommand
with OracleParameter
, and I set all the the parameters Size
property to max length of each column, then the error solved.
OracleParameter parm1 = new OracleParameter();
param1.OracleDbType = OracleDbType.Varchar2;
param1.Value = "test1";
param1.Size = 8;
OracleParameter parm2 = new OracleParameter();
param2.OracleDbType = OracleDbType.Varchar2;
param2.Value = "test1";
param2.Size = 12;
Oneliner:
do_X() if len(your_list) > your_index else do_something_else()
Full example:
In [10]: def do_X():
...: print(1)
...:
In [11]: def do_something_else():
...: print(2)
...:
In [12]: your_index = 2
In [13]: your_list = [1,2,3]
In [14]: do_X() if len(your_list) > your_index else do_something_else()
1
Just for info. Imho, try ... except IndexError
is better solution.
A slighest different version, skipping the cut step, taking advantage of the '--no-version' option:
gem list --no-version |xargs gem uninstall -ax
Since you are removing everything, I don't see the need for the 'I' option. Whenever the gem is removed, it's fine.
Hey i figured it out shortly after. For some reason I was just having a brain fart.
image.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.2)
For me, it came down to the proxy_pass
location setting. I needed to change over to using the HTTPS protocol, and have a valid SSL certificate set up on the node server side of things. That way when I introduce an external node server, I only have to change the IP and everything else remains the same config.
I hope this helps someone along the way... I was staring at the problem the whole time... sigh...
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream nodeserver {
server 127.0.0.1:8080;
}
server {
listen 443 default_server ssl http2;
listen [::]:443 default_server ssl http2 ipv6only=on;
server_name mysite.com;
ssl_certificate ssl/site.crt;
ssl_certificate_key ssl/site.key;
location /websocket { #replace /websocket with the path required by your application
proxy_pass https://nodeserver;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_intercept_errors on;
proxy_redirect off;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-NginX-Proxy true;
proxy_ssl_session_reuse off;
}
}
People seem to be over complicating this.. Just combine the two lists, then sort them:
>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
..or shorter (and without modifying l1
):
>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.
If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of datetime
objects)
Using the timeit.Timer().repeat()
(which repeats the functions 1000000 times), I loosely benchmarked it against ghoseb's solution, and sorted(l1+l2)
is substantially quicker:
merge_sorted_lists
took..
[9.7439379692077637, 9.8844599723815918, 9.552299976348877]
sorted(l1+l2)
took..
[2.860386848449707, 2.7589840888977051, 2.7682540416717529]
Try the element:
$(td).find('a').attr('disabled', 'disabled');
Disabling a link works for me in Chrome: http://jsfiddle.net/KeesCBakker/LGYpz/.
Firefox doesn't seem to play nice. This example works:
<a id="a1" href="http://www.google.com">Google 1</a>
<a id="a2" href="http://www.google.com">Google 2</a>
$('#a1').attr('disabled', 'disabled');
$(document).on('click', 'a', function(e) {
if ($(this).attr('disabled') == 'disabled') {
e.preventDefault();
}
});
Note: added a 'live' statement for future disabled / enabled links.
Note2: changed 'live' into 'on'.
Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...
Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String
and you to compare them...
1. you have 2 string values you get from an input and you'd like to compare them, they are as below:
var date1 = '01/12/2018';
var date2 = '12/12/2018';
2. They need to be Date Object
to be compared as date values, so simply convert them to date, using new Date()
, I just re-assign them for simplicity of explanation, but you can do it anyway you like:
date1 = new Date(date1);
date2 = new Date(date2);
3. Now simply compare them, using the >
<
>=
<=
date1 > date2; //false
date1 < date2; //true
date1 >= date2; //false
date1 <= date2; //true
The packaging library contains utilities for working with versions and other packaging-related functionality. This implements PEP 0440 -- Version Identification and is also able to parse versions that don't follow the PEP. It is used by pip, and other common Python tools to provide version parsing and comparison.
$ pip install packaging
from packaging.version import parse as parse_version
version = parse_version('1.0.3.dev')
This was split off from the original code in setuptools and pkg_resources to provide a more lightweight and faster package.
Before the packaging library existed, this functionality was (and can still be) found in pkg_resources, a package provided by setuptools. However, this is no longer preferred as setuptools is no longer guaranteed to be installed (other packaging tools exist), and pkg_resources ironically uses quite a lot of resources when imported. However, all the docs and discussion are still relevant.
From the parse_version()
docs:
Parsed a project's version string as defined by PEP 440. The returned value will be an object that represents the version. These objects may be compared to each other and sorted. The sorting algorithm is as defined by PEP 440 with the addition that any version which is not a valid PEP 440 version will be considered less than any valid PEP 440 version and the invalid versions will continue sorting using the original algorithm.
The "original algorithm" referenced was defined in older versions of the docs, before PEP 440 existed.
Semantically, the format is a rough cross between distutils'
StrictVersion
andLooseVersion
classes; if you give it versions that would work withStrictVersion
, then they will compare the same way. Otherwise, comparisons are more like a "smarter" form ofLooseVersion
. It is possible to create pathological version coding schemes that will fool this parser, but they should be very rare in practice.
The documentation provides some examples:
If you want to be certain that your chosen numbering scheme works the way you think it will, you can use the
pkg_resources.parse_version()
function to compare different version numbers:>>> from pkg_resources import parse_version >>> parse_version('1.9.a.dev') == parse_version('1.9a0dev') True >>> parse_version('2.1-rc2') < parse_version('2.1') True >>> parse_version('0.6a9dev-r41475') < parse_version('0.6a9') True
This is more than a bit late, but you can extend the regex expression to account for scientific notation too.
import re
# Format is [(<string>, <expected output>), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
('hello X42 I\'m a Y-32.35 string Z30',
['42', '-32.35', '30']),
('he33llo 42 I\'m a 32 string -30',
['33', '42', '32', '-30']),
('h3110 23 cat 444.4 rabbit 11 2 dog',
['3110', '23', '444.4', '11', '2']),
('hello 12 hi 89',
['12', '89']),
('4',
['4']),
('I like 74,600 commas not,500',
['74,600', '500']),
('I like bad math 1+2=.001',
['1', '+2', '.001'])]
for s, r in ss:
rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
if rr == r:
print('GOOD')
else:
print('WRONG', rr, 'should be', r)
Gives all good!
Additionally, you can look at the AWS Glue built-in regex
I have used a script but to make a join, maybe I can help you
string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());
I just want to WARN you about:
>>> (int) (290.15 * 100);
=> 29014
>>> (int) round((290.15 * 100), 0);
=> 29015
Bringing it all together, a table solution done purely with DIV and CSS, try it ;) The browser should support RGBA colors though....
<head>
<style>
.colored-div-table {
display: table;
table-layout: fixed;
}
.colored-div-table #col {
display: table-column;
}
.colored-div-table #col:nth-child(odd) {
}
.colored-div-table #col:nth-child(even) {
}
.colored-div-table #col:nth-child(1){
background-color: lightblue;
width: 50px !important;
}
.colored-div-table #col:nth-child(2){
background-color: lightyellow;
width: 200px !important;
}
.colored-div-table #col:nth-child(3){
background-color: lightcyan;
width: 50px !important;
}
.colored-div-table #row {
display: table-row;
}
.colored-div-table #row div {
display: table-cell;
}
.colored-div-table #row div:nth-child(1) {
}
.colored-div-table #row div:nth-child(2) {
}
.colored-div-table #row div:nth-child(3) {
}
.colored-div-table #row:nth-child(odd) {
background-color: rgba(0,0,0,0.1)
}
.colored-div-table #row:nth-child(even) {
}
</style>
</head>
<body>
<div id="divtable" class="colored-div-table">
<div id="col"></div>
<div id="col"></div>
<div id="col"></div>
<div id="row">
<div>First Line</div><div>FL C2</div><div>FL C3></div>
</div>
<div id="row">
<div>Second Line</div><div>SL C2</div><div>SL C3></div>
</div>
<div id="row">
<div>Third Line</div><div>TL C2</div><div>TL C3></div>
</div>
<div id="row">
<div>Forth Line</div><div>FL C2</div><div>FL C3></div>
</div>
<div id="row">
<div>Fifth Line</div><div>FL C2</div><div>FL C3></div>
</div>
<div id="row">
<div>Sixth Line</div><div>SL C2</div><div>SL C3></div>
</div>
<div id="row">
<div>Seventh Line</div><div>SL C2</div><div>SL C3></div>
</div>
<div id="row">
<div>Eight Line</div><div>EL C2</div><div>EL C3></div>
</div>
<div id="row">
<div>Nineth Line</div><div>NL C2</div><div>NL C3></div>
</div>
<div id="row">
<div>Tenth Line</div><div>TL C2</div><div>TL C3></div>
</div>
</div>
</body>
mtcars[do.call(order, mtcars[cols]), ]
I like having a list of sorted indices. That way, I can sort any list in the same order as the source list. Once you have a list of sorted indices, a simple list comprehension will do the trick:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
sorted_y_idx_list = sorted(range(len(Y)),key=lambda x:Y[x])
Xs = [X[i] for i in sorted_y_idx_list ]
print( "Xs:", Xs )
# prints: Xs: ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Note that the sorted index list can also be gotten using numpy.argsort()
.
docker ps -a
This command saves modified container state into a new image user/test_image
docker commit $CONTAINER_ID user/test_image
docker run -ti --entrypoint=sh user/test_image
Entrypoint argument description: https://docs.docker.com/engine/reference/run/#/entrypoint-default-command-to-execute-at-runtime
Steps above just start a stopped container with the same filesystem state. That is great for a quick investigation. But environment variables, network configuration, attached volumes and other staff is not inherited, you should specify all these arguments explicitly.
Steps to start a stopped container have been borrowed from here: (last comment) https://github.com/docker/docker/issues/18078
Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:
try{
Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
p.waitFor();
}catch( IOException ex ){
//Validate the case the file can't be accesed (not enought permissions)
}catch( InterruptedException ex ){
//Validate the case the process is being stopped by some external situation
}
This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
Do you mean you want Class C to be the base class for A & B in that case.
public abstract class C
{
public abstract void Method1();
public abstract void Method2();
}
public class A : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
public class B : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
If you're just after console logging here's what I'd do:
export default class App extends Component {
componentDidMount() {
console.log('I was triggered during componentDidMount')
}
render() {
console.log('I was triggered during render')
return (
<div> I am the App component </div>
)
}
}
Shouldn't be any need for those packages just to do console logging.
You need to install mysql server for your machine first. Once done, you will be able to add local db details to it.
For e.g. IP: 127.0.0.1
port: 3306
user: root
pass: pass of root which you have set
Here is the link on step by step guide for linux.
https://support.rackspace.com/how-to/install-mysql-server-on-the-ubuntu-operating-system/
Using the Access-Control-Allow-Origin header to the request won't help you in that case while this header can only be used on the response...
To make it work you should probably add this header to your response.You can also try to add the header crossorigin:true
to your request.
Just throwing this out there...Can't you just do:
Collections.sort(myarrayList);
It's been awhile though...
you are confusing the concept of appending and prepending. the following code is prepending:
sys.path.insert(1,'/thePathToYourFolder/')
it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. sys.path.append()
puts things at the very end of the search sequence.
it is advisable that you use something like virtualenv
instead of manually coding your package directories into the PYTHONPATH
everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:
if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/
To get the data of a specific field,
$form->get('fieldName')->getData();
Or for all the form data
$form->getData();
Link to docs: https://symfony.com/doc/2.7/forms.html
Not in the RFC, no, but there are practical limits.
The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).
Note: Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.
This is my way to achieve that.
First of all add Root_fragment
inside viewPager
tab in which you want to implement button click fragment
event. Example;
@Override
public Fragment getItem(int position) {
if(position==0)
return RootTabFragment.newInstance();
else
return SecondPagerFragment.newInstance();
}
First of all, RootTabFragment
should be include FragmentLayout
for fragment change.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Then, inside RootTabFragment
onCreateView
, implement fragmentChange
for your FirstPagerFragment
getChildFragmentManager().beginTransaction().replace(R.id.root_frame, FirstPagerFragment.newInstance()).commit();
After that, implement onClick
event for your button inside FirstPagerFragment
and make fragment change like that again.
getChildFragmentManager().beginTransaction().replace(R.id.root_frame, NextFragment.newInstance()).commit();
Hope this will help you guy.
To resolve this error:
ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name
Just run this PL/SQL
command for extended tablespace size automatically on-demand:
alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
I get this error in import big dump file, just run this command without stopping import routine or restarting the database.
Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.
More info: alter_autoextend_on
Using the process's lock is much stronger and takes care of the ungraceful exits also. lock_file is kept open as long as the process is running. It will be closed (by shell) once the process exists (even if it gets killed). I found this to be very efficient:
lock_file=/tmp/`basename $0`.lock
if fuser $lock_file > /dev/null 2>&1; then
echo "WARNING: Other instance of $(basename $0) running."
exit 1
fi
exec 3> $lock_file
This is what is actually happening:
global_list = []
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to global_list
useTheList(global_list)
main()
This is what you want:
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(returned_list)
main()
You can even skip the temporary returned_list
and pass the returned value directly to useTheList
:
def main():
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(defineAList())
Another option is to use the built-in Command Palette, which will walk you right through cloning a Git repository to a new directory.
From Using Version Control in VS Code:
You can clone a Git repository with the Git: Clone command in the Command Palette (Windows/Linux: Ctrl + Shift + P, Mac: Command + Shift + P). You will be asked for the URL of the remote repository and the parent directory under which to put the local repository.
At the bottom of Visual Studio Code you'll get status updates to the cloning. Once that's complete an information message will display near the top, allowing you to open the folder that was created.
Note that Visual Studio Code uses your machine's Git installation, and requires 2.0.0 or higher.
Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH
environment variable (or other language equivalent, like PYTHONPATH
, LD_LIBRARY_PATH
) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like
var logger = new Logger() //sane, simple code
And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.
No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.
P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.
You can also give weight separately like this ,
LayoutParams lp1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
lp1.weight=1;
Security is already a tough topic, but I'm disappointed to see the most popular solution is to delete the security signatures. JCE requires these signatures. Maven shade explodes the BouncyCastle jar file which puts the signatures into META-INF, but the BouncyCastle signatures aren't valid for a new, uber-jar (only for the BC jar), and that's what causes the Invalid signature error in this thread.
Yes, excluding or deleting the signatures as suggested by @ruhsuzbaykus does indeed make the original error go away, but it can also lead to new, cryptic errors:
java.security.NoSuchAlgorithmException: PBEWithSHA256And256BitAES-CBC-BC SecretKeyFactory not available
By explicitly specifying where to find the algorithm like this:
SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC","BC");
I was able to get a different error:
java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
JCE can't authenticate the provider because we've deleted the cryptographic signatures by following the suggestion elsewhere in this same thread.
The solution I found was the executable packer plugin that uses a jar-in-jar approach to preserve the BouncyCastle signature in a single, executable jar.
Another way to do this (the correct way?) is to use Maven Jar signer. This allows you to keep using Maven shade without getting security errors. HOWEVER, you must have a code signing certificate (Oracle suggests searching for "Java Code Signing Certificate"). The POM config looks like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>org.bouncycastle:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>your.class.here</mainClass>
</transformer>
</transformers>
<shadedArtifactAttached>true</shadedArtifactAttached>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jarsigner-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>sign</id>
<goals>
<goal>sign</goal>
</goals>
</execution>
<execution>
<id>verify</id>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<keystore>/path/to/myKeystore</keystore>
<alias>myfirstkey</alias>
<storepass>111111</storepass>
<keypass>111111</keypass>
</configuration>
</plugin>
No, there's no way to get JCE to recognize a self-signed cert, so if you need to preserve the BouncyCastle certs, you have to either use the jar-in-jar plugin or get a JCE cert.
How about get_the_category?
You can then do
$category = get_the_category();
$firstCategory = $category[0]->cat_name;
The assembly was introduced with .NET 3.5 and is in the GAC.
Simply add a .NET reference to your project.
Project -> Right Click References
-> Select .NET
tab -> System.Web.Extensions
If it is not there, you need to install .NET 3.5 or 4.0.
Try the --force
option. svn help checkout
gives the details.
string str = "2C F4 32 3C B9 DE";
str.erase(remove(str.begin(),str.end(),' '),str.end());
cout << str << endl;
output: 2CF4323CB9DE
White space affects inline elements.
This should not come as a surprise. We see it every day with span, strong and other inline elements. Set the font size to zero to remove the extra margin.
.container {
font-size: 0px;
letter-spacing: 0px;
word-spacing: 0px;
}
.container > div {
display: inline-block;
margin: 0px;
padding: 0px;
font-size: 15px;
letter-spacing: 1em;
word-spacing: 2em;
}
The example would then look like this.
<div class="container">
<div>First</div>
<div>Second</div>
</div>
A jsfiddle version of this. http://jsfiddle.net/QtDGJ/1/
If you are using Node.js Express and Typescript here is a working example, this works with javascript also, just change the let to var and the import to includes etc...
first import the following make sure you install formidable by running the following command:
npm install formidable
than import the following:
import * as formidable from 'formidable';
import * as fs from 'fs';
then your function like bellow:
uploadFile(req, res) {
let form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
let oldpath = files.file.path;
let newpath = 'C:/test/' + files.file.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
}
I feel it is worth adding that a static variable is not the same as a constant variable.
using a constant variable in a class
struct Foo{
const int a;
Foo(int b) : a(b){}
}
and we would declare it like like so
fooA = new Foo(5);
fooB = new Foo(10);
// fooA.a = 5;
// fooB.a = 10;
For a static variable
struct Bar{
static int a;
Foo(int b){
a = b;
}
}
Bar::a = 0; // set value for a
which is used like so
barA = new Bar(5);
barB = new Bar(10);
// barA.a = 10;
// barB.a = 10;
// Bar::a = 10;
You see what happens here. The constant variable, which is instanced along with each instance of Foo, as Foo is instanced has a separate value for each instance of Foo, and it can't be changed by Foo at all.
Where as with Bar, their is only one value for Bar::a no matter how many instances of Bar are made. They all share this value, you can also access it with their being any instances of Bar. The static variable also abides rules for public/private, so you could make it that only instances of Bar can read the value of Bar::a;
The SERVER_PORT environment variable will be picked up and used by Laravel. Either do:
export SERVER_PORT="8080"
php artisan serve
Or set SERVER_PORT=8080 in your .env file.
For port 8080:
php artisan serve --port=8080
And if you want to run it on port 80, you probably need to sudo:
sudo php artisan serve --port=80
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
I found this here:
On windows (win xp), the parent process will not finish until the longtask.py
has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.
The solution is to pass DETACHED_PROCESS
Process Creation Flag to the underlying CreateProcess
function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:
DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen([sys.executable, "longtask.py"],
creationflags=DETACHED_PROCESS).pid
I find the Script package useful for this. You can download it here.
Once installed you can run scripts in many languages directly from Atom using cmd-i
on Mac or shift-ctrl-b
on Windows or Linux.
Change
var svg = document.documentElement;
to
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
so that you create a SVG
element.
For the link to be an hyperlink, simply add a href
attribute :
h.setAttributeNS(null, 'href', 'http://www.google.com');
$(".hit").click(function(){
var values = [];
var table = $(this).closest("table");
table.find("tr").each(function() {
values.push($(this).find("td:first").html());
});
alert(values);
});
You should avoid $(".hit")
it's really inefficient. Try using event delegation instead.
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
According to the above answers setdefault() method worked for me.
old_attr_name = mydict.setdefault(key, attr_name)
if attr_name != old_attr_name:
raise RuntimeError(f"Key '{key}' duplication: "
f"'{old_attr_name}' and '{attr_name}'.")
Though this solution is not generic. Just suited me in this certain case. The exact solution would be checking for the key
first (as was already advised), but with setdefault()
we avoid one extra lookup on the dictionary, that is, though small, but still a performance gain.
Expired certificate was the cause of our "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated".
keytool -list -v -keystore filetruststore.ts
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 1 entry
Alias name: somealias
Creation date: Jul 26, 2012
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Unknown, OU=SomeOU, O="Some Company, Inc.", L=SomeCity, ST=GA, C=US
Issuer: CN=Unknown, OU=SomeOU, O=Some Company, Inc.", L=SomeCity, ST=GA, C=US
Serial number: 5011a47b
Valid from: Thu Jul 26 16:11:39 EDT 2012 until: Wed Oct 24 16:11:39 EDT 2012
I am adding for completion a simple function, using only numpy operators:
def probs_to_onehot(output_probabilities):
argmax_indices_array = np.argmax(output_probabilities, axis=1)
onehot_output_array = np.eye(np.unique(argmax_indices_array).shape[0])[argmax_indices_array.reshape(-1)]
return onehot_output_array
It takes as input a probability matrix: e.g.:
[[0.03038822 0.65810204 0.16549407 0.3797123 ] ... [0.02771272 0.2760752 0.3280924 0.33458805]]
And it will return
[[0 1 0 0] ... [0 0 0 1]]