this worked for me on Ubuntu 20.04 with mysql 8, the weird hashing thing is because the native PASSWORD() function was removed in mysql 8 (or earlier?)
UPDATE mysql.user SET
plugin = 'mysql_native_password',
Host = '%',
authentication_string = CONCAT('*', UPPER(SHA1(UNHEX(SHA1('insert password here')))))
WHERE User = 'root';
FLUSH PRIVILEGES;
Option Explicit
Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook
TitleId = 4
Resultid = 0
Dim FileName1, FileName2 As String
Dim Difference As Long
'TestPassCount = 0
'TestFailCount = 0
'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count
If (TestDataRowCount <= 2) Then
MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
For RecordId = 3 To TestDataRowCount
RefreshResultSheet
'Source File row count
SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
Set sourcewb = Workbooks.Open(SrceFile)
With sourcewb.Worksheets(1)
SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
sourcewb.Close
End With
'Target File row count
TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
Set targetwb = Workbooks.Open(TrgtFile)
With targetwb.Worksheets(1)
TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
targetwb.Close
End With
' Set Row Count Result Test data value
TitleId = TitleId + 3
Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value
'Compare Source and Target Row count
Resultid = TitleId + 1
Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
If (SourceRowCount = TargetRowCount) Then
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestPassCount = TestPassCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestFailCount = TestFailCount + 1
End If
'For comparison of two files
FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
FileName2 = Worksheets("TestData").Range("E" & RecordId).Value
Set myWorkbook1 = Workbooks.Open(FileName1)
Set myWorkbook2 = Workbooks.Open(FileName2)
Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
myWorkbook1.Close
myWorkbook2.Close
'MsgBox Difference
'Set Result of data validation in result sheet
Resultid = Resultid + 1
Worksheets("Result").Activate
Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"
If Difference > 0 Then
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestFailCount = TestFailCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestPassCount = TestPassCount + 1
End If
Next RecordId
End If
UpdateTestExecData TestPassCount, TestFailCount
End Sub
Sub RefreshResultSheet()
Worksheets("Result").Activate
Worksheets("Result").Range("B1:B4").Select
Selection.ClearContents
Worksheets("Result").Range("D1:D4").Select
Selection.ClearContents
Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub
Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
Worksheets("Result").Range("D2").Value = TestPassCount
Worksheets("Result").Range("D3").Value = TestFailCount
Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub
You can try:
<label id ="label_id"></label>
$("#label_id").html('value');
In your Html page please add
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test the multiselect with ajax</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Bootstrap multiselect -->
<link rel="stylesheet" href="http://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<br>
<form method="post" id="myForm">
<!-- Build your select: -->
<select name="categories[]" id="example-getting-started" multiple="multiple" class="col-md-12">
<option value="A">Cheese</option>
<option value="B">Tomatoes</option>
<option value="C">Mozzarella</option>
<option value="D">Mushrooms</option>
<option value="E">Pepperoni</option>
<option value="F">Onions</option>
<option value="G">10</option>
<option value="H">11</option>
<option value="I">12</option>
</select>
<br><br>
<button type="button" class="btnSubmit"> Send </button>
</form>
<br><br>
<div id="result">result</div>
</div><!--container-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Bootstrap multiselect -->
<script src="http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<!-- Bootstrap multiselect -->
<script src="ajax.js"></script>
<!-- Initialize the plugin: -->
<script type="text/javascript">
$(document).ready(function() {
$('#example-getting-started').multiselect();
});
</script>
</body>
</html>
In your ajax.js page please add
$(document).ready(function () {
$(".btnSubmit").on('click',(function(event) {
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "action.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#result").html(data);
// To clear the selected options
var select = $("#example-getting-started");
select.children().remove();
if (data.d) {
$(data.d).each(function(key,value) {
$("#example-getting-started").append($("<option></option>").val(value.State_id).html(value.State_name));
});
}
$('#example-getting-started').multiselect({includeSelectAllOption: true});
$("#example-getting-started").multiselect('refresh');
},
error: function()
{
console.log("failed to send the data");
}
});
}));
});
In your action.php page add
echo "<b>You selected :</b>";
for($i=0;$i<=count($_POST['categories']);$i++){
echo $_POST['categories'][$i]."<br>";
}
I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):
gulp.task('develop', ['clean'], function () {
gulp.start('coffee');
});
Slight variation on above:
Code here:
void EliminateTrailingFloatZeros(char *iValue)
{
char *p = 0;
for(p=iValue; *p; ++p) {
if('.' == *p) {
while(*++p);
while('0'==*--p) *p = '\0';
if(*p == '.') *p = '\0';
break;
}
}
}
It still has potential for overflow, so be careful ;P
The hex editor plugin mentioned by ellak still works, but it seems that you need the TextFX Characters plugin as well.
I initially installed only the hex plugin and Notepad++ would no longer pop up; instead it started eating memory (killed it at 1.2 GB). I removed it again and for other reasons installed the TextFX plugin (based on Find multiple lines in Notepad++)
Out of curiosity I installed the hex plugin again and now it works.
Note that this is on a fresh install of Windows 7 64 bit.
To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 tr
from rule one and add it to rule two.
table.rule1 tr td {
background-color: #ff0000;
}
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.
To add to Lennart Regebro's answer There is even the third way that can be used:
encoded3 = str.encode(original, 'utf-8')
print(encoded3)
Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.
A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.
Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.
In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".
The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.
Define the following function (not mine, not sure where I found it long ago):
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then:
String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
InputStream response = conn.getInputStream();
jsonReply = convertStreamToString(response);
// Do JSON handling here....
}
@Petr Mensik & kensen john
Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:
<%
String callback = request.getParameter("callback");
response.setCharacterEncoding("UTF-8");
if (callback != null) {
// Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
response.setContentType("text/javascript");
} else {
// Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
response.setContentType("application/json");
}
[...]
String output = "";
if (callback != null) {
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
When callback is supplied, returns:
callback({...JSON stuff...});
with content-type "text/javascript"
When callback is NOT supplied, returns:
{...JSON stuff...}
with content-type "application/json"
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
This is done using the REPLACE function
To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:
SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn] FROM [SomeTable]
To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"
UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')
For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.
For that need to add the 2021 partition into that table
ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS
I'd recommend getting the source with urllib and, if you're going to parse, use something like Beautiful Soup.
import urllib
url = urllib.urlopen("http://example.com") # Open the URL.
content = url.readlines() # Read the source and save it to a variable.
I like this tool, called simply DbSchema. It's written in Java so it runs on OS X, Windows, or Linux. It's a little clunky, especially when it comes to printing, but from my experience they're all like that. This one is the best of the several I've tried. It makes nice, clear diagrams. Free trial. Costs about $120 depending on how many licenses you buy.
Swift 5 The easiest way to add permissions without having to do it programatically, is to open your info.plist file and select the + next to Information Property list. Scroll through the drop down list to the Privacy options and select Privacy Camera Usage Description for accessing camera, or Privacy Photo Library Usage Description for accessing the Photo Library. Fill in the String value on the right after you've made your selection, to include the text you would like displayed to your user when the alert pop up asks for permissions.
Read these tutorials Asp.net Update Panel and Introduction to the UpdatePanel Control
Simple and understandable
Yes Fiddler is an option for me:
CustomRules.js
).OnBeforeResponse
Add the following lines:
oSession.oResponse.headers.Remove("X-Frame-Options");
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
Below code will only allow numbers "0123456789”, even if you accidentally type other than "0123456789”, edit text will not accept.
EditText number1 = (EditText) layout.findViewById(R.id.edittext);
number1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_CLASS_PHONE);
number1.setKeyListener(DigitsKeyListener.getInstance("0123456789”));
The most compact version:
<input type="submit" onclick="return confirm('Are you sure?')" />
The key thing to note is the return
-
Because there are many ways to skin a cat, here is another alternate method:
HTML:
<input type="submit" onclick="clicked(event)" />
Javascript:
<script>
function clicked(e)
{
if(!confirm('Are you sure?')) {
e.preventDefault();
}
}
</script>
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
Also works for items with spaces and ignores directories
for f in *; do [[ -f "$f" ]] && mv "$f" "unix_$f"; done
The command above worked for me
C:\Users\marcelo\Downloads\vs_community.exe --lang en-en --layout C:\VisualStudio2017 --all
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
Use this code very simple solution
@Override
public void onBackPressed() {
super.onBackPressed(); // this line close the app on backpress
}
Quick Open File is a plugin that, coming from an Eclipse background, I can't live without
No more digging through the solution explorer trying to find files
I would recommend everyone look into CSS grids. It has been supported by most browsers now since about 2017. Here is a link to some documentation: https://css-tricks.com/snippets/css/complete-guide-grid/ . It is so much easier to keep your page elements where you want them, especially when it comes to responsiveness. It took me all of 20 minutes to learn how to do it, and I'm a newbie!
<div class="grid-div">
<p class="hello">Hello</p>
<p class="world">World</p>
</div>
//begin css//
.grid-div {
display: grid;
grid-template-columns: 50% 50%;
grid-template-rows: 50% 50%;
}
.hello {
grid-column-start: 2;
grid-row-start: 2;
}
.world {
grid-column-start: 1;
grid-row-start: 2;
}
This code will split the page into 4 equal quadrants, placing the "Hello" in the bottom right, and the "World" in the bottom left without having to change their positioning or playing with margins.
This can be extrapolated into very complex grid layouts with overlapping, infinite grids of all sizes, and even grids nested inside grids, without losing control of your elements every time something changes (MS Word I'm looking at you).
Hope this helps whoever still needs it!
I like doing something like this:
Message::select('*')
->from(DB::raw("( SELECT * FROM `messages`
WHERE `to_id` = ".Auth::id()." AND `isseen` = 0
GROUP BY `from_id` asc) as `sub`"))
->count();
It's not very elegant, but it's simple.
This worked for me may times:
ssh -x remoteServer "cd yourRemoteDir; ./yourRemoteScript.sh </dev/null >/dev/null 2>&1 & "
Attempting to debug in RubyMine using Ubuntu 18.04, Ruby 2.6.*, Rails 5, & RubyMine 2019.1.1, I ran into the same issue.
To resolve the issue, I uncommented the mini_racer
line from my Gemfile
and then ran bundle
:
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
Change to:
# See https://github.com/rails/execjs#readme for more supported runtimes
gem 'mini_racer', platforms: :ruby
It seems that OpenQA, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to //td[text()="${nbsp}"]
.
I reproduced here the text from OpenQA concerning this issue (found here):
HTML automatically normalizes whitespace within elements, ignoring leading/trailing spaces and converting extra spaces, tabs and newlines into a single space. When Selenium reads text out of the page, it attempts to duplicate this behavior, so you can ignore all the tabs and newlines in your HTML and do assertions based on how the text looks in the browser when rendered. We do this by replacing all non-visible whitespace (including the non-breaking space "
") with a single space. All visible newlines (<br>
,<p>
, and<pre>
formatted new lines) should be preserved.We use the same normalization logic on the text of HTML Selenese test case tables. This has a number of advantages. First, you don't need to look at the HTML source of the page to figure out what your assertions should be; "
" symbols are invisible to the end user, and so you shouldn't have to worry about them when writing Selenese tests. (You don't need to put "
" markers in your test case to assertText on a field that contains "
".) You may also put extra newlines and spaces in your Selenese<td>
tags; since we use the same normalization logic on the test case as we do on the text, we can ensure that assertions and the extracted text will match exactly.This creates a bit of a problem on those rare occasions when you really want/need to insert extra whitespace in your test case. For example, you may need to type text in a field like this: "
foo
". But if you simply write<td>foo </td>
in your Selenese test case, we'll replace your extra spaces with just one space.This problem has a simple workaround. We've defined a variable in Selenese,
${space}
, whose value is a single space. You can use${space}
to insert a space that won't be automatically trimmed, like this:<td>foo${space}${space}${space}</td>
. We've also included a variable${nbsp}
, that you can use to insert a non-breaking space.Note that XPaths do not normalize whitespace the way we do. If you need to write an XPath like
//div[text()="hello world"]
but the HTML of the link is really "hello world
", you'll need to insert a real "
" into your Selenese test case to get it to match, like this://div[text()="hello${nbsp}world"]
.
For JavaScript arrays, you use Both push() and concat() function.
var array = [1, 2, 3];
array.push(4, 5); //use push for appending a single array.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); //It is better use concat for appending more then one array.
You can also use the following instruction:
Reserved.objects.filter(client=client_id).order_by('check_in').reverse()
I just tested your snippet, and their is no double spacing line here. The end-of-line are \r\n
, so what i would check in your case is:
(Note that even by putting a value with \n, DictWriter automaticly quote the value.)
Hiding HTML source isn't really possible. Disabling right-click only frustrates users who wish to do something constructive with your content (copy/paste content or forms, or print, for example).
If you're running a server-side scripting language you could obfuscate or minify the HTML, CSS and Javascript. This will make it harder for someone to copy your code or see how you've achieved certain effects.
You specified both jQuery and Javascript in the tags so here's both approaches.
jQuery
var selector = '.nav li';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/
Pure Javascript:
var selector, elems, makeActive;
selector = '.nav li';
elems = document.querySelectorAll(selector);
makeActive = function () {
for (var i = 0; i < elems.length; i++)
elems[i].classList.remove('active');
this.classList.add('active');
};
for (var i = 0; i < elems.length; i++)
elems[i].addEventListener('mousedown', makeActive);
Fiddle: http://jsfiddle.net/rn3nc/1
jQuery with event delegation:
Please note that in approach 1, the handler is directly bound to that element. If you're expecting the DOM to update and new li
s to be injected, it's better to use event delegation and delegate to the next element that will remain static, in this case the .nav
:
$('.nav').on('click', 'li', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/1/
The subtle difference is that the handler is bound to the .nav
now, so when you click the li
the event bubbles up the DOM to the .nav
which invokes the handler if the element clicked matches your selector
argument. This means new elements won't need a new handler bound to them, because it's already bound to an ancestor.
It's really quite interesting. Read more about it here: http://api.jquery.com/on/
OPT
ional
It holds optional software and packages that you install that are not required for the system to run.
For me, restarting my phone did the trick.
class
& new
are 2 constraints on the generic type parameter T
.
Respectively they ensure:
class
The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
new
The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.
Their combination means that the type T
must be a Reference Type (can't be a Value Type), and must have a parameterless constructor.
Example:
struct MyStruct { } // structs are value types
class MyClass1 { } // no constructors defined, so the class implicitly has a parameterless one
class MyClass2 // parameterless constructor explicitly defined
{
public MyClass2() { }
}
class MyClass3 // only non-parameterless constructor defined
{
public MyClass3(object parameter) { }
}
class MyClass4 // both parameterless & non-parameterless constructors defined
{
public MyClass4() { }
public MyClass4(object parameter) { }
}
interface INewable<T>
where T : new()
{
}
interface INewableReference<T>
where T : class, new()
{
}
class Checks
{
INewable<int> cn1; // ALLOWED: has parameterless ctor
INewable<string> n2; // NOT ALLOWED: no parameterless ctor
INewable<MyStruct> n3; // ALLOWED: has parameterless ctor
INewable<MyClass1> n4; // ALLOWED: has parameterless ctor
INewable<MyClass2> n5; // ALLOWED: has parameterless ctor
INewable<MyClass3> n6; // NOT ALLOWED: no parameterless ctor
INewable<MyClass4> n7; // ALLOWED: has parameterless ctor
INewableReference<int> nr1; // NOT ALLOWED: not a reference type
INewableReference<string> nr2; // NOT ALLOWED: no parameterless ctor
INewableReference<MyStruct> nr3; // NOT ALLOWED: not a reference type
INewableReference<MyClass1> nr4; // ALLOWED: has parameterless ctor
INewableReference<MyClass2> nr5; // ALLOWED: has parameterless ctor
INewableReference<MyClass3> nr6; // NOT ALLOWED: no parameterless ctor
INewableReference<MyClass4> nr7; // ALLOWED: has parameterless ctor
}
Use directions service of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map.
Information and examples about rendering the directions route on the map can be found in rendering directions section of Google Maps API v3 documentation.
You might want to see this page:
http://blog.niklasottosson.com/?p=1914
I guess you can go something like this:
DEMO:http://jsfiddle.net/g9eL6768/2/
HTML:
<table id="mytable"><thead>
<tr>
<th id="sl">S.L.</th>
<th id="nm">name</th>
</tr>
....
JS:
// sortTable(f,n)
// f : 1 ascending order, -1 descending order
// n : n-th child(<td>) of <tr>
function sortTable(f,n){
var rows = $('#mytable tbody tr').get();
rows.sort(function(a, b) {
var A = getVal(a);
var B = getVal(b);
if(A < B) {
return -1*f;
}
if(A > B) {
return 1*f;
}
return 0;
});
function getVal(elm){
var v = $(elm).children('td').eq(n).text().toUpperCase();
if($.isNumeric(v)){
v = parseInt(v,10);
}
return v;
}
$.each(rows, function(index, row) {
$('#mytable').children('tbody').append(row);
});
}
var f_sl = 1; // flag to toggle the sorting order
var f_nm = 1; // flag to toggle the sorting order
$("#sl").click(function(){
f_sl *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_sl,n);
});
$("#nm").click(function(){
f_nm *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_nm,n);
});
Hope this helps.
I used the following property which works fine for me:
$('#selector').dialog({
minHeight: 'auto'
});
Since you also have PHP in the tag, I'm going to suggest some server side options.
The easiest solution is the one most people suggest here. The problem I generally have with this, is that it can causes your CSS files or <style> tags to be up to 20 times bigger than your html documents and can cause browser slowdowns for parsing and processing tags that it can't understand -moz-border-radius
vs -webkit-border-radius
The second best solution(i've found) is to have php output your actual css file i.e.
<link rel="stylesheet" type="text/css" href="mycss.php">
where
<?php header("Content-Type: text/css"); if( preg_match("/chrome/", $_SERVER['HTTP_USER_AGENT']) ) { // output chrome specific css style } else { // output default css style } ?>
This allows you to create smaller easier to process files for the browser.
The best method I've found, is specific to Apache though. The method is to use mod_rewrite or mod_perl's PerlMapToStorageHandler to remap the URL to a file on the system based on the rendering engine.
say your website is http://www.myexample.com/
and it points to /srv/www/html
. For chrome, if you ask for main.css, instead of loading /srv/www/html/main.css
it checks to see if there is a /srv/www/html/main.webkit.css
and if it exists, it dump that, else it'll output the main.css. For IE, it tries main.trident.css
, for firefox it tries main.gecko.css
. Like above, it allows me to create smaller, more targeted, css files, but it also allows me to use caching better, as the browser will attempt to redownload the file, and the web server will present the browser with proper 304's to tell it, you don't need to redownload it. It also allows my web developers a bit more freedom without for them having to write backend code to target platforms. I also have .js files being redirected to javascript engines as well, for main.js
, in chrome it tries main.v8.js
, in safari, main.nitro.js
, in firefox, main.gecko.js
. This allows for outputting of specific javascript that will be faster(less browser testing code/feature testing). Granted the developers don't have to target specific and can write a main.js
and not make main.<js engine>.js
and it'll load that normally. i.e. having a main.js
and a main.jscript.js
file means that IE gets the jscript one, and everyone else gets the default js, same with the css files.
Code:
^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]+\.[0-9]*[1-9][0-9]*)$
Example: http://regexr.com/3anf5
This may be what you are looking for...
http://technet.microsoft.com/en-us/library/cc730708%28WS.10%29.aspx
I would also advise longer term to consider a limited rights domain user, what you are trying works fine in a silo machine scenario but you are going to have to make changes if you move to another machine for the DB server.
i created a package. it may meet your needs.
https://github.com/caoyongfeng0214/rn-overlaye
<View style={{paddingBottom:100}}>
<View> ...... </View>
<Overlay style={{left:0, right:0, bottom:0}}>
<View><Text>Footer</Text></View>
</Overlay>
</View>
You are able to choose one that you like, but it has to be unique.
Every time I have to enter the SKU I use the App identifier (e.g. de.mycompany.myappname
) because this is already unique.
Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:
'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'
Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)
Today I had to search for the first key of my array returned by a POST request. (And note the number for a form id etc)
Well, I've found this: Return first key of associative array in PHP
I've done this, and it work.
$data = $request->request->all();
dump($data);
while ($test = current($data)) {
dump($test);
echo key($data).'<br />';die();
break;
}
Maybe it will eco 15min of an other guy. CYA.
I believe that I have the simplest answer. You don't need the string.h library in this program, nor the stdbool.h library. Simply using pointers and pointer arithmetic will help you become a better C programmer.
Simply return 0 for False (no substring found), or 1 for True (yes, a substring "sub" is found within the overall string "str"):
#include <stdlib.h>
int is_substr(char *str, char *sub)
{
int num_matches = 0;
int sub_size = 0;
// If there are as many matches as there are characters in sub, then a substring exists.
while (*sub != '\0') {
sub_size++;
sub++;
}
sub = sub - sub_size; // Reset pointer to original place.
while (*str != '\0') {
while (*sub == *str && *sub != '\0') {
num_matches++;
sub++;
str++;
}
if (num_matches == sub_size) {
return 1;
}
num_matches = 0; // Reset counter to 0 whenever a difference is found.
str++;
}
return 0;
}
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
Observable
, Observer
)ContainerAdapter
, ComponentAdapter
, FocusAdapter
, KeyAdapter
, MouseAdapter
are not adapters; they are actually Null Objects. Poor naming choice by Sun.BufferedInputStream
can decorate other streams such as FilterInputStream
)java.lang.Runtime#getRuntime()
is SingletonButtonGroup
for Mediator patternAction
, AbstractAction
may be used for different visual representations to execute same code -> Command patternand many more I guess
You could also use the CountDownLatch
object like explained here.
instead of os.walk
, just use os.listdir
You need CORS proxy which proxies your request from your browser to requested service with appropriate CORS headers. List of such services are in code snippet below. You can also run provided code snippet to see ping to such services from your location.
$('li').each(function() {_x000D_
var self = this;_x000D_
ping($(this).text()).then(function(delta) {_x000D_
console.log($(self).text(), delta, ' ms');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/jdfreder/pingjs/c2190a3649759f2bd8569a72ae2b597b2546c871/ping.js"></script>_x000D_
<ul>_x000D_
<li>https://crossorigin.me/</li>_x000D_
<li>https://cors-anywhere.herokuapp.com/</li>_x000D_
<li>http://cors.io/</li>_x000D_
<li>https://cors.5apps.com/?uri=</li>_x000D_
<li>http://whateverorigin.org/get?url=</li>_x000D_
<li>https://anyorigin.com/get?url=</li>_x000D_
<li>http://corsproxy.nodester.com/?src=</li>_x000D_
<li>https://jsonp.afeld.me/?url=</li>_x000D_
<li>http://benalman.com/code/projects/php-simple-proxy/ba-simple-proxy.php?url=</li>_x000D_
</ul>
_x000D_
Try wexpect, which is the windows alternative of pexpect.
import wexpect
p = wexpect.spawn('myprogram.exe')
p.stdout.readline('.') // regex pattern of any character
output_str = p.after()
I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:
Actually, there's a much simpler way to do this. If you just open the batch file, click on the window, and then click "properties", and then to "layout", and scroll down to "Window Size", you can edit it from there. It will also stay that way every time you open that specific batch file, so it's pretty handy.
Files named __init__.py
are used to mark directories on disk as Python package directories.
If you have the files
mydir/spam/__init__.py
mydir/spam/module.py
and mydir
is on your path, you can import the code in module.py
as
import spam.module
or
from spam import module
If you remove the __init__.py
file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
The __init__.py
file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc.
Given the example above, the contents of the init module can be accessed as
import spam
based on this
The easiest way to add these headers is a .htaccess
file that adds some configuration to your server. If the assets are hosted on a server that you don't control, there's nothing you can do about it.
Note that some hosting providers will not let you use .htaccess
files, so check their terms if it doesn't seem to work.
The HTML5Boilerplate project has an excellent .htaccess
file that covers the necessary settings. See the relevant part of the file at their Github repository
These are the important bits
# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------
# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".
<IfModule mod_expires.c>
ExpiresActive on
# Your document html
ExpiresByType text/html "access plus 0 seconds"
# Media: images, video, audio
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
# CSS and JavaScript
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
</IfModule>
They have documented what that file does, the most important bit is that you need to rename your CSS and Javascript files whenever they change, because your visitor's browsers will not check them again for a year, once they are cached.
Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:
Html.Hidden("Name", "Value")
Will result in:
<input id="Name" name="Name" type="hidden" value="Value">
In your controller, you might have an action like:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
}
And a model like:
public class MyModel
{
public string Name { get; set; }
}
The raw Html.Hidden
we used above will get correlated to the Name
property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name
property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor
, you get protected from that:
Html.HiddenFor(x => x.Name, "Value");
Now, if you rename the Name
property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x.
.
To add with @msandiford answer, as most of the times when a file tree is walked u may want to execute a function as a directory or any particular file is visited. If u are reluctant to using streams. The following methods overridden can be implemented
Files.walkFileTree(Paths.get(Krawl.INDEXPATH), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// Do someting before directory visit
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// Do something when a file is visited
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
// Do Something after directory visit
return FileVisitResult.CONTINUE;
}
});
What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).
There are two ways to count total number of records that the query will return. First this
$query = $this->db->query('select blah blah');
return $query->num_rows();
This will return number of rows the query brought.
Second
return $this->db->count_all_results('select blah blah');
Simply count_all_results will require to run the query again.
I've just had some of the similar problems with scrollTop
described here.
In the end I got around this on Firefox and IE by using the selector $('*').scrollTop(0);
Not perfect if you have elements you don't want to effect but it gets around the Document, Body, HTML and Window disparity. If it helps...
Uninstall whatever node version you have
sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs-legacy
sudo apt-get --purge remove nodejs
install nvm (Node Version Manager) https://github.com/creationix/nvm
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash
Now you can install whatever version of node you want and switch between the versions.
Always check manually the methods, tags you use, and make sure that they always escape (once) in the end. Frameworks have many bugs and differences in this aspect.
An overview: http://www.gablog.eu/online/node/91
I had the same error, although in my case the problem was with the formatting of the DESTINATION path. The comments above are correct with respect to debugging the path string formatting, but there seems to be a bug in the File.Copy exception reporting where it still throws back the SOURCE path instead of the DESTINATION path. So don't forget to look here as well.
-TC
The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).
This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
(emphasis mine)
You can pivot your DataFrame after creating:
>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1 c1 c2
0
r1 avg11 avg12
r2 avg21 avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1 c1 c2
0
r1 stdev11 stdev12
r2 stdev21 stdev22
You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:
Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
By using just jQuery, you cannot avoid a server call.
However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.
To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.
I just added the environment variable Boost_INCLUDE_DIR or add it to the cmake command -DBoost_INCLUDE_DIR and point to the include folder.
Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this:
const
declares an object as constant. This implies a guarantee that once initialized, the value of that object won't change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization.
constexpr
declares an object as fit for use in what the Standard calls constant expressions. But note that constexpr
is not the only way to do this.
When applied to functions the basic difference is this:
const
can only be used for non-static member functions, not functions in general. It gives a guarantee that the member function does not modify any of the non-static data members (except for mutable data members, which can be modified anyway).
constexpr
can be used with both member and non-member functions, as well as constructors. It declares the function fit for use in constant expressions. The compiler will only accept it if the function meets certain criteria (7.1.5/3,4), most importantly (†):
return
statement is allowed. In the case of a constructor, only an initialization list, typedefs, and static assert are allowed. (= default
and = delete
are allowed, too, though.)asm
declaration, a goto
statement, a statement with a label other than case
and default
, try-block, the definition of a variable of non-literal type, definition of a variable of static or thread storage duration, the definition of a variable for which no initialization is performed.As said above, constexpr
declares both objects as well as functions as fit for use in constant expressions. A constant expression is more than merely constant:
It can be used in places that require compile-time evaluation, for example, template parameters and array-size specifiers:
template<int N>
class fixed_size_list
{ /*...*/ };
fixed_size_list<X> mylist; // X must be an integer constant expression
int numbers[X]; // X must be an integer constant expression
But note:
Declaring something as constexpr
does not necessarily guarantee that it will be evaluated at compile time. It can be used for such, but it can be used in other places that are evaluated at run-time, as well.
An object may be fit for use in constant expressions without being declared constexpr
. Example:
int main()
{
const int N = 3;
int numbers[N] = {1, 2, 3}; // N is constant expression
}
This is possible because N
, being constant and initialized at declaration time with a literal, satisfies the criteria for a constant expression, even if it isn't declared constexpr
.
So when do I actually have to use constexpr
?
N
above can be used as constant expression without being declared constexpr
. This is true for all objects that are:const
[This is due to §5.19/2: A constant expression must not include a subexpression that involves "an lvalue-to-rvalue modification unless […] a glvalue of integral or enumeration type […]" Thanks to Richard Smith for correcting my earlier claim that this was true for all literal types.]
For a function to be fit for use in constant expressions, it must be explicitly declared constexpr
; it is not sufficient for it merely to satisfy the criteria for constant-expression functions. Example:
template<int N>
class list
{ };
constexpr int sqr1(int arg)
{ return arg * arg; }
int sqr2(int arg)
{ return arg * arg; }
int main()
{
const int X = 2;
list<sqr1(X)> mylist1; // OK: sqr1 is constexpr
list<sqr2(X)> mylist2; // wrong: sqr2 is not constexpr
}
When can I / should I use both, const
and constexpr
together?
A. In object declarations. This is never necessary when both keywords refer to the same object to be declared. constexpr
implies const
.
constexpr const int N = 5;
is the same as
constexpr int N = 5;
However, note that there may be situations when the keywords each refer to different parts of the declaration:
static constexpr int N = 3;
int main()
{
constexpr const int *NP = &N;
}
Here, NP
is declared as an address constant-expression, i.e. a pointer that is itself a constant expression. (This is possible when the address is generated by applying the address operator to a static/global constant expression.) Here, both constexpr
and const
are required: constexpr
always refers to the expression being declared (here NP
), while const
refers to int
(it declares a pointer-to-const). Removing the const
would render the expression illegal (because (a) a pointer to a non-const object cannot be a constant expression, and (b) &N
is in-fact a pointer-to-constant).
B. In member function declarations. In C++11, constexpr
implies const
, while in C++14 and C++17 that is not the case. A member function declared under C++11 as
constexpr void f();
needs to be declared as
constexpr void f() const;
under C++14 in order to still be usable as a const
function.
Easier solution for wamp is: go to phpMyAdmin, click localhost, select latin1_bin for Server connection collation, then start to create database and table
What I do on my cloud instances is I redirect port 80 to port 3000 with this command:
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000
Then I launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.
You should also edit your /etc/rc.local
file and add that line minus the sudo
. That will add the redirect when the machine boots up. You don't need sudo
in /etc/rc.local
because the commands there are run as root
when the system boots.
Use the forever module to launch your Node.js with. It will make sure that it restarts if it ever crashes and it will redirect console logs to a file.
Add your Node.js start script to the file you edited for port redirection, /etc/rc.local
. That will run your Node.js launch script when the system starts.
This not only applies to Linode, but Digital Ocean, AWS EC2 and other VPS providers as well. However, on RedHat based systems /etc/rc.local
is /ect/rc.d/local
.
You Just Simply have to Follow these steps for making it easy...
You don't have to write new onClickListener
for Every Button
... Just Implement View.OnClickLister
to your Activity
/Fragment
.. it will implement new Method called onClick()
for handling onClick Events for Button
,TextView` etc.
- Implement
OnClickListener()
in yourActivity
/Fragment
public class MainActivity extends Activity implements View.OnClickListener {
}
- Implement onClick() method in your Activity/Fragment
public class MainActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onClick(View v) {
// default method for handling onClick Events..
}
}
- Implement
OnClickListener()
For Buttons
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Button one = (Button) findViewById(R.id.oneButton);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.twoButton);
two.setOnClickListener(this);
Button three = (Button) findViewById(R.id.threeButton);
three.setOnClickListener(this);
}
- Find Buttons By Id and Implement Your Code..
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
case R.id.threeButton:
// do your code
break;
default:
break;
}
}
Please refer to this link for more information :
https://androidacademic.blogspot.com/2016/12/multiple-buttons-onclicklistener-android.html (updated)
This will make easier to handle many buttons click events and makes it looks simple to manage it...
You are not returning. Change to
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>;
})
This video tutorial worked for me:
$ curl https://bootstrap.pypa.io/get-pip.py | python
I originally used the code taken from the discussion thread that @nmichaels used in his answer. I now use a slightly different calculation. I've included some comments in case anyone else has the same query as @Arijoon
const (
MinUint uint = 0 // binary: all zeroes
// Perform a bitwise NOT to change every bit from 0 to 1
MaxUint = ^MinUint // binary: all ones
// Shift the binary number to the right (i.e. divide by two)
// to change the high bit to 0
MaxInt = int(MaxUint >> 1) // binary: all ones except high bit
// Perform another bitwise NOT to change the high bit to 1 and
// all other bits to 0
MinInt = ^MaxInt // binary: all zeroes except high bit
)
The last two steps work because of how positive and negative numbers are represented in two's complement arithmetic. The Go language specification section on Numeric types refers the reader to the relevant Wikipedia article. I haven't read that, but I did learn about two's complement from the book Code by Charles Petzold, which is a very accessible intro to the fundamentals of computers and coding.
I put the code above (minus most of the comments) in to a little integer math package.
To obtain the channel id you can view the source code of the channel page and find either data-channel-external-id="UCjXfkj5iapKHJrhYfAF9ZGg"
or "externalId":"UCjXfkj5iapKHJrhYfAF9ZGg"
.
UCjXfkj5iapKHJrhYfAF9ZGg
will be the channel ID you are looking for.
With IIS's self-signed certificate feature, you cannot set the common name (CN) for the certificate, and therefore cannot create a certificate bound to your choice of subdomain.
One way around the problem is to use makecert.exe, which is bundled with the .Net 2.0 SDK. On my server it's at:
C:\Program Files\Microsoft.Net\SDK\v2.0 64bit\Bin\makecert.exe
You can create a signing authority and store it in the LocalMachine certificates repository as follows (these commands must be run from an Administrator account or within an elevated command prompt):
makecert.exe -n "CN=My Company Development Root CA,O=My Company,
OU=Development,L=Wallkill,S=NY,C=US" -pe -ss Root -sr LocalMachine
-sky exchange -m 120 -a sha1 -len 2048 -r
You can then create a certificate bound to your subdomain and signed by your new authority:
(Note that the the value of the -in parameter must be the same as the CN value used to generate your authority above.)
makecert.exe -n "CN=subdomain.example.com" -pe -ss My -sr LocalMachine
-sky exchange -m 120 -in "My Company Development Root CA" -is Root
-ir LocalMachine -a sha1 -eku 1.3.6.1.5.5.7.3.1
Your certificate should then appear in IIS Manager to be bound to your site as explained in Tom Hall's post.
All kudos for this solution to Mike O'Brien for his excellent blog post at http://www.mikeobrien.net/blog/creating-self-signed-wildcard
def find_defining_class(obj, meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
So
print find_defining_class(car, 'speedometer')
Think Python page 210
You can also use insertAdjacentHTML
function:
const select = document.querySelector('select')
const value = 'bmw'
const label = 'BMW'
select.insertAdjacentHTML('beforeend', `
<option value="${value}">${label}</option>
`)
Got the same error when tried to export a large Excel file (~150.000 rows) Fixed with the following code
Application xlApp = new Application();
xlApp.DefaultSaveFormat = XlFileFormat.xlOpenXMLWorkbook;
FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :
strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"
I agree with @adietisheim and the rest of people that suggest HttpClient.
I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.
An example of code to make a put http call is as follows:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(URI);
StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
I usually end up going with a library like underscore-php these days.
require_once("vendor/autoload.php"); //use if needed
use Underscore\Types\String;
$str = "there is a string";
echo( String::startsWith($str, 'the') ); // 1
echo( String::endsWith($str, 'ring')); // 1
The library is full of other handy functions.
You could try adding the following script code to implement this:
if(CompareDates(smallDate,largeDate,'-') == 0) {
alert('Selected date must be current date or previous date!');
return false;
}
function CompareDates(smallDate,largeDate,separator) {
var smallDateArr = Array();
var largeDateArr = Array();
smallDateArr = smallDate.split(separator);
largeDateArr = largeDate.split(separator);
var smallDt = smallDateArr[0];
var smallMt = smallDateArr[1];
var smallYr = smallDateArr[2];
var largeDt = largeDateArr[0];
var largeMt = largeDateArr[1];
var largeYr = largeDateArr[2];
if(smallYr>largeYr)
return 0;
else if(smallYr<=largeYr && smallMt>largeMt)
return 0;
else if(smallYr<=largeYr && smallMt==largeMt && smallDt>largeDt)
return 0;
else
return 1;
}
In iOS 9, SSL connections will fail for all invalid or self-signed certificates. This is the default behavior of the new App Transport Security feature in iOS 9.0 or later, and on OS X 10.11 and later.
You can override this behavior in the Info.plist
, by setting NSAllowsArbitraryLoads
to YES
in the NSAppTransportSecurity
dictionary. However, I recommend overriding this setting for testing purposes only.
For information see App Transport Technote here.
This does not answer your specific question, but when I had the same problem I ended up here and I figured that more people might do the same.
The problem I had was that I had indeliberately declared my Get method as static. I missed this an entire forenoon, and it caused no warnings from attributes or similar.
Incorrect:
public class EchoController : ApiController
{
public static string Get()
{
return string.Empty;
}
}
Correct:
public class EchoController : ApiController
{
public string Get()
{
return string.Empty;
}
}
The correct character (comma or colon) depends on the purpose.
Comma (,
) will sum only the two cells in question.
Colon (:
) will sum all the cells within the range with corners defined by those two cells.
What if you compile it using another machine? A fresh installed one would be lovely. I hope your machine is not jealous.
Changing
RestResponse response = client.Execute(request);
to
IRestResponse response = client.Execute(request);
worked for me.
you could also do show columns in $table
or see Hive, how do I retrieve all the database's tables columns for access to hive metadata
A much simpler way to do this is to use vCenter Converter Standalone Client and do a P2V but in this case a V2V. It is much faster than copying the entire VM files onto some storage somewhere and copy it onto your new vCenter. It takes a long time to copy or exporting it to an OVF template and then import it. You can set your vCenter Converter Standalone Client to V2V in one step and synchronize and then have it power up the VM on the new Vcenter and shut off on the old vCenter. Simple.
For me using this method I was able to move a VM from one vCenter to another vCenter in about 30 minutes as compared to copying or exporting which took over 2hrs. Your results may vary.
This process below, from another responder, would work even better if you can present that datastore to ESXi servers on the vCenter and then follow step 2. Eliminating having to copy all the VMs then follow rest of the process.
In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:
$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"
the only way I know of is to use the Win32 exclusive lock API which isn't too speedy, but examples exist.
Most people, for a simple solution to this, simply to try/catch/sleep loops.
A simple solution that worked for me is to close the Terminal and restart it.
Instead of shooting in the dark, get the reason for this error by installing it via adb
:
adb -s emulator-5555 install ~/path-to-your-apk/com.app.apk
Replace emulator-5555
with your device name. You can obtain a list using:
adb devices
Upon failing, it will give a reason. Common reasons and their fixes:
My solution:
Change back to bash
:
source .bashrc
next:
echo $PATH
copy this:
/home/frank/.asdf/shims:/home/frank/....
back to the zsh
:
source .zsh
open .zshrc
:
and paste:
export PATH=/home/frank/.asdf/shims:/home/frank/....
restart terminal
Got it :D
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
alert(getContextPath());
Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.
To only find the first locations, use lapply()
with min()
:
my_string <- c("test1", "test1test1", "test1test1test1")
unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(min) %>%
unlist()
#> [1] 5 5 5
To only find the last locations, use lapply()
with max()
:
unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1] 5 10 15
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(max) %>%
unlist()
#> [1] 5 10 15
here's what I did to alert user in case their network went down or upon page update failure:
I have a div-tag on the page where I put current time and update this tag every 10 seconds. It looks something like this: <div id="reloadthis">22:09:10</div>
At the end of the javascript function that updates the time in the div-tag, I put this (after time is updated with AJAX):
var new_value = document.getElementById('reloadthis').innerHTML;
var new_length = new_value.length;
if(new_length<1){
alert("NETWORK ERROR!");
}
That's it! You can replace the alert-part with anything you want, of course. Hope this helps.
I had the same problem - i wanted to pass a parameter to another page by clicking a hyperlink and get the value to go to the next page (without using GET because the parameter is stored in the URL).
to those who don't understand why you would want to do this the answer is you dont want the user to see sensitive information or you dont want someone editing the GET.
well after scouring the internet it seemed it wasnt possible to make a normal hyperlink using the POST method.
And then i had a eureka moment!!!! why not just use CSS to make the submit button look like a normal hyperlink??? ...and put the value i want to pass in a hidden field
i tried it and it works. you can see an exaple here http://paulyouthed.com/test/css-button-that-looks-like-hyperlink.php
the basic code for the form is:
<form enctype="multipart/form-data" action="page-to-pass-to.php" method="post">
<input type="hidden" name="post-variable-name" value="value-you-want-pass"/>
<input type="submit" name="whatever" value="text-to-display" id="hyperlink-style-button"/>
</form>
the basic css is:
#hyperlink-style-button{
background:none;
border:0;
color:#666;
text-decoration:underline;
}
#hyperlink-style-button:hover{
background:none;
border:0;
color:#666;
text-decoration:none;
cursor:pointer;
cursor:hand;
}
Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.
The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.
arrayData.forEach((key : any, val: any) => {
key['index'] = val + 1;
arrayData2.forEach((keys : any, vals :any) => {
if (key.group_id == keys.id) {
key.group_name = keys.group_name;
}
})
})
Make a state machine that operates on one basic principle: is the current character a number.
Optimizations are possible.
You can't do it with the HTML5 input type. There are many libs available to do it, you can use momentjs or some other jQuery UI components for the best outcome.
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textFile=Input.txt"
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
for /f
will read all the data (generated by the type
comamnd) before starting to process it. In the subprocess started to execute the type
, we include a redirection overwritting the file (so it is emptied). Once the do
clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.
I know this is too late. But i solved this issue with following Code:
Java Script:
Handlebars.registerHelper('eachData', function(context, options) {
var fn = options.fn, inverse = options.inverse, ctx;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ctx = Object.create(context[i]);
ctx.index = i;
ret = ret + fn(ctx);
}
} else {
ret = inverse(this);
}
return ret;
});
HTML:
{{#eachData items}}
{{index}} // You got here start with 0 index
{{/eachData}}
if you want start your index with 1 you should do following code:
Javascript:
Handlebars.registerHelper('eachData', function(context, options) {
var fn = options.fn, inverse = options.inverse, ctx;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ctx = Object.create(context[i]);
ctx.index = i;
ret = ret + fn(ctx);
}
} else {
ret = inverse(this);
}
return ret;
});
Handlebars.registerHelper("math", function(lvalue, operator, rvalue, options) {
lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);
return {
"+": lvalue + rvalue
}[operator];
});
HTML:
{{#eachData items}}
{{math index "+" 1}} // You got here start with 1 index
{{/eachData}}
Thanks.
public static int minIndex (ArrayList<Float> list) {
return list.indexOf (Collections.min(list));
}
System.out.println("Min = " + list.get(minIndex(list));
In addition to @Boaz's and @vegemite4me's answers....
By implementing ImplicitNamingStrategy
you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder
during Hibernate's initialization:
metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());
It works for @UniqueConstraint
, but not for @Column(unique = true)
, which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).
There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586
Thanks.
What eventually worked for me, after lot's of confusing manuals and confusing tutorials, since Docker is obviously at time of my writing at peek of inflated expectations, is:
docker save image_name > image_name.tar
cat image_name.tar | docker load
Export and import, as proposed in another answers does not export ports and variables, which might be required for your container to run. And you might end up with stuff like "No command specified" etc... When you try to load it on another machine.
So, difference between save and export is that save command saves whole image with history and metadata, while export command exports only files structure (without history or metadata).
Needless to say is that, if you already have those ports taken on the docker hyper-visor you are doing import, by some other docker container, you will end-up in conflict, and you will have to reconfigure exposed ports.
Note: In order to move data with docker, you might be having persistent storage somewhere, which should also be moved alongside with containers.
Or even more simple if you don't want to use a lot of linq and for some reason don't want to use a for loop.
int i = 0;
foreach(var x in arr)
{
//Do some stuff
i++;
}
I was using Android Pie and nothing seemed to worked so I played around with app:tabTextAppearance attribute. I know its not the perfect answer but might help someone.
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabTextAppearance="@style/TextAppearance.AppCompat.Caption" />
Just got this error msg on my 32 bit Windows - I read the FAQ here: http://pythonware.com/products/pil/faq.htm and this sort of indicates that Windows is funny. Looked again at install pg and downloaded the Windows executable for Python26 # Python Imaging Library 1.1.7 for Python 2.6 (Windows only) - and the _imaging module gets installed when you run this. Should solve problem. So you can't just do the python setup.py install routine on: Python Imaging Library 1.1.7 Source Kit (all platforms) (November 15, 2009).
Enable Microsoft ActiveX Data Objects 2.8 Library
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=yourdatabase;" & _
"USER=yourdbusername;" & _
"PASSWORD=yourdbpassword;" & _
"Option=3"
End Sub
There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/
Attach an event listener to the form using .addEventListener()
and then call the .preventDefault()
method on event
:
const element = document.querySelector('form');_x000D_
element.addEventListener('submit', event => {_x000D_
event.preventDefault();_x000D_
// actual logic, e.g. validate the form_x000D_
console.log('Form submission cancelled.');_x000D_
});
_x000D_
<form>_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
I think it's a better solution than defining a submit
event handler inline with the onsubmit
attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.
Using the .onsubmit
property of the form
DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick
.
$("#datepicker").datepicker("getDate")
returns a date object, not a string.
var dateObject = $("#datepicker").datepicker("getDate"); // get the date object
var dateString = dateObject.getFullYear() + '-' + (dateObject.getMonth() + 1) + '-' + dateObject.getDate();// Y-n-j in php date() format
For me, I had typed image with a lower case "i" instead of Image. So I did:
from PIL import Image
NOT from PIL import image
The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.
You can access web references via the advanced options in add service reference (if I recall correctly).
I'd use service reference because as I understand it, it's the newer mechanism of the two.
mkdir -p ~/.ssh/
cat your_key > ~/.ssh/authorized_keys
cat your_key >> ~/.ssh/authorized_keys
In my particular project I couldn't get it to work, and used declare var $;
. Not a clean/recommended solution, it doesnt recognise the JQuery variables, but I had no errors after using that (and had to for my automatic builds to succeed).
mysql datetime -> GregorianCalendar
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());
GregorianCalendar -> mysql datetime
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);
The reason why you are able to access the drive in when you normally run the executable from command prompt is that when u are executing it as normal exe you are running that application in the User account from which you have logged on . And that user has the privileges to access the network. But , when you install the executable as a service , by default if you see in the task manage it runs under 'SYSTEM' account . And you might be knowing that the 'SYSTEM' doesn't have rights to access network resources.
There can be two solutions to this problem.
To map the drive as persistent as already pointed above.
There is one more approach that can be followed. If you open the service manager by typing in the 'services.msc'you can go to your service and in the properties of your service there is a logOn tab where you can specify the account as any other account than 'System' you can either start service from your own logged on user account or through 'Network Service'. When you do this .. the service can access any network component and drive even if they are not persistent also. To achieve this programmatically you can look into 'CreateService' function at http://msdn.microsoft.com/en-us/library/ms682450(v=vs.85).aspx and can set the parameter 'lpServiceStartName ' to 'NT AUTHORITY\NetworkService'. This will start your service under 'Network Service' account and then you are done.
You can also try by making the service as interactive by specifying SERVICE_INTERACTIVE_PROCESS in the servicetype parameter flag of your CreateService() function but this will be limited only till XP as Vista and 7 donot support this feature.
Hope the solutions help you.. Let me know if this worked for you .
Try this solution for keep selected value in dropdown:
<form action="<?php echo get_page_link(); ?>" method="post">
<select name="<?php echo $field_key['key']; ?>" onchange="javascript:
submit()">
<option value="">All Category</option>
<?php
foreach( $field['choices'] as $key => $value ){
if($post_key==$key){ ?>
<option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
}else{?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php }
}?>
</select>
</form>
What you're doing is correct. Fragments
don't have access to the ActionBar
APIs, so you have to call getActivity
. Unless your Fragment
is a static inner class, in which case you should create a WeakReference
to the parent and call Activity.getActionBar
from there.
To set the title for your ActionBar
, while using a custom layout, in your Fragment
you'll need to call getActivity().setTitle(YOUR_TITLE)
.
The reason you call setTitle
is because you're calling getTitle
as the title of your ActionBar
. getTitle
returns the title for that Activity
.
If you don't want to get call getTitle
, then you'll need to create a public method that sets the text of your TextView
in the Activity
that hosts the Fragment
.
In your Activity:
public void setActionBarTitle(String title){
YOUR_CUSTOM_ACTION_BAR_TITLE.setText(title);
}
In your Fragment:
((MainFragmentActivity) getActivity()).setActionBarTitle(YOUR_TITLE);
Docs:
Also, you don't need to call this.whatever
in the code you provided, just a tip.
I think you misunderstand Unicode and its relationship to Perl. No matter which way you store data, Unicode, ISO-8859-1, or many other things, your program has to know how to interpret the bytes it gets as input (decoding) and how to represent the information it wants to output (encoding). Get that interpretation wrong and you garble the data. There isn't some magic default setup inside your program that's going to tell the stuff outside your program how to act.
You think it's hard, most likely, because you are used to everything being ASCII. Everything you should have been thinking about was simply ignored by the programming language and all of the things it had to interact with. If everything used nothing but UTF-8 and you had no choice, then UTF-8 would be just as easy. But not everything does use UTF-8. For instance, you don't want your input handle to think that it's getting UTF-8 octets unless it actually is, and you don't want your output handles to be UTF-8 if the thing reading from them can't handle UTF-8. Perl has no way to know those things. That's why you are the programmer.
I don't think Unicode in Perl 5 is too complicated. I think it's scary and people avoid it. There's a difference. To that end, I've put Unicode in Learning Perl, 6th Edition, and there's a lot of Unicode stuff in Effective Perl Programming. You have to spend the time to learn and understand Unicode and how it works. You're not going to be able to use it effectively otherwise.
/stop([a-zA-Z])+/
Will match any stop word (stop, stopped, stopping, etc)
However, if you just want to match "stop" at the start of a string
/^stop/
will do :D
I finished my time alert with a unwanted effect.... Browsers add stuff to windows. My script is an aptated one and I will show after the following text.
I found a CSS script for popups, which doesn't have unwanted browser stuff. This was written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO. This script I will show after the following text.
This CSS script above looks professional and is alot more tidy. This button could be a clickable company logo image. By suppressing this button/image from running a function, this means you can run this function from inside javascript or call it with CSS, without it being run by clicking it.
This popup alert stays inside the window that popped it up. So if you are a multi-tasker you won't have trouble knowing what alert goes with what window.
The statements above are valid ones.... (Please allow). How these are achieved will be down to experimentation, as my knowledge of CSS is limited at the moment, but I learn fast.
CSS menus/DHTML use mouseover(valid statement).
I have a CSS menu script of my own which is adapted from 'Javascript for dummies' that pops up a menu alert. This works, but text size is limited. This hides under the top window banner. This could be set to be timed alert. This isn't great, but I will show this after the following text.
The Prakash script above I feel could be the answer if you can adapt it.
Scripts that follow:- My adapted timed window alert, Prakash's CSS popup script, my timed menu alert.
1.
<html>
<head>
<title></title>
<script language="JavaScript">
// Variables
leftposition=screen.width-350
strfiller0='<table border="1" cellspacing="0" width="98%"><tr><td><br>'+'Alert: '+'<br><hr width="98%"><br>'
strfiller1=' This alert is a timed one.'+'<br><br><br></td></tr></table>'
temp=strfiller0+strfiller1
// Javascript
// This code belongs to Stephen Mayes Date: 25/07/2016 time:8:32 am
function preview(){
preWindow= open("", "preWindow","status=no,toolbar=no,menubar=yes,width=350,height=180,left="+leftposition+",top=0");
preWindow.document.open();
preWindow.document.write(temp);
preWindow.document.close();
setTimeout(function(){preWindow.close()},4000);
}
</script>
</head>
<body>
<input type="button" value=" Open " onclick="preview()">
</body>
</html>
2.
<style>
body {
font-family: Arial, sans-serif;
background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
background-size: cover;
height: 100vh;
}
h1 {
text-align: center;
font-family: Tahoma, Arial, sans-serif;
color: #06D85F;
margin: 80px 0;
}
.box {
width: 40%;
margin: 0 auto;
background: rgba(255,255,255,0.2);
padding: 35px;
border: 2px solid #fff;
border-radius: 20px/50px;
background-clip: padding-box;
text-align: center;
}
.button {
font-size: 1em;
padding: 10px;
color: #fff;
border: 2px solid #06D85F;
border-radius: 20px/50px;
text-decoration: none;
cursor: pointer;
transition: all 0.3s ease-out;
}
.button:hover {
background: #06D85F;
}
.overlay {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.7);
transition: opacity 500ms;
visibility: hidden;
opacity: 0;
}
.overlay:target {
visibility: visible;
opacity: 1;
}
.popup {
margin: 70px auto;
padding: 20px;
background: #fff;
border-radius: 5px;
width: 30%;
position: relative;
transition: all 5s ease-in-out;
}
.popup h2 {
margin-top: 0;
color: #333;
font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
position: absolute;
top: 20px;
right: 30px;
transition: all 200ms;
font-size: 30px;
font-weight: bold;
text-decoration: none;
color: #333;
}
.popup .close:hover {
color: #06D85F;
}
.popup .content {
max-height: 30%;
overflow: auto;
}
@media screen and (max-width: 700px){
.box{
width: 70%;
}
.popup{
width: 70%;
}
}
</style>
<script>
// written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO
</script>
<body>
<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
<a class="button" href="#popup1">Let me Pop up</a>
</div>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Here i am</h2>
<a class="close" href="#">×</a>
<div class="content">
Thank to pop me out of that button, but now i'm done so you can close this window.
</div>
</div>
</div>
</body>
3.
<HTML>
<HEAD>
<TITLE>Using DHTML to Create Sliding Menus (From JavaScript For Dummies, 4th Edition)</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from older browsers
function displayMenu(currentPosition,nextPosition) {
// Get the menu object located at the currentPosition on the screen
var whichMenu = document.getElementById(currentPosition).style;
if (displayMenu.arguments.length == 1) {
// Only one argument was sent in, so we need to
// figure out the value for "nextPosition"
if (parseInt(whichMenu.top) == -5) {
// Only two values are possible: one for mouseover
// (-5) and one for mouseout (-90). So we want
// to toggle from the existing position to the
// other position: i.e., if the position is -5,
// set nextPosition to -90...
nextPosition = -90;
}
else {
// Otherwise, set nextPosition to -5
nextPosition = -5;
}
}
// Redisplay the menu using the value of "nextPosition"
whichMenu.top = nextPosition + "px";
}
// End hiding-->
</SCRIPT>
<STYLE TYPE="text/css">
<!--
.menu {position:absolute; font:10px arial, helvetica, sans-serif; background-color:#ffffcc; layer-background-color:#ffffcc; top:-90px}
#resMenu {right:10px; width:-130px}
A {text-decoration:none; color:#000000}
A:hover {background-color:pink; color:blue}
-->
</STYLE>
</HEAD>
<BODY BGCOLOR="white">
<div id="resMenu" class="menu" onmouseover="displayMenu('resMenu',-5)" onmouseout="displayMenu('resMenu',-90)"><br />
<a href="#"> Alert:</a><br>
<a href="#"> </a><br>
<a href="#"> You pushed that button again... Didn't yeah? </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
</div>
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
<input type="button" value="Wake that alert up" onclick="displayMenu('resMenu',-5)">
</BODY>
</HTML>
For the record: When you add an import, you are also indicating your dependencies.
You could see quickly what are the dependencies of files (excluding classes of the same namespace).
Adding the following line in the head tag fixed my issue.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
There is no big difference in data.The Major difference is column order In list tables schema column will be after table/view column In list tables show details schema column will be after column type
$('#select_id option:eq(0)').prop('selected', 'selected');
its good
MediaRecorder API is the solution you are looking for,
Firefox has been supporting it for some time now, and the buzz is is Chrome is gonna implement it in its next release (Chrome 48), but guess you still might need to enable the experimental flag, apparently the flag won't be need from Chrome version 49, for more info check out this Chrome issue.
Meanwhile, a sample of how to do it in Firefox:
var video, reqBtn, startBtn, stopBtn, ul, stream, recorder;
video = document.getElementById('video');
reqBtn = document.getElementById('request');
startBtn = document.getElementById('start');
stopBtn = document.getElementById('stop');
ul = document.getElementById('ul');
reqBtn.onclick = requestVideo;
startBtn.onclick = startRecording;
stopBtn.onclick = stopRecording;
startBtn.disabled = true;
ul.style.display = 'none';
stopBtn.disabled = true;
function requestVideo() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
})
.then(stm => {
stream = stm;
reqBtn.style.display = 'none';
startBtn.removeAttribute('disabled');
video.src = URL.createObjectURL(stream);
}).catch(e => console.error(e));
}
function startRecording() {
recorder = new MediaRecorder(stream, {
mimeType: 'video/mp4'
});
recorder.start();
stopBtn.removeAttribute('disabled');
startBtn.disabled = true;
}
function stopRecording() {
recorder.ondataavailable = e => {
ul.style.display = 'block';
var a = document.createElement('a'),
li = document.createElement('li');
a.download = ['video_', (new Date() + '').slice(4, 28), '.webm'].join('');
a.href = URL.createObjectURL(e.data);
a.textContent = a.download;
li.appendChild(a);
ul.appendChild(li);
};
recorder.stop();
startBtn.removeAttribute('disabled');
stopBtn.disabled = true;
}
_x000D_
<div>
<button id='request'>
Request Camera
</button>
<button id='start'>
Start Recording
</button>
<button id='stop'>
Stop Recording
</button>
<ul id='ul'>
Downloads List:
</ul>
</div>
<video id='video' autoplay></video>
_x000D_
System.out.println(Integer.toBinaryString(2 << 11));
Shifts binary 2(10
) by 11 times to the left. Hence: 1000000000000
System.out.println(Integer.toBinaryString(2 << 22));
Shifts binary 2(10
) by 22 times to the left. Hence : 100000000000000000000000
System.out.println(Integer.toBinaryString(2 << 33));
Now, int is of 4 bytes,hence 32 bits. So when you do shift by 33, it's equivalent to shift by 1. Hence : 100
Re-Ordering data Table based on some condition or check box checked. PFB :-
var tableResult= $('#exampleTable').DataTable();
var $tr = $(this).closest('tr');
if ($("#chkBoxId").prop("checked"))
{
// re-draw table shorting based on condition
tableResult.row($tr).invalidate().order([colindx, 'asc']).draw();
}
else {
tableResult.row($tr).invalidate().order([colindx, "asc"]).draw();
}
From python 3.x, the unified integer libries are even more smarter than older versions. On my (i7 Ubuntu) box I got the following,
>>> type(math.factorial(30))
<class 'int'>
For implementation details refer Include/longintrepr.h, Objects/longobject.c and Modules/mathmodule.c
files. The last file is a dynamic module (compiled to an so file). The code is well commented to follow.
Here is yet another way which fits in one line but is not particularly elegant:
dt = datetime.datetime.fromordinal(datetime.date.today().toordinal())
function fib(n) {
if (n <= 1) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
fib(10); // returns 55
Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:
The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:
<Reference Include="Filename, ..., processorArchitecture=x86">
<HintPath>C:\path\to\x86\DLL</HintPath>
</Reference>
Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<Reference ...>....</Reference>
</ItemGroup>
Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<Reference Include="Filename, ..., processorArchitecture=AMD64">
<HintPath>C:\path\to\x64\DLL</HintPath>
</Reference>
</ItemGroup>
After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.
Solving the MSI issue is up next, and unfortunately this will require a non-VS.NET tool: I prefer Caphyon's Advanced Installer for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well.
You can probably achieve the same results using other tools or the Windows Installer XML (WiX) toolset, but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.
One thing you may still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.
This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.
Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...
Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):
<ItemGroup Condition="'$(Platform)' == 'x86'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" />
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" />
</ItemGroup>
The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture.
The Google Play Store is now officially preinstalled the Android Emulator. Make sure you are running the latest version of Android Studio 2.4. In the Android Studio AVD Manager choose a virtual device configuration that has the Google Play store icon next to it, and then select one of the system images that have the label "Google Play". See this release note: https://androidstudio.googleblog.com/2017/04/android-studio-24-preview-4-is-now.html
If you are using Java 5/6, you can use Apache Commons IO for read file to string. The class org.apache.commons.io.FileUtils
contais several method for read files.
e.g. using the method FileUtils#readFileToString
:
File file = new File("abc.txt");
String content = FileUtils.readFileToString(file);
Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:
document.forms['yourform']['yourtextarea'].value = 'yourvalue';
where in the HTML your textarea is nested somewhere in a form like this:
<form name="yourform">
<textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>
And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.
SELECT *
FROM trees
WHERE trees.`title` COLLATE UTF8_GENERAL_CI LIKE '%elm%'
Actually, if you add COLLATE UTF8_GENERAL_CI
to your column's definition, you can just omit all these tricks: it will work automatically.
ALTER TABLE trees
MODIFY COLUMN title VARCHAR(…) CHARACTER
SET UTF8 COLLATE UTF8_GENERAL_CI.
This will also rebuild any indexes on this column so that they could be used for the queries without leading '%'
I was able to resolve this issue using this
@media (hover:none), (hover:on-demand) {
Your class or ID{
attributes
}
}
I'm outdated I know.. But a little workaround would be to put your checkbox inside a label tag, then style the label with a border:
<label class='hasborder'><input type='checkbox' /></label>
then style the label:
.hasborder { border:1px solid #F00; }
Some comments on your code
for(i='A';i<='Z';i++)
, if you can check this with a simple if
statement ... you loop over a whole range while you can simply check whether it is contained in that rangeA
you will have your result the first time you enter the first loop) you still loop over all the restSystem.out.println("Lowercase");
statement (and the uppercase statement) are placed in the wrong loopCharacter
class which has for example nice isUpperCase
and isLowerCase
methodsI leave the rest up to you since it is homework
spark-md5
and Q
Assuming your'e using a modern browser (that supports HTML5 File API), here's how you calculate the MD5 Hash of a large file (it will calculate the hash on variable chunks)
function calculateMD5Hash(file, bufferSize) {
var def = Q.defer();
var fileReader = new FileReader();
var fileSlicer = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var hashAlgorithm = new SparkMD5();
var totalParts = Math.ceil(file.size / bufferSize);
var currentPart = 0;
var startTime = new Date().getTime();
fileReader.onload = function(e) {
currentPart += 1;
def.notify({
currentPart: currentPart,
totalParts: totalParts
});
var buffer = e.target.result;
hashAlgorithm.appendBinary(buffer);
if (currentPart < totalParts) {
processNextPart();
return;
}
def.resolve({
hashResult: hashAlgorithm.end(),
duration: new Date().getTime() - startTime
});
};
fileReader.onerror = function(e) {
def.reject(e);
};
function processNextPart() {
var start = currentPart * bufferSize;
var end = Math.min(start + bufferSize, file.size);
fileReader.readAsBinaryString(fileSlicer.call(file, start, end));
}
processNextPart();
return def.promise;
}
function calculate() {
var input = document.getElementById('file');
if (!input.files.length) {
return;
}
var file = input.files[0];
var bufferSize = Math.pow(1024, 2) * 10; // 10MB
calculateMD5Hash(file, bufferSize).then(
function(result) {
// Success
console.log(result);
},
function(err) {
// There was an error,
},
function(progress) {
// We get notified of the progress as it is executed
console.log(progress.currentPart, 'of', progress.totalParts, 'Total bytes:', progress.currentPart * bufferSize, 'of', progress.totalParts * bufferSize);
});
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.4.1/q.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/2.0.2/spark-md5.min.js"></script>
<div>
<input type="file" id="file"/>
<input type="button" onclick="calculate();" value="Calculate" class="btn primary" />
</div>
_x000D_
Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems
Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:
For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:
<html> <head> <title>Test Page</title> </head> <body> <h2>Data Collection</h2><p> <form action="process.php" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" name="Name"/></td> </tr> <tr> <td>Age:</td> <td><input type="text" name="Age"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit"/> </td> </tr> </table> </form> </body> </html>
This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:
<?php
print "Your name is ". $Name;
print "<br />";
print "You are ". $Age . " years old";
print "<br />"; $old = 25 + $Age;
print "In 25 years you will be " . $old . " years old";
?>
As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.
Additional JavaScript Example
This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.
Note: document.getElementById("fname").value
gets the object with the ID
tag that equals fname
and then pulls it's value
- which in this case is the text in the First Name textbox.
<html>
<head>
<script type="text/javascript">
function ExampleJS(){
var jFirst = document.getElementById("fname").value;
var jLast = document.getElementById("lname").value;
alert("Your name is: " + jFirst + " " + jLast);
}
</script>
</head>
<body>
<FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">
First name: <input type="text" id="fname" name="firstname" /><br />
Last name: <input type="text" id="lname" name="lastname" /><br />
<input name="Submit" type="submit" value="Update" />
</FORM>
</body>
</html>
Inside Fragment
class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
// or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
Always remember in case of Fragment that onViewCreated()
method will not called automatically if you are returning null or super.onCreateView()
from onCreateView()
method.
It will be called by default in case of ListFragment
as ListFragment
return FrameLayout
by default.
Note: you can get the fragment view anywhere in the class by using getView()
once onCreateView()
has been executed successfully.
i.e.
getView().findViewById("your view id");
I don't know about php but i belive the problem is from this :
echo '<script language="javascript>';
echo 'alery("message successfully sent")';
echo '</script>';
Try to change this with :
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up
<a href="\\server\folder\path" target="_blank">click</a>
If there is a need in a fancy UI - then it will barely serve as a solution.
I present a fully worked example on how building a shared library
and using it under Python
by means of ctypes
. I consider the Windows
case and deal with DLLs
. Two steps are needed:
The shared library
I consider is the following and is contained in the testDLL.cpp
file. The only function testDLL
just receives an int
and prints it.
#include <stdio.h>
?
extern "C" {
?
__declspec(dllexport)
?
void testDLL(const int i) {
printf("%d\n", i);
}
?
} // extern "C"
To build a DLL
with Visual Studio
from the command line run
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsdevcmd"
to set the include path and then run
cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll
to build the DLL.
DLL
from the IDEAlternatively, the DLL
can be build using Visual Studio
as follows:
Under Python, do the following
import os
import sys
from ctypes import *
lib = cdll.LoadLibrary('testDLL.dll')
lib.testDLL(3)
The question doesn't seem to require a programmatic solution, but my Google search brought me here anyway. Here's my C# attempt at detecting where the SDK is installed, based on the most common installation paths.
static string FindAndroidSDKPath()
{
string uniqueFile = Path.Combine("platform-tools", "adb.exe"); // look for adb in Android folders
string[] searchDirs =
{
// User/AppData/Local
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
// Program Files
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
// Program Files (x86) (it's okay if we're on 32-bit, we check if this folder exists first)
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + " (x86)",
// User/AppData/Roaming
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
};
foreach (string searchDir in searchDirs)
{
string androidDir = Path.Combine(searchDir, "Android");
if (Directory.Exists(androidDir))
{
string[] subDirs = Directory.GetDirectories(androidDir, "*sdk*", SearchOption.TopDirectoryOnly);
foreach (string subDir in subDirs)
{
string path = Path.Combine(subDir, uniqueFile);
if (File.Exists(path))
{
// found unique file at DIR/Android
return subDir;
}
}
}
}
// no luck finding SDK! :(
return null;
}
I need this because I'm writing an extension to a C# program to work with Android Studio/Gradle. Hopefully someone else will find this approach useful.
You can do this without a for
statement ^.^:
@echo off
:SPINNER
SET COUNTP1=1
:1
CLS
:: YOUR COMMAND GOES HERE
IF !COUNTP1! EQU 200 goto 2
SET COUNTP1=1
) ELSE (
SET /A COUNTP1+=1
)
goto 1
:2
:: COMMAND HAS FINISHED RUNNING 200 TIMES
It has basic understanding. Just give it a test. :P
I found that this works really well in Chrome.
Right click on the element that you'd like to inspect, then click Force Element State > Hover. Screenshot attached.
In the current version of TortoiseHg Workbench 4.4.1 (07.2018) you can use Repository
- Rollback/undo...
:
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
You can use awk:
ls -l | awk 'NR==2'
The above code will not get what we want because of off-by-one error: the ls -l command's first line is the total line. For that, the following revised code will work:
ls -l | awk 'NR==3'
Use this code ,which helped me to open all types of files ...
private void openFile(File url) {
try {
Uri uri = Uri.fromFile(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if (url.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if (url.toString().contains(".zip")) {
// ZIP file
intent.setDataAndType(uri, "application/zip");
} else if (url.toString().contains(".rar")){
// RAR file
intent.setDataAndType(uri, "application/x-rar-compressed");
} else if (url.toString().contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if (url.toString().contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if (url.toString().contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") ||
url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
}
}
You may try this :
string s = "";
foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
well, for me it was different. I was missing assembly of my console application project with MVC project. So, adding reference was not enough.
well this might help someone else. go to root web.config file system.web
-> compilation
-> add your project reference like this.
<assemblies>
<add assembly="Your.Namespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</assemblies>
just try to push it to your branch again. This will ask your username and password again, so you can feed in the changed password. So that your new password will be stored again in the cache.
I use a JavaScript port of the Mersenne Twister: https://gist.github.com/300494 It allows you to set the seed manually. Also, as mentioned in other answers, the Mersenne Twister is a really good PRNG.
Yes. I also think that using read() with arguments like read(Char[], int init, int end) is a better way to read a such a large file (Eg : read(buffer,0,buffer.length))
And I also experienced the problem of missing values of using the BufferedReader instead of BufferedInputStreamReader for a binary data input stream. So, using the BufferedInputStreamReader is a much better in this like case.
It is definitely possible to use Javascript to change the meta tags of the page. Here is a Javascript only approach:
document.getElementsByTagName('meta')["keywords"].content = "My new page keywords!!";
document.getElementsByTagName('meta')["description"].content = "My new page description!!";
document.title = "My new Document Title!!";
I have verified that Google does index these client side changes for the code above.
<input [ngModel]="item.value | useMyPipeToFormatThatValue"
(ngModelChange)="item.value=$event" name="inputField" type="text" />
The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)]
actually encompasses. []
is one-way binding syntax and ()
is event binding syntax. When used together - [()]
Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.
The reason you cannot use [()]
with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.
See Angular Template Syntax for more info.
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.
There's a bit of confusion in your question:
Date
datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE
into a Date
.TO_CHAR
function. In Oracle, a Date
has no format: it is a point in time.TO_TIMESTAMP_TZ
to convert a VARCHAR2
to a TIMESTAMP
, but this won't convert a Date
to a TIMESTAMP
.FROM_TZ
to add the time zone information to a TIMESTAMP
(or a Date
).CST
is a time zone but CDT
is not. CDT
is a daylight saving information.CST/CDT
(-05:00
) and CST/CST
(-06:00
) will have different values obviously, but the time zone CST
will inherit the daylight saving information depending upon the date by default.So your conversion may not be as simple as it looks.
Assuming that you want to convert a Date
d
that you know is valid at time zone CST/CST
to the equivalent at time zone CST/CDT
, you would use:
SQL> SELECT from_tz(d, '-06:00') initial_ts,
2 from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
3 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
4 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
5 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00
My default timestamp format has been used here. I can specify a format explicitely:
SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
2 to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
3 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
4 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
5 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
6 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00 2012-10-09 02:10:21 -05:00
Prerequisites to execute this command -
pip (recursive acronym of Pip Installs Packages) is a package management system used to install and manage software packages written in Python. Many packages can be found in the Python Package Index (PyPI).
sudo apt-get install python-pip
Install Virtual Environment. Used to create virtual environment, to install packages and dependencies of multiple projects isolated from each other.
sudo pip install virtualenv
Install virtual environment wrapper About virtual env wrapper
sudo pip install virtualenvwrapper
After Installing prerequisites you need to bring virtual environment wrapper into action to create virtual environment. Following are the steps -
set virtual environment directory in path variable-
export WORKON_HOME=(directory you need to save envs)
source /usr/local/bin/virtualenvwrapper.sh -p $WORKON_HOME
As mentioned by @Mike, source `which virtualenvwrapper.sh` or which virtualenvwrapper.sh
can used to locate virtualenvwrapper.sh file.
It's best to put above two lines in ~/.bashrc to avoid executing the above commands every time you open new shell. That's all you need to create environment using mkvirtualenv
Points to keep in mind -
Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.
# make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))
# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)
# Make a vector of thresholds 'Brks' to colour code z
Brks <- c(seq(0,18,3),Inf)
# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')
# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")
# Make up lookup dataframe 'LkUp' of the lables and colours
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)
# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))
# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')
# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
Grd$Var2,
xlim = c(0,400),
ylim = c(0,400),
cex = 1.0,
col = Grd$Clrs,
pch = 20,
xlab = 'mX',
ylab = 'mY',
main = 'My Grid',
axes = FALSE,
labels = FALSE,
las = 1
)
axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')
legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')
-m
means the parent number.
From the git doc:
Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.
For example, if your commit tree is like below:
- A - D - E - F - master
\ /
B - C branch one
then git cherry-pick E
will produce the issue you faced.
git cherry-pick E -m 1
means using D-E
, while git cherry-pick E -m 2
means using B-C-E
.
Use a backslash:
echo "\"" # Prints one " character.
I found the following summary very useful: http://www.techrepublic.com/article/configure-vi-for-java-application-development/5054618. The description of :make was for ant not maven, but otherwise a nice summary.
default_keys = [1, "name"]
To get dictionary with None as values:
dict.fromkeys(default_keys)
Output :
{1: None, 'name': None}
To get dictionary with default values:
dict.fromkeys(default_keys, [])
Output :
{1: [], 'name': []}
I had this, but not sure if this is correct. Could try this out also.
mysql_query("START TRANSACTION");
$flag = true;
$query = "INSERT INTO testing (myid) VALUES ('test')";
$query2 = "INSERT INTO testing2 (myid2) VALUES ('test2')";
$result = mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}
$result = mysql_query($query2) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}
if ($flag) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
Idea from here: http://www.phpknowhow.com/mysql/transactions/
I guess your app crashes because of NullPointerException
.
Change this
ListView lv = (ListView)getActivity().findViewById(R.id.lv_contact);
to
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
assuming listview belongs to the fragment layout.
The rest of the code looks alright
Edit:
Well since you said it is not working i tried it myself
There's a note on top of the docs:
Note: The Google Web Search API has been officially deprecated as of November 1, 2010. It will continue to work as per our deprecation policy, but the number of requests you may make per day will be limited. Therefore, we encourage you to move to the new Custom Search API.
The deprecation policy says that they will continue to run the API for 3 years. So if you already have an application that uses the old API, you don't have to rush to change things just yet. If you're writing a new application, use the Custom Search API. See my answer here for how to do this in Python, but the idea's the same for any language.
We are seeing 404 errors in our logs when using //somedomain.com as references to JS files.
The references that cause the 404s come out looking like this: ref:
<script src="//somedomain.com/somescript.js" />
404 request:
http://mydomain.com//somedomain.com/somescript.js
With these showing up regularly in our web server logs, it is safe to say that: All browsers and Bots DO NOT honor RFC 3986 section 4.2. The safest bet is to include the protocol whenever possible.
This is my version, quite similar to the upper one, but I think good for reference.
if (mob_url == "") {
lt_url = desk_url;
} else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") {
lt_url = mob_url;
} else {
lt_url = desk_url;
}
Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.
I found the following worked for me in a user defined function I created. I concatenated the cell range reference and worksheet name as a string and then used in an Evaluate statement (I was using Evaluate on Sumproduct).
For example:
Function SumRange(RangeName as range)
Dim strCellRef, strSheetName, strRngName As String
strCellRef = RangeName.Address
strSheetName = RangeName.Worksheet.Name & "!"
strRngName = strSheetName & strCellRef
Then refer to strRngName in the rest of your code.
For example this simple Makefile should be sufficient:
CC=gcc CFLAGS=-Wall all: program program: program.o program.o: program.c program.h headers.h clean: rm -f program program.o run: program ./program
Note there must be <tab>
on the next line after clean and run, not spaces.
UPDATE Comments below applied
just put #login-box
before <h2>Welcome</h2>
will be ok.
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
here is jsfiddle http://jsfiddle.net/SyjjW/4/
In your comment in response to John, you suggest that you want the keys and values of the dictionary, not just the values.
PEP 256 suggests this for sorting a dictionary by values.
import operator
sorted(d.iteritems(), key=operator.itemgetter(1))
If you want descending order, do this
sorted(d.iteritems(), key=itemgetter(1), reverse=True)
... right now it happens only to the website I'm testing. I can't post it here because it's confidential.
Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use
--secure-protocol=TLSv1
. If this does not help check if you can access the site with openssl s_client -connect ...
(probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ...
.
Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.
The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.
Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?
The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.
Disabling and Enabling All Foreign Keys
CREATE PROCEDURE pr_Disable_Triggers_v2
@disable BIT = 1
AS
DECLARE @sql VARCHAR(500)
, @tableName VARCHAR(128)
, @tableSchema VARCHAR(128)
-- List of all tables
DECLARE triggerCursor CURSOR FOR
SELECT t.TABLE_NAME AS TableName
, t.TABLE_SCHEMA AS TableSchema
FROM INFORMATION_SCHEMA.TABLES t
ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA
OPEN triggerCursor
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
IF @disable = 1
SET @sql = @sql + ' DISABLE TRIGGER ALL'
ELSE
SET @sql = @sql + ' ENABLE TRIGGER ALL'
PRINT 'Executing Statement - ' + @sql
EXECUTE ( @sql )
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
END
CLOSE triggerCursor
DEALLOCATE triggerCursor
First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:
0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missingInside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.
It seems you are looking for the Post/Redirect/Get
pattern.
As another solution you may stop to use redirecting at all.
You may process and render the processing result at once with no POST
confirmation alert. You should just manipulate the browser history object:
history.replaceState("", "", "/the/result/page")
In ST2 there's a package you can install called Default FileType which does just that.
More info here.
This is how you do it. No, not really.
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
#define p_ntohl(u) ({const uint32_t Q=0xFF000000; \
uint32_t S=(uint32_t)(u); \
(*(uint8_t*)&Q)?S: \
( (S<<24)| \
((S<<8)&0x00FF0000)| \
((S>>8)&0x0000FF00)| \
((S>>24)&0xFF) ); })
main (void)
{
uint32_t s[0x40];
assert((unsigned char)1 == (unsigned char)(257));
memset(s, 0, sizeof(s));
fgets((char*)s, sizeof(s), stdin);
switch (p_ntohl(s[0])) {
case 'open':
case 'read':
case 'seek':
puts("ok");
break;
case 'rm\n\0':
puts("not authorized");
break;
default:
puts("unrecognized command");
}
return 0;
}
here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).
<html>
<head>
<title>An example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function call_counter(url, pk) {
window.open(url);
$.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
alert("counter updated!");
});
}
</script>
</head>
<body>
<button onclick="call_counter('http://www.google.com', 12345);">
I update object 12345
</button>
<button onclick="call_counter('http://www.yahoo.com', 999);">
I update object 999
</button>
</body>
</html>
Alternative approach
Instead of placing the JavaScript code, you can change your link in this way:
<a target="_blank"
class="btn btn-info pull-right"
href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
Check It Out
</a>
and in your views.py
:
def YOUR_VIEW_DEF(request, pk):
YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
return HttpResponseRedirect(request.GET.get('next')))
You can also add linker flags to a specific target using the LINK_FLAGS
property:
set_property(TARGET ${target} APPEND_STRING PROPERTY LINK_FLAGS " ${flag}")
If you want to propagate this change to other targets, you can create a dummy target to link to.
For application-wide settings and for global constants I recommend to use Settingslogic. This settings are stored in YML file and can be accessed from models, views and controllers. Furthermore, you can create different settings for all your environments:
# app/config/application.yml
defaults: &defaults
cool:
sweet: nested settings
neat_setting: 24
awesome_setting: <%= "Did you know 5 + 5 = #{5 + 5}?" %>
colors: "white blue black red green"
development:
<<: *defaults
neat_setting: 800
test:
<<: *defaults
production:
<<: *defaults
Somewhere in the view (I prefer helper methods for such kind of stuff) or in a model you can get, for ex., array of colors Settings.colors.split(/\s/)
. It's very flexible. And you don't need to invent a bike.