I had this problem, and the cause was rather silly. I was trying out Microsoft's demo regarding running a ServiceHost from w/in a Command Line executable. I followed the instructions, including where it says to add the appropriate Service (and interface). But I got the above error.
Turns out when I added the service class, VS automatically added the configuration to the app.config. And the demo was trying to add that info too. Since it was already in the config, I removed the demo part, and it worked.
Your Javascript should be
<script>
$("#intro").owlCarousel({
// Most important owl features
//Autoplay
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: true
)}
</script>
Unfortunately, the answer to your question of whether there is official Material support for selecting the time is "No", but it's currently an open issue on the official Material2 GitHub repo: https://github.com/angular/material2/issues/5648
Hopefully this changes soon, in the mean time, you'll have to fight with the 3rd-party ones you've already discovered. There are a few people in that GitHub issue that provide their self-made workarounds that you can try.
application/xml
is seen by svn
as binary type whereas text/xml
as text file for which a diff can be displayed.
As pointed out by fyrye, the accepted answer pertains to older versions of MySQL in which ONLY_FULL_GROUP_BY
had not yet been introduced. With MySQL 8.0.17 (used in this example), unless you disable ONLY_FULL_GROUP_BY
you would get the following error message:
mysql> SELECT id, firstName, lastName FROM table_name GROUP BY firstName;
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'mydatabase.table_name.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
One way to work around this not mentioned by fyrye, but described in https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html, is to apply the ANY_VALUE()
function to the columns which are not in the GROUP BY
clause (id
and lastName
in this example):
mysql> SELECT ANY_VALUE(id) as id, firstName, ANY_VALUE(lastName) as lastName FROM table_name GROUP BY firstName;
+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
| 1 | John | Doe |
| 2 | Bugs | Bunny |
+----+-----------+----------+
2 rows in set (0.01 sec)
As written in the aforementioned docs,
In this case, MySQL ignores the nondeterminism of address values within each name group and accepts the query. This may be useful if you simply do not care which value of a nonaggregated column is chosen for each group.
ANY_VALUE()
is not an aggregate function, unlike functions such asSUM()
orCOUNT()
. It simply acts to suppress the test for nondeterminism.
Cross Browser jQuery Solution! Raw available at GitHub
The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:
Use is as simple as: Scroll Down to 'Run Snippet'
$.winFocus(function(event, isVisible) {
console.log("Combo\t\t", event, isVisible);
});
// OR Pass False boolean, and it will not trigger on load,
// Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
console.log("Combo\t\t", event, isVisible);
}, false);
// OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
// (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
blur: function(event) {
console.log("Blur\t\t", event);
},
focus: function(event) {
console.log("Focus\t\t", event);
}
});
// OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
console.log("Blur\t\t", event);
},
function(event) {
console.log("Focus\t\t", event);
});
/* Begin Plugin */_x000D_
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):_x000D_
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=_x000D_
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],_x000D_
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:_x000D_
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);_x000D_
/* End Plugin */_x000D_
_x000D_
// Simple example_x000D_
$(function() {_x000D_
$.winFocus(function(event, isVisible) {_x000D_
$('td tbody').empty();_x000D_
$.each(event, function(i) {_x000D_
$('td tbody').append(_x000D_
$('<tr />').append(_x000D_
$('<th />', { text: i }),_x000D_
$('<td />', { text: this.toString() })_x000D_
)_x000D_
)_x000D_
});_x000D_
if (isVisible) _x000D_
$("#isVisible").stop().delay(100).fadeOut('fast', function(e) {_x000D_
$('body').addClass('visible');_x000D_
$(this).stop().text('TRUE').fadeIn('slow');_x000D_
});_x000D_
else {_x000D_
$('body').removeClass('visible');_x000D_
$("#isVisible").text('FALSE');_x000D_
}_x000D_
});_x000D_
})
_x000D_
body { background: #AAF; }_x000D_
table { width: 100%; }_x000D_
table table { border-collapse: collapse; margin: 0 auto; width: auto; }_x000D_
tbody > tr > th { text-align: right; }_x000D_
td { width: 50%; }_x000D_
th, td { padding: .1em .5em; }_x000D_
td th, td td { border: 1px solid; }_x000D_
.visible { background: #FFA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>See Console for Event Object Returned</h3>_x000D_
<table>_x000D_
<tr>_x000D_
<th><p>Is Visible?</p></th>_x000D_
<td><p id="isVisible">TRUE</p></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody></tbody>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
For Ubuntu i use this:
(exec PROG_SH &> /dev/null &)
regards
Open a Terminal window and navigate to your project directory. Run these sets of commands, depending on which compiler you have installed:
To compile multiple C++ files using clang++:
$ clang++ *.cpp
$ ./a.out
To compile multiple C++ files using g++:
$ g++ -c *.cpp
$ g++ -o temp.exe *.o
$ ./temp.exe
Check "Getting a list of all subdirectories in the current directory".
Here's a Python 3 version:
import os
dir_list = next(os.walk('.'))[1]
print(dir_list)
In javascript you can call a function (even if it has parameters) without parameters.
So you can add default values like this:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
//your code
}
and then you can call it like func();
to use default parameters.
Here's a test:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);
I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open
and hoping that the user has their browser set to open new windows in new tabs.
this problem arises when we use vectors in place of scalars for example in a for loop the range should be a scalar, in case you have given a vector in that place you get error. So to avoid the problem use the length of the vector you have used
I simplify the code a little bit.
from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
Just entering a single space for the Back button navigation item works!!
Try modifying the path in the windows registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment).
Caveat: Don't break the registry :)
The concatenation operator +
is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append()
method is a mutator
on list
which appends its single object
argument (in your specific example the list c
) to the subject list
. In your example this results in c
appending a reference to itself (hence the infinite recursion).
The list.extend()
method is also a mutator method which concatenates its sequence
argument with the subject list
. Specifically, it appends each of the elements of sequence
in iteration order.
Being an operator, +
returns the result of the expression as a new value. Being a non-chaining mutator
method, list.extend()
modifies the subject list in-place and returns nothing.
I've added this due to the potential confusion which the Abel's answer above may cause by mixing the discussion of lists, sequences and arrays.
Arrays
were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types. Do not confuse arrays
with lists
. They are not the same.
From the array docs:
Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character.
Since I realized that (the very excellent) answers of this post lack of by
and aggregate
explanations. Here is my contribution.
The by
function, as stated in the documentation can be though, as a "wrapper" for tapply
. The power of by
arises when we want to compute a task that tapply
can't handle. One example is this code:
ct <- tapply(iris$Sepal.Width , iris$Species , summary )
cb <- by(iris$Sepal.Width , iris$Species , summary )
cb
iris$Species: setosa
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.300 3.200 3.400 3.428 3.675 4.400
--------------------------------------------------------------
iris$Species: versicolor
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.000 2.525 2.800 2.770 3.000 3.400
--------------------------------------------------------------
iris$Species: virginica
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.200 2.800 3.000 2.974 3.175 3.800
ct
$setosa
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.300 3.200 3.400 3.428 3.675 4.400
$versicolor
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.000 2.525 2.800 2.770 3.000 3.400
$virginica
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.200 2.800 3.000 2.974 3.175 3.800
If we print these two objects, ct
and cb
, we "essentially" have the same results and the only differences are in how they are shown and the different class
attributes, respectively by
for cb
and array
for ct
.
As I've said, the power of by
arises when we can't use tapply
; the following code is one example:
tapply(iris, iris$Species, summary )
Error in tapply(iris, iris$Species, summary) :
arguments must have same length
R says that arguments must have the same lengths, say "we want to calculate the summary
of all variable in iris
along the factor Species
": but R just can't do that because it does not know how to handle.
With the by
function R dispatch a specific method for data frame
class and then let the summary
function works even if the length of the first argument (and the type too) are different.
bywork <- by(iris, iris$Species, summary )
bywork
iris$Species: setosa
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. :4.300 Min. :2.300 Min. :1.000 Min. :0.100 setosa :50
1st Qu.:4.800 1st Qu.:3.200 1st Qu.:1.400 1st Qu.:0.200 versicolor: 0
Median :5.000 Median :3.400 Median :1.500 Median :0.200 virginica : 0
Mean :5.006 Mean :3.428 Mean :1.462 Mean :0.246
3rd Qu.:5.200 3rd Qu.:3.675 3rd Qu.:1.575 3rd Qu.:0.300
Max. :5.800 Max. :4.400 Max. :1.900 Max. :0.600
--------------------------------------------------------------
iris$Species: versicolor
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. :4.900 Min. :2.000 Min. :3.00 Min. :1.000 setosa : 0
1st Qu.:5.600 1st Qu.:2.525 1st Qu.:4.00 1st Qu.:1.200 versicolor:50
Median :5.900 Median :2.800 Median :4.35 Median :1.300 virginica : 0
Mean :5.936 Mean :2.770 Mean :4.26 Mean :1.326
3rd Qu.:6.300 3rd Qu.:3.000 3rd Qu.:4.60 3rd Qu.:1.500
Max. :7.000 Max. :3.400 Max. :5.10 Max. :1.800
--------------------------------------------------------------
iris$Species: virginica
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. :4.900 Min. :2.200 Min. :4.500 Min. :1.400 setosa : 0
1st Qu.:6.225 1st Qu.:2.800 1st Qu.:5.100 1st Qu.:1.800 versicolor: 0
Median :6.500 Median :3.000 Median :5.550 Median :2.000 virginica :50
Mean :6.588 Mean :2.974 Mean :5.552 Mean :2.026
3rd Qu.:6.900 3rd Qu.:3.175 3rd Qu.:5.875 3rd Qu.:2.300
Max. :7.900 Max. :3.800 Max. :6.900 Max. :2.500
it works indeed and the result is very surprising. It is an object of class by
that along Species
(say, for each of them) computes the summary
of each variable.
Note that if the first argument is a data frame
, the dispatched function must have a method for that class of objects. For example is we use this code with the mean
function we will have this code that has no sense at all:
by(iris, iris$Species, mean)
iris$Species: setosa
[1] NA
-------------------------------------------
iris$Species: versicolor
[1] NA
-------------------------------------------
iris$Species: virginica
[1] NA
Warning messages:
1: In mean.default(data[x, , drop = FALSE], ...) :
argument is not numeric or logical: returning NA
2: In mean.default(data[x, , drop = FALSE], ...) :
argument is not numeric or logical: returning NA
3: In mean.default(data[x, , drop = FALSE], ...) :
argument is not numeric or logical: returning NA
aggregate
can be seen as another a different way of use tapply
if we use it in such a way.
at <- tapply(iris$Sepal.Length , iris$Species , mean)
ag <- aggregate(iris$Sepal.Length , list(iris$Species), mean)
at
setosa versicolor virginica
5.006 5.936 6.588
ag
Group.1 x
1 setosa 5.006
2 versicolor 5.936
3 virginica 6.588
The two immediate differences are that the second argument of aggregate
must be a list while tapply
can (not mandatory) be a list and that the output of aggregate
is a data frame while the one of tapply
is an array
.
The power of aggregate
is that it can handle easily subsets of the data with subset
argument and that it has methods for ts
objects and formula
as well.
These elements make aggregate
easier to work with that tapply
in some situations.
Here are some examples (available in documentation):
ag <- aggregate(len ~ ., data = ToothGrowth, mean)
ag
supp dose len
1 OJ 0.5 13.23
2 VC 0.5 7.98
3 OJ 1.0 22.70
4 VC 1.0 16.77
5 OJ 2.0 26.06
6 VC 2.0 26.14
We can achieve the same with tapply
but the syntax is slightly harder and the output (in some circumstances) less readable:
att <- tapply(ToothGrowth$len, list(ToothGrowth$dose, ToothGrowth$supp), mean)
att
OJ VC
0.5 13.23 7.98
1 22.70 16.77
2 26.06 26.14
There are other times when we can't use by
or tapply
and we have to use aggregate
.
ag1 <- aggregate(cbind(Ozone, Temp) ~ Month, data = airquality, mean)
ag1
Month Ozone Temp
1 5 23.61538 66.73077
2 6 29.44444 78.22222
3 7 59.11538 83.88462
4 8 59.96154 83.96154
5 9 31.44828 76.89655
We cannot obtain the previous result with tapply
in one call but we have to calculate the mean along Month
for each elements and then combine them (also note that we have to call the na.rm = TRUE
, because the formula
methods of the aggregate
function has by default the na.action = na.omit
):
ta1 <- tapply(airquality$Ozone, airquality$Month, mean, na.rm = TRUE)
ta2 <- tapply(airquality$Temp, airquality$Month, mean, na.rm = TRUE)
cbind(ta1, ta2)
ta1 ta2
5 23.61538 65.54839
6 29.44444 79.10000
7 59.11538 83.90323
8 59.96154 83.96774
9 31.44828 76.90000
while with by
we just can't achieve that in fact the following function call returns an error (but most likely it is related to the supplied function, mean
):
by(airquality[c("Ozone", "Temp")], airquality$Month, mean, na.rm = TRUE)
Other times the results are the same and the differences are just in the class (and then how it is shown/printed and not only -- example, how to subset it) object:
byagg <- by(airquality[c("Ozone", "Temp")], airquality$Month, summary)
aggagg <- aggregate(cbind(Ozone, Temp) ~ Month, data = airquality, summary)
The previous code achieve the same goal and results, at some points what tool to use is just a matter of personal tastes and needs; the previous two objects have very different needs in terms of subsetting.
for current year we can use getFullYear() from Date class however there are many function which you can use as per the requirements, some functions are as,
var now = new Date()_x000D_
console.log("Current Time is: " + now);_x000D_
_x000D_
// getFullYear function will give current year _x000D_
var currentYear = now.getFullYear()_x000D_
console.log("Current year is: " + currentYear);_x000D_
_x000D_
// getYear will give you the years after 1990 i.e currentYear-1990_x000D_
var year = now.getYear()_x000D_
console.log("Current year is: " + year);_x000D_
_x000D_
// getMonth gives the month value but months starts from 0_x000D_
// add 1 to get actual month value _x000D_
var month = now.getMonth() + 1_x000D_
console.log("Current month is: " + month);_x000D_
_x000D_
// getDate gives the date value_x000D_
var day = now.getDate()_x000D_
console.log("Today's day is: " + day);
_x000D_
If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:
---- foo_proxy.py ----
tmp = __import__('foo-bar')
globals().update(vars(tmp))
---- main.py ----
from foo_proxy import *
The same, Server.UrlEncode()
calls HttpUtility.UrlEncode()
I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>
You can use time
and subshell ()
:
time (
for (( i=1; i<10000; i++ )); do
echo 1 >/dev/null
done
)
Or in same shell {}
:
time {
for (( i=1; i<10000; i++ )); do
echo 1 >/dev/null
done
}
This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"
strProcess = "EXCEL.EXE"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Wscript.Sleep(1000) 'Sleep 1 second
'msgbox colProcesses.count 'optional to show the loop works
Loop
Credit to: http://crimsonshift.com/scripting-check-if-process-or-program-is-running-and-start-it/
ManagementFactory.getThreadMXBean().getThreadCount()
doesn't limit itself to thread groups as Thread.activeCount()
does.
Prior to version 1.14, wget timeout arguments were not adhered to if downloading over https due to a bug.
Install yarn an then run
yarn global add install-peerdeps
Check if your commits have Change-Id: ...
in their descriptions. Every commit should have them.
If no, use git rebase -i
to reword the commit messages and add proper Change-Ids (usually this is a SHA1 of the first version of the reviewed commit).
For the future, you should install commit hook, which automatically adds the required Change-Id.
Execute scp -p -P 29418 username@your_gerrit_address:hooks/commit-msg .git/hooks/
in the repository directory
or download them from
http://your_gerrit_address/tools/hooks/commit-msg
and copy to .git/hooks
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Use this:
print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
sum += number
print("Total Sum is: %d" %sum )
Try to run xcrun simctl delete unavailable
in your terminal.
Original answer: Xcode - free to clear devices folder?
I got this working by installing the various plugins below.
Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.
Screenshot of Extensions
This is what has to occur.
You have to copy your DLL that you want to Register to: c:\windows\SysWOW64\
Then in the Run dialog, type this in:
C:\Windows\SysWOW64\regsvr32.exe c:\windows\system32\YourDLL.dll
and you will get the message:
DllRegisterServer in c:\windows\system32\YourDLL.dll succeeded.
Here is an easy way to create a "2D" array.
2.1.1 :004 > m=Array.new(3,Array.new(3,true))
=> [[true, true, true], [true, true, true], [true, true, true]]
Blimey. This was a really useful thread to discover.
I still found some of these suggestions confusing. Whenever I used value
with [1]
in the string, it would only retrieved the first value. And some suggestions recommended using cross apply
which (in my tests) just brought back far too much data.
So, here's my simple example of how you'd create an xml
object, then read out its values into a table.
DECLARE @str nvarchar(2000)
SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Mike</firstName>'
SET @str = @str + ' <lastName>Gledhill</lastName>'
SET @str = @str + ' <age>31</age>'
SET @str = @str + ' </user>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Mark</firstName>'
SET @str = @str + ' <lastName>Stevens</lastName>'
SET @str = @str + ' <age>42</age>'
SET @str = @str + ' </user>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Sarah</firstName>'
SET @str = @str + ' <lastName>Brown</lastName>'
SET @str = @str + ' <age>23</age>'
SET @str = @str + ' </user>'
SET @str = @str + '</users>'
DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML)
-- Iterate through each of the "users\user" records in our XML
SELECT
x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)
And here's the output:
It's bizarre syntax, but with a decent example, it's easy enough to add to your own SQL Server functions.
Speaking of which, here's the correct answer to this question.
Assuming your have your xml data in an @xml
variable of type xml
(as demonstrated in my example above), here's how you would return the three rows of data from the xml quoted in the question:
SELECT
x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName'
FROM @xml.nodes('/person') as x(Rec)
git remote prune
and git fetch --prune
do the same thing: deleting the refs to the branches that don't exist on the remote, as you said. The second command connects to the remote and fetches its current branches before pruning.
However it doesn't touch the local branches you have checked out, that you can simply delete with
git branch -d random_branch_I_want_deleted
Replace -d
by -D
if the branch is not merged elsewhere
git prune
does something different, it purges unreachable objects, those commits that aren't reachable in any branch or tag, and thus not needed anymore.
fyi <form>
supports :before
/ :after
as well, might be of help if you wrap your <input>
element with it... (got myself a design issue with that too)
Working with POST in webapi can be tricky! Would like to add to the already correct answer..
Will focus specifically on POST as dealing with GET is trivial. I don't think many would be searching around for resolving an issue with GET with webapis. Anyways..
If your question is - In MVC Web Api, how to- - Use custom action method names other than the generic HTTP verbs? - Perform multiple posts? - Post multiple simple types? - Post complex types via jQuery?
Then the following solutions may help:
First, to use Custom Action Methods in Web API, add a web api route as:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}");
}
And then you may create action methods like:
[HttpPost]
public string TestMethod([FromBody]string value)
{
return "Hello from http post web api controller: " + value;
}
Now, fire the following jQuery from your browser console
$.ajax({
type: 'POST',
url: 'http://localhost:33649/api/TestApi/TestMethod',
data: {'':'hello'},
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function(data){ console.log(data) }
});
Second, to perform multiple posts, It is simple, create multiple action methods and decorate with the [HttpPost] attrib. Use the [ActionName("MyAction")] to assign custom names, etc. Will come to jQuery in the fourth point below
Third, First of all, posting multiple SIMPLE types in a single action is not possible. Moreover, there is a special format to post even a single simple type (apart from passing the parameter in the query string or REST style). This was the point that had me banging my head with Rest Clients (like Fiddler and Chrome's Advanced REST client extension) and hunting around the web for almost 5 hours when eventually, the following URL proved to be of help. Will quote the relevant content for the link might turn dead!
Content-Type: application/x-www-form-urlencoded
in the request header and add a = before the JSON statement:
={"Name":"Turbo Tina","Email":"[email protected]"}
PS: Noticed the peculiar syntax?
http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api
Anyways, let us get over that story. Moving on:
Fourth, posting complex types via jQuery, ofcourse, $.ajax() is going to promptly come in the role:
Let us say the action method accepts a Person object which has an id and a name. So, from javascript:
var person = { PersonId:1, Name:"James" }
$.ajax({
type: 'POST',
url: 'http://mydomain/api/TestApi/TestMethod',
data: JSON.stringify(person),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data){ console.log(data) }
});
And the action will look like:
[HttpPost]
public string TestMethod(Person person)
{
return "Hello from http post web api controller: " + person.Name;
}
All of the above, worked for me!! Cheers!
That doesn't work because distToPoint
is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p)
. You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p)
.
using Microsoft.Office.Interop.Excel;
string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;
//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();
wb.Close();
This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.
For a clear understanding, please take a look at my codepen implementations https://codepen.io/serdarsenay/pen/XELWqN
Biggest difference is the need to sort your sample before applying binary search, therefore for most "normal sized" (meaning to be argued) samples will be quicker to search with a linear search algorithm.
Here is the javascript code, for html and css and full running example please refer to above codepen link.
var unsortedhaystack = [];
var haystack = [];
function init() {
unsortedhaystack = document.getElementById("haystack").value.split(' ');
}
function sortHaystack() {
var t = timer('sort benchmark');
haystack = unsortedhaystack.sort();
t.stop();
}
var timer = function(name) {
var start = new Date();
return {
stop: function() {
var end = new Date();
var time = end.getTime() - start.getTime();
console.log('Timer:', name, 'finished in', time, 'ms');
}
}
};
function lineerSearch() {
init();
var t = timer('lineerSearch benchmark');
var input = this.event.target.value;
for(var i = 0;i<unsortedhaystack.length - 1;i++) {
if (unsortedhaystack[i] === input) {
document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return unsortedhaystack[i];
}
}
}
function binarySearch () {
init();
sortHaystack();
var t = timer('binarySearch benchmark');
var firstIndex = 0;
var lastIndex = haystack.length-1;
var input = this.event.target.value;
//currently point in the half of the array
var currentIndex = (haystack.length-1)/2 | 0;
var iterations = 0;
while (firstIndex <= lastIndex) {
currentIndex = (firstIndex + lastIndex)/2 | 0;
iterations++;
if (haystack[currentIndex] < input) {
firstIndex = currentIndex + 1;
//console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
} else if (haystack[currentIndex] > input) {
lastIndex = currentIndex - 1;
//console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
} else {
document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return true;
}
}
}
Looks like problem is based on a server side.
Im my case I worked with paypal server and neither of suggested answers helped, but http://forums.iis.net/t/1217360.aspx?HTTP+403+Forbidden+error
I was facing this issue and just got the reply from Paypal technical. Add this will fix the 403 issue.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "[any words that is more than 5 characters]";
I have successfully implemented simple code for Multiple permission at Once. Follow the below steps 1:Make Utility.java class like below
public class Utility {
public static final int MY_PERMISSIONS_REQUEST = 123;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permission)) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST);
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST);
}
return false;
}
}
}
return true;
}
}
2: Now call
boolean permissionCheck = Utility.checkPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.GET_ACCOUNTS);
in your Activity onCreate() or according to your logic.
3:Now check permission before performing operation for particular task
if (permissionCheck) {
performTaskOperation();//this method what you need to perform
} else {
Toast.makeText(this, "Need permission ON.", Toast.LENGTH_SHORT).show();
}
4: Now implement onRequestPermissionsResult() method in your Activity as below
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("STORAGE"))
performTaskOperation();//this method what you need to perform
}
break;
}
}
You are missing PIL (Python Image Library and Imaging package). To install PIL I used
pip install pillow
For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source. http://effbot.org/downloads/Imaging-1.1.6.tar.gz and cd into Download directory. Then run these:
$ gunzip Imaging-1.1.6.tar.gz
$ tar xvf Imaging-1.1.6.tar
$ cd Imaging-1.1.6
$ python setup.py install
Or if you have PIP installed in your Mac
pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz
then you can use:
from PIL import Image
in your python code.
When compiling memcached under Centos 5.x i got the same problem.
The solution is to upgrade gcc and g++ to version 4.4 at least.
Make sure your CC/CXX is set (exported) to right binaries before compiling.
You can use this func:
func randomString(length int) string {
b := make([]byte, length)
rand.Read(b)
return fmt.Sprintf("%x", b)[:length]
}
Check it out in the playground
The urls are different.
http://localhost/AccountSvc/DataInquiry.asmx
vs.
/acctinqsvc/portfolioinquiry.asmx
Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.
You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx
, and specify the desired method/operation in the SOAPAction header.
The SOAPAction header values are different.
http://localhost/AccountSvc/DataInquiry.asmx/ + methodName
vs.
http://tempuri.org/GetMyName
You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl
There should be a <soap:operation>
tag underneath the <wsdl:operation>
tag that matches the operation you are attempting to execute, which appears to be GetMyName
.
There is no XML declaration in the request body that includes your SOAP XML.
You specify text/xml
in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii
, but there's no telling if you aren't specifying them!
The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8
Hope that helps!
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
CommonJS is more than that - it's a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.
AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.
AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side. However, you can use either module spec in either environment - for example, RequireJS offers directions for running in Node.js and browserify is a CommonJS Module implementation that can run in the browser.
MacPorts will install ant for you in MacOSX 10.9. Just use
$ sudo port install apache-ant
and it will install.
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
0 will get printed.
As in C++ true refers to 1 and false refers to 0.
In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.
When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
#include <iostream>
int main()
{
std::cout << std::boolalpha << false << std::endl;
}
output:
false
If you are in a network of users, then the username will be different:
Environment.UserName
Will Display format : 'Username', rather than
System.Security.Principal.WindowsIdentity.GetCurrent().Name
Will Display format : 'NetworkName\Username'
Choose the format you want.
var searchArray = function(arr, str){
// If there are no items in the array, return an empty array
if(typeof arr === 'undefined' || arr.length === 0) return [];
// If the string is empty return all items in the array
if(typeof str === 'undefined' || str.length === 0) return arr;
// Create a new array to hold the results.
var res = [];
// Check where the start (*) is in the string
var starIndex = str.indexOf('*');
// If the star is the first character...
if(starIndex === 0) {
// Get the string without the star.
str = str.substr(1);
for(var i = 0; i < arr.length; i++) {
// Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
// It doesn't necessarily mean it IS a string either.
if(!arr[i].indexOf) continue;
// Check if the string is at the end of each item.
if(arr[i].indexOf(str) === arr[i].length - str.length) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// Otherwise, if the star is the last character
else if(starIndex === str.length - 1) {
// Get the string without the star.
str = str.substr(0, str.length - 1);
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is at the beginning of each item
if(arr[i].indexOf(str) === 0) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// In any other case...
else {
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is anywhere in each item
if(arr[i].indexOf(str) !== -1) {
// If it is, add the item to the results
res.push(arr[i]);
}
}
}
// Return the results as a new array.
return res;
}
var birds = ['bird1','somebird','bird5','bird-big','abird-song'];
var res = searchArray(birds, 'bird*');
// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song
There is an long list of caveats to a method like this, and a long list of 'what ifs' that are not taken into account, some of which are mentioned in other answers. But for a simple use of star syntax this may be a good starting point.
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55
Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator
const designated = "1 jan 2021"
function countdown(designated_time){
const currentTime = new Date();
const future_time = new Date(designated_time);
console.log(future_time - currentTime);
}
countdown(designated);
setInterval(countdown, 1000, designated);
There are so many ways you can do this, me personally things this is clean and sweet.
You can use HAVING clause for filter calculated in SELECT fields and aliases
According to the jQuery documentation of select()
:
Trigger the select event of each matched element. This causes all of the functions that have been bound to that select event to be executed, and calls the browser's default select action on the matching element(s).
There is your explanation why the jQuery select()
won't work in this case.
-------------------------------------------------------------------------------
-- Author name
-- Created date
-- Purpose description of the business/technical purpose
-- using multiple lines as needed
-- Copyright © yyyy, Company Name, All Rights Reserved
-------------------------------------------------------------------------------
-- Modification History
--
-- 01/01/0000 developer full name
-- A comprehensive description of the changes. The description may use as
-- many lines as needed.
-------------------------------------------------------------------------------
Setters and getters in Swift apply to computed properties/variables. These properties/variables are not actually stored in memory, but rather computed based on the value of stored properties/variables.
See Apple's Swift documentation on the subject: Swift Variable Declarations.
You can loop over each row of the DataTable
and check the value.
I'm a big fan of using a foreach loop when using IEnumerable
s. Makes it very simple and clean to look at or process each row
DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
if (dr["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
}
Alternatively you can use a PrimaryKey
for your DataTable
. This helps in various ways, but you often need to define one before you can use it.
An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx
DataTable workTable = new DataTable("Customers");
// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };
Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.
Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx
DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
Finally, you can use the Select() method to find data within a DataTable
also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.
String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);
foreach (DataRow dr in drFound)
{
// do you deed. Each record here was already found to match your criteria
}
This only started happening to me today (May 2017) and no answers in this thread solved my issue. The resolution for me was from here;
https://forums.developer.apple.com/thread/76803
Open Terminal
. Change to home directory,
cd ~
Move the current transporter directory,
mv .itmstransporter/ .old_itmstransporter/
Invoke the following file to let Transporter update itself.
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"
Wait till it updates, then open Xcode and attempt upload.
After using the wrong quotation mark characters in install.packages()
, correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.
You can just use:
> names(LIST)
[1] "A" "B"
Obviously the names of the first element is just
> names(LIST)[1]
[1] "A"
If its a get request use, $_GET['subject']
or if its a post request use, $_POST['subject']
To me it seems like the best solution is to use a directive; there's no need for the controller to know that the view is being updated.
Javascript:
var app = angular.module('app', ['directives']);
angular.module('directives', []).directive('toggleClass', function () {
var directiveDefinitionObject = {
restrict: 'A',
template: '<span ng-click="localFunction()" ng-class="selected" ng-transclude></span>',
replace: true,
scope: {
model: '='
},
transclude: true,
link: function (scope, element, attrs) {
scope.localFunction = function () {
scope.model.value = scope.$id;
};
scope.$watch('model.value', function () {
// Is this set to my scope?
if (scope.model.value === scope.$id) {
scope.selected = "active";
} else {
// nope
scope.selected = '';
}
});
}
};
return directiveDefinitionObject;
});
HTML:
<div ng-app="app" ng-init="model = { value: 'dsf'}"> <span>Click a span... then click another</span>
<br/>
<br/>
<span toggle-class model="model">span1</span>
<br/><span toggle-class model="model">span2</span>
<br/><span toggle-class model="model">span3</span>
CSS:
.active {
color:red;
}
I have a fiddle that demonstrates. The idea is when a directive is clicked, a function is called on the directive that sets a variable to the current scope id. Then each directive also watches the same value. If the scope ID's match, then the current element is set to be active using ng-class.
The reason to use directives, is that you no longer are dependent on a controller. In fact I don't have a controller at all (I do define a variable in the view named "model"). You can then reuse this directive anywhere in your project, not just on one controller.
Put novalidate="novalidate"
on <form>
tag.
<form novalidate="novalidate">
...
</form>
In XHTML, attribute minimization is forbidden, and the novalidate attribute must be defined as
<form novalidate="novalidate">
.
A little known (and little documented) fact about MATLAB's system()
function: On unixoid systems it uses whatever interpreter is given in the environment variable SHELL
or MATLAB_SHELL
at the time of starting MATLAB. So if you start MATLAB with
SHELL='/usr/bin/python' matlab
any subsequent system()
calls will use Python instead of your default shell as an interpreter.
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
That cannot be done in excel 2007. The list must be in the same sheet as your data. It might work in later versions though.
You need to dynamically allocate your matrix. For instance:
int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));
This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.
Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix
or rsuffix
keyword like so:
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
This way, the columns have distinct names. The documentation addresses this very problem.
Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe
are redundant to the stars in restaurant_review_frame
, you could del restaurant_ids_dataframe['stars']
.
Another answer to the OP's exact question is to set the consumes
content type to "text/plain"
and then declare a @RequestBody String
input parameter. This will pass the text of the POST data in as the declared String
variable (postPayload
in the following example).
Of course, this presumes your POST payload is text data (as the OP stated was the case).
Example:
@RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
public ModelAndView someMethod(@RequestBody String postPayload) {
// ...
}
Use:
dqote='"'
sqote="'"
Use the '+' operator and dqote
and squote
variables to get what you need.
If I want sed -e s/",u'"/",'"/g -e s/^"u'"/"'"/
, you can try the following:
dqote='"'
sqote="'"
cmd1="sed -e s/" + dqote + ",u'" + dqote + "/" + dqote + ",'" + dqote + '/g -e s/^"u' + sqote + dqote + '/' + dqote + sqote + dqote + '/'
The answer by Jones Agyemang is probably sufficient for most use cases and was a great starting point for my solution. For scripting in Git Bent, the git wrapper library I made, I needed something a bit more robust. I'm posting the prototype I've written which is not yet totally script-friendly
<<<<<<< HEAD
which doesn't work for merge conflicts from using git stash apply
which has <<<<<<< Updated Upstream
=======
& >>>>>>>
You need the str_split_line
function from below.
# Root git directory
dir="$(git rev-parse --show-toplevel)"
# Put the grep output into an array (see below)
str_split_line "$(grep -r "^<<<<<<< " "${dir})" files
bn="$(basename "${dir}")"
for i in "${files[@]}"; do
# Remove the matched string, so we're left with the file name
file="$(sed -e "s/:<<<<<<< .*//" <<< "${i}")"
# Remove the path, keep the project dir's name
fileShort="${file#"${dir}"}"
fileShort="${bn}${fileShort}"
# Confirm merge divider & closer are present
c1=$(grep -c "^=======" "${file}")
c2=$(grep -c "^>>>>>>> " "${file}")
if [[ c1 -gt 0 && c2 -gt 0 ]]; then
echo "${fileShort} has a merge conflict"
fi
done
projectdir/file-name
projectdir/subdir/file-name
You can just copy the block of code if you don't want this as a separate function
function str_split_line(){
# for IFS, see https://stackoverflow.com/questions/16831429/when-setting-ifs-to-split-on-newlines-why-is-it-necessary-to-include-a-backspac
IFS="
"
declare -n lines=$2
while read line; do
lines+=("${line}")
done <<< "${1}"
}
The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0
if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0
only works for the older MDB format.
You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).
You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.
Public Sub foo()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Access\webforums\whiteboard2003.mdb"
strSql = "SELECT Count(*) FROM MyTable;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
MsgBox rs.fields(0) & " rows in MyTable"
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.
This won't work. You first have to initialize the array. So far, you only have a String[] reference, pointing to null
.
When you try to read the length member, what you actually do is null.length
, which results in a NullPointerException.
This must be a new feature or something, otherwise I'm not sure why it hasn't been mentioned.
You can access the value in a column in a DataRow
object using row["ColumnName"]
:
DataRow row = table.Rows[0];
string rowValue = row["ColumnName"].ToString();
That's about it. There is no magic built-in function...
Try to run in another port like 3131. Run the command:
react-native run-android --port=3131
I found this catered for dates in 21st Century that could be entered as dd/mm or dd/mm/yy. It is intended to print an attendance register and asks for the meeting date to start with.
Sub Print_Register()
Dim MeetingDate, Answer
Sheets("Register").Select
Range("A1").Select
GetDate:
MeetingDate = DateValue(InputBox("Enter the date of the meeting." & Chr(13) & _
"Note Format" & Chr(13) & "Format DD/MM/YY or DD/MM", "Meeting Date", , 10000, 10000))
If MeetingDate = "" Then GoTo TheEnd
If MeetingDate < 36526 Then MeetingDate = MeetingDate + 36526
Range("Current_Meeting_Date") = MeetingDate
Answer = MsgBox("Date OK?", 3)
If Answer = 2 Then GoTo TheEnd
If Answer = 7 Then GoTo GetDate
ExecuteExcel4Macro "PRINT(1,,,1,,,,,,,,2,,,TRUE,,FALSE)"
TheEnd:
End Sub
I prefer ^[-+]?([1-9]\d*|0)$
because ^[-+]?[0-9]+$
allows the string starting with 0
.
RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')
class TestRE(unittest.TestCase):
def test_int(self):
self.assertFalse(RE_INT.match('+'))
self.assertFalse(RE_INT.match('-'))
self.assertTrue(RE_INT.match('1'))
self.assertTrue(RE_INT.match('+1'))
self.assertTrue(RE_INT.match('-1'))
self.assertTrue(RE_INT.match('0'))
self.assertTrue(RE_INT.match('+0'))
self.assertTrue(RE_INT.match('-0'))
self.assertTrue(RE_INT.match('11'))
self.assertFalse(RE_INT.match('00'))
self.assertFalse(RE_INT.match('01'))
self.assertTrue(RE_INT.match('+11'))
self.assertFalse(RE_INT.match('+00'))
self.assertFalse(RE_INT.match('+01'))
self.assertTrue(RE_INT.match('-11'))
self.assertFalse(RE_INT.match('-00'))
self.assertFalse(RE_INT.match('-01'))
self.assertTrue(RE_INT.match('1234567890'))
self.assertTrue(RE_INT.match('+1234567890'))
self.assertTrue(RE_INT.match('-1234567890'))
There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar
:
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
The last thing is to wrap SqlConnection
and SqlCommand
into using
so any resources used by those will be disposed of:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
{
cmd.Parameters.AddWithValue("@id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Using Lambda:
new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
.setTitle(getString(R.string.info))
.setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
moveTaskToBack(true);
finish();
})
.setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
})
.show();
You also need to set level language to support java 8 in your gradle.build:
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
I used this line to locate and edit the permissions under xampp:
chmod 777 ~/.bitnami/stackman/machines/xampp/volumes/root/htdocs/folder
In case you're working with a regular old System.Collections.IEnumerable
instead of IEnumerable<T>
you can use enumerable.Cast<object>().ToList()
this works too, ...if you have multiple column joins
from p in context.Periods
join f in context.Facts
on new {
id = p.periodid,
p.otherid
} equals new {
f.id,
f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value
Suppose you dataframe looks like :
Now you want to check if filename "80900026941984" is present in the dataframe or not.
You can simply write :
if sum(df["filename"].astype("str").str.contains("80900026941984")) > 0:
print("found")
ES6 offers the Set data structure which is basically an array that doesn't accept duplicates. With the Set data structure, there's a very easy way to find duplicates in an array (using only one loop).
Here's my code
function findDuplicate(arr) {
var set = new Set();
var duplicates = new Set();
for (let i = 0; i< arr.length; i++) {
var size = set.size;
set.add(arr[i]);
if (set.size === size) {
duplicates.add(arr[i]);
}
}
return duplicates;
}
Simply you can save with extension .json but while saving you have to do some changes.
Change Save as type in red circle in image to All Files.
It will create .json file with name bharti.json.
To check this --> Right click at file --> Properties --> Type of file: JSON File (.json)
= """" & A1 & """"
Public Function Enquote(cell As Range, Optional quoteCharacter As String = """") As Variant
Enquote = quoteCharacter & cell.value & quoteCharacter
End Function
=OfficePersonal.xls!Enquote(A1)
=OfficePersonal.xls!Enquote(A1, "'")
To get permanent quoted strings, you will have to copy formula values and paste-special-values.
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine. creates the the key with its value in the array
If sunday is considered as week start day, then here is the code
Declare @currentdate date = '18 Jun 2020'
select DATEADD(D, -(DATEPART(WEEKDAY, @currentdate) - 1), @currentdate)
select DATEADD(D, (7 - DATEPART(WEEKDAY, @currentdate)), @currentdate)
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
Here is a basic implementation of a graph. Note: I use vertex which is chained to next vertex. And each vertex has a list pointing to adjacent nodes.
#include <iostream>
using namespace std;
// 1 ->2
// 1->4
// 2 ->3
// 4->3
// 4 -> 5
// Adjacency list
// 1->2->3-null
// 2->3->null
//4->5->null;
// Structure of a vertex
struct vertex {
int i;
struct node *list;
struct vertex *next;
};
typedef struct vertex * VPTR;
// Struct of adjacency list
struct node {
struct vertex * n;
struct node *next;
};
typedef struct node * NODEPTR;
class Graph {
public:
// list of nodes chained together
VPTR V;
Graph() {
V = NULL;
}
void addEdge(int, int);
VPTR addVertex(int);
VPTR existVertex(int i);
void listVertex();
};
// If vertex exist, it returns its pointer else returns NULL
VPTR Graph::existVertex(int i) {
VPTR temp = V;
while(temp != NULL) {
if(temp->i == i) {
return temp;
}
temp = temp->next;
}
return NULL;
}
// Add a new vertex to the end of the vertex list
VPTR Graph::addVertex(int i) {
VPTR temp = new(struct vertex);
temp->list = NULL;
temp->i = i;
temp->next = NULL;
VPTR *curr = &V;
while(*curr) {
curr = &(*curr)->next;
}
*curr = temp;
return temp;
}
// Add a node from vertex i to j.
// first check if i and j exists. If not first add the vertex
// and then add entry of j into adjacency list of i
void Graph::addEdge(int i, int j) {
VPTR v_i = existVertex(i);
VPTR v_j = existVertex(j);
if(v_i == NULL) {
v_i = addVertex(i);
}
if(v_j == NULL) {
v_j = addVertex(j);
}
NODEPTR *temp = &(v_i->list);
while(*temp) {
temp = &(*temp)->next;
}
*temp = new(struct node);
(*temp)->n = v_j;
(*temp)->next = NULL;
}
// List all the vertex.
void Graph::listVertex() {
VPTR temp = V;
while(temp) {
cout <<temp->i <<" ";
temp = temp->next;
}
cout <<"\n";
}
// Client program
int main() {
Graph G;
G.addEdge(1, 2);
G.listVertex();
}
With the above code, you can expand to do DFS/BFS etc.
EDIT :
The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.
Could you post an example from your code ?
Take a look at this gist : https://gist.github.com/Akayh/5566992
it works but it was done very quickly :
MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")
Set new value to mString : "Singleton"
Launch activityB and show the mString value. "Singleton" appears...
In my case, I've just downloaded the missing file directly from here: https://gitlab.com/mailman/mailman-website/raw/a97d6b4c5b29594004e3855f1ab1222449d0c211/content/fonts/glyphicons-halflings-regular.woff2
The first answer is great only for those people who know kotlin, for those who still using java here I translate the first answer
public Notification getNotification() {
String channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channel).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentTitle("snap map fake location");
Notification notification = mBuilder
.setPriority(PRIORITY_LOW)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
return notification;
}
@NonNull
@TargetApi(26)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "snap map fake location ";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("snap map channel", name, importance);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "snap map channel";
}
For android, P don't forget to include this permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).
I went with a list.Sort solution something like this.
var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
OrderId = o.id,
OrderDate = o.orderDate,
OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
});
data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));
I think the best answer in 2017 is to use the javax.json APIs. Use javax.json.JsonBuilderFactory to create your json objects, then write the objects out using javax.json.JsonWriterFactory. Very nice builder/writer combination.
if you need to decompile standalone jar try JD-GUI by the same autor (of JD-Eclipse). It is a standalone application (does not need eclipse). It can open both *.class and *.jar files. Interesting enough it needs .Net installed (as do JD-Eclipse indeed), but otherwise works like a charm.
Find it here:
Regards,
SHOW FULL PROCESSLIST
If you don't use FULL
, "only the first 100 characters of each statement are shown in the Info
field".
When using phpMyAdmin, you should also click on the "Full texts" option ("? T ?" on top left corner of a results table) to see untruncated results.
You can call tail +[line number] [file]
and pipe it to grep -n
which shows the line number:
tail +[line number] [file] | grep -n /regex/
The only problem with this method is the line numbers reported by grep -n
will be [line number] - 1
less than the actual line number in [file]
.
What about something like this:
for /f %%f in ('curl -s -l -u user:pass ftp://ftp.myftpsite.com/') do curl -O -u user:pass ftp://ftp.myftpsite.com/%%f
Menu Window ? Preferences. General ? Appearance ? Colors and Fonts ? Basic ? Text Font
The Spinner class implements DialogInterface.OnClickListener
, thereby effectively hijacking the standard View.OnClickListener
.
If you are not using a sub-classed Spinner or don't intend to, choose another answer.
Otherwise just add the following code to your custom Spinner:
@Override
/** Override triggered on 'tap' of closed Spinner */
public boolean performClick() {
// [ Do anything you like here ]
return super.performClick();
}
Example: Display a pre-supplied hint via Snackbar whenever the Spinner is opened:
private String sbMsg=null; // Message seen by user when Spinner is opened.
public void setSnackbarMessage(String msg) { sbMsg=msg; }
@Override
/** Override triggered on 'tap' of closed Spinner */
public boolean performClick() {
if (sbMsg!=null && !sbMsg.isEmpty()) { /* issue Snackbar */ }
return super.performClick();
}
A custom Spinner is a terrific starting point for programmatically standardising Spinner appearance throughout your project.
If interested, looky here
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
The solution that worked for me is:
suptitle()
for the actual titletitle()
for the subtitle and adjust it using the optional parameter y
: import matplotlib.pyplot as plt
"""
some code here
"""
plt.title('My subtitle',fontsize=16)
plt.suptitle('My title',fontsize=24, y=1)
plt.show()
There can be some nasty overlap between the two pieces of text. You can fix this by fiddling with the value of y
until you get it right.
Save yourself some troubleshooting time and log your require call, like so:
console.log(require('dotenv').config())
You should see an error with more detailed info on the problem.
You can have multiple CTE
s in one query, as well as reuse a CTE
:
WITH cte1 AS
(
SELECT 1 AS id
),
cte2 AS
(
SELECT 2 AS id
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1
Note, however, that SQL Server
may reevaluate the CTE
each time it is accessed, so if you are using values like RAND()
, NEWID()
etc., they may change between the CTE
calls.
I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:
copyFactory = (() ->
resource = ->
resource.__super__.constructor.apply this, arguments
return
this.extendTo resource
resource
).call(factory)
I have found... margin: 0 auto; works for me. But I have also seen it NOT work due to the class being trumped by another specificity that had ... float:left; so watch for that you may need to add ... float:none; this worked in my case as I was coding a media query.
To add a prefix to all files and folders in the current directory using util-linux's rename
(as opposed to prename
, the perl variant from Debian and certain other systems), you can do:
rename '' <prefix> *
This finds the first occurrence of the empty string (which is found immediately) and then replaces that occurrence with your prefix, then glues on the rest of the file name to the end of that. Done.
For suffixes, you need to use the perl version or use find.
There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.
Windows shell, one liner:
FOR /F %%I IN ('DIR *.* /B /O:-D') DO COPY %%I <<NewDir>> & EXIT
boolean b = ....;
int i = -("false".indexOf("" + b));
What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.
You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.
Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).
Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org
Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.
In summary then: it all depends on your region.
Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.
Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.
Using the concept from waldyrious's answer, I've created the following solution that also addresses the issue of the video playing behind the image on tab restore or using the browser's back button to come back to the page with the video.
<div class="js-video-lead">
<img class="hide" src="link/to/lead/image.jpg" />
<iframe frameborder="0" height="240" src="https://www.youtube.com/embed/<code here>" width="426"></iframe>
</div>
The "hide" class is from Bootstrap and simply applies display: none;
so that the image is not visible on page load if JavaScript is disabled.
function video_lead_play_state(element, active)
{
var $active = $(element).closest(".js-video-lead").find(".btn-play-active");
var $default = $(element).closest(".js-video-lead").find(".btn-play-default");
if (active) {
$active.show();
$default.hide();
} else {
$active.hide();
$default.show();
}
}
$(document).ready(function () {
// hide the videos and show the images
var $videos = $(".js-video-lead iframe");
$videos.hide();
$(".js-video-lead > img").not(".btn-play").show();
// position the video holders
$(".js-video-lead").css("position", "relative");
// prevent autoplay on load and add the play button
$videos.each(function (index, video) {
var $video = $(video);
// prevent autoplay due to normal navigation
var url = $video.attr("src");
if (url.indexOf("&autoplay") > -1) {
url = url.replace("&autoplay=1", "");
} else {
url = url.replace("?autoplay=1", "");
}
$video.attr("src", url).removeClass(
"js-video-lead-autoplay"
);
// add and position the play button
var top = parseInt(parseFloat($video.css("height")) / 2) - 15;
var left = parseInt(parseFloat($video.css("width")) / 2) - 21;
var $btn_default = $("<img />").attr("src", "play-default.png").css({
"position": "absolute",
"top": top + "px",
"left": left + "px",
"z-index": 100
}).addClass("btn-play btn-play-default");
var $btn_active = $("<img />").attr("src", "play-active.png").css({
"display": "none",
"position": "absolute",
"top": top + "px",
"left": left + "px",
"z-index": 110
}).addClass("btn-play btn-play-active");
$(".js-video-lead").append($btn_default).append($btn_active);
});
$(".js-video-lead img").on("click", function (event) {
var $holder = $(this).closest(".js-video-lead");
var $video = $holder.find("iframe");
var url = $video.attr("src");
url += (url.indexOf("?") > -1) ? "&" : "?";
url += "autoplay=1";
$video.addClass("js-video-lead-autoplay").attr("src", url);
$holder.find("img").remove();
$video.show();
});
$(".js-video-lead > img").on("mouseenter", function (event) {
video_lead_play_state(this, true);
});
$(".js-video-lead > img").not(".btn-play").on("mouseleave", function (event) {
video_lead_play_state(this, false);
});
});
jQuery is required for this solution and it should work with multiple embedded videos (with different lead images) on the same page.
The code utilizes two images play-default.png
and play-active.png
which are small (42 x 30) images of the YouTube play button. play-default.png
is black with some transparency and is displayed initially. play-active.png
is red and is displayed when the user moves the mouse over the image. This mimic's the expected behavior that a normal embedded YouTube video exhibits.
A simple solution that works for me, to work with console ability(ReadKey, String with Format and arg etc) and to see and save the output:
I write TextWriter that write to Console
and to Trace
and replace the Console.Out
with it.
if you use Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window" you get it in the Immediate Window and pretty clean.
my code: in start of my code:
Console.SetOut(new TextHelper());
and the class:
public class TextHelper : TextWriter
{
TextWriter console;
public TextHelper() {
console = Console.Out;
}
public override Encoding Encoding => this.console.Encoding;
public override void WriteLine(string format, params object[] arg)
{
string s = string.Format(format, arg);
WriteLine(s);
}
public override void Write(object value)
{
console.Write(value);
System.Diagnostics.Trace.Write(value);
}
public override void WriteLine(object value)
{
Write(value);
Write("\n");
}
public override void WriteLine(string value)
{
console.WriteLine(value);
System.Diagnostics.Trace.WriteLine(value);
}
}
Note: I override just what I needed so if you write other types you should override more
Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.
It is important to remember that the driver(file) must have execution permission (linux chmod +x geckodriver).
To sum up:
Add system property:
System.setProperty("webdriver.gecko.driver", "FILE PATH");
Instantiate and use the class
WebDriver driver = new FirefoxDriver();
Do whatever you want
Close the driver
driver.close;
You can reverse by the $index parameter
<tr ng-repeat="friend in friends | orderBy:'$index':true">
Or you could git checkout -b <new-branch>
and git cherry-pick <commit>
the before to the and git rebase
to drop revert
commit. send pull request like before.
To skip the test case during maven clean install i used -DskipTests paramater in following command
mvn clean install -DskipTests
into terminal window
I think you want (this won't fit in a int
though, you'll need to store it as a long
):
long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;
Alternatively, storing the ticks is a better idea.
When you declare a variable, you need to declare its type - in this case: int
. Also you've put a random comma in the while
loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
Google recently added this comprehensive list of reference devices and resolutions, including new device types such as wearables and laptops:
By default, a MariaDB installation has an anonymous user, allowing anyone to log into MariaDB without having to have a user account created for them. This is intended only for testing, and to make the installation go a bit smoother. You should remove them before moving into a production environment.
So many good answers, her are my 2 cents
i prefer to use inline function and old style of put and get value
object PreferenceHelper {
private const val PREFERENCES_KEY = "MyLocalPreference"
private fun getPreference(context: Context): SharedPreferences {
return context.getSharedPreferences(
PREFERENCES_KEY,
Context.MODE_PRIVATE
)
}
fun setBoolean(appContext: Context, key: String?, value: Boolean?) =
getPreference(appContext).edit().putBoolean(key, value!!).apply()
fun setInteger(appContext: Context, key: String?, value: Int) =
getPreference(appContext).edit().putInt(key, value).apply()
fun setFloat(appContext: Context, key: String?, value: Float) =
getPreference(appContext).edit().putFloat(key, value).apply()
fun setString(appContext: Context, key: String?, value: String?) =
getPreference(appContext).edit().putString(key, value).apply()
// To retrieve values from shared preferences:
fun getBoolean(appContext: Context, key: String?, defaultValue: Boolean?): Boolean =
getPreference(appContext).getBoolean(key, defaultValue!!)
fun getInteger(appContext: Context, key: String?, defaultValue: Int): Int =
getPreference(appContext)
.getInt(key, defaultValue)
fun getString(appContext: Context, key: String?, defaultValue: String?): String? =
getPreference(appContext)
.getString(key, defaultValue)
}
Usage
PreferenceHelper.setString(context,"CUSTOMER_NAME", "HITESH")
Toast.makeText(context, "Hello " + PreferenceHelper.getString(context,"CUSTOMER_NAME", "User"), Toast.LENGTH_LONG).show()
To get past INSTALL_FAILED_MISSING_SHARED_LIBRARY
error with Google Maps for Android:
Install Google map APIs. This can be done in Eclipse Windows/Android SDK and AVD Manager -> Available Packages -> Third Party Add-ons -> Google Inc. -> Google APIs by Google Inc., Android API X
From command line create new AVD. This can be done by listing targets (android list targets), then android create avd -n new_avd_api_233 -t "Google Inc.:Google APIs:X"
Then create AVD (Android Virtual Device) in Eclipse Windows/Android SDK and AVD Manager -> New... -> (Name: new_avd_X, Target: Google APIs (Google Inc.) - API Level X)
IMPORTANT
: You must create your AVD with Target as Google APIs (Google Inc.) otherwise it will again failed.
Create Android Project in Eclipse File/New/Android Project and select Google APIs Build Target.
add <uses-library android:name="com.google.android.maps" /> between <application> </application> tags.
Run Project as Android Application.
If error persists, then you still have problems, if it works, then this error is forever behind you.
I did it like this
#!/bin/bash
ZK_HOST="localhost"
ZK_PORT=2181
for i in `echo dump | nc $ZK_HOST $ZK_PORT | grep brokers`
do
echo $i
DETAIL=`zkCli -server "$ZK_HOST:$ZK_PORT" get $i 2>/dev/null | tail -n 1`
echo $DETAIL
done
You can use Xtreme Download Manager(XDM) software for this. This software can download from any site in this format. Even this software can change the ts file format. You only need to change the format when downloading.
like:https://www.videohelp.com/software/Xtreme-Download-Manager-
Do you just want to know how to write a line to a file? First, you need to open the file:
f = open("filename.txt", 'w')
Then, you need to write the string to the file:
f.write("dict = {'one': 1, 'two': 2}" + '\n')
You can repeat this for each line (the +'\n'
adds a newline if you want it).
Finally, you need to close the file:
f.close()
You can also be slightly more clever and use with
:
with open("filename.txt", 'w') as f:
f.write("dict = {'one': 1, 'two': 2}" + '\n')
### repeat for all desired lines
This will automatically close the file, even if exceptions are raised.
But I suspect this is not what you are asking...
A simple way :
n = int(input())
arr = list(map(int, input().split()))
for i in reversed(range(0, n)):
print("%d %d" %(i, arr[i]))
This is how it look like in pure bash
cat /usr/lib/cgi-bin/index.cgi
#!/bin/bash
echo Content-type: text/html
echo ""
## make POST and GET stings
## as bash variables available
if [ ! -z $CONTENT_LENGTH ] && [ "$CONTENT_LENGTH" -gt 0 ] && [ $CONTENT_TYPE != "multipart/form-data" ]; then
read -n $CONTENT_LENGTH POST_STRING <&0
eval `echo "${POST_STRING//;}"|tr '&' ';'`
fi
eval `echo "${QUERY_STRING//;}"|tr '&' ';'`
echo "<!DOCTYPE html>"
echo "<html>"
echo "<head>"
echo "</head>"
if [[ "$vote" = "a" ]];then
echo "you pressed A"
sudo /usr/local/bin/run_a.sh
elif [[ "$vote" = "b" ]];then
echo "you pressed B"
sudo /usr/local/bin/run_b.sh
fi
echo "<body>"
echo "<div id=\"content-container\">"
echo "<div id=\"content-container-center\">"
echo "<form id=\"choice\" name='form' method=\"POST\" action=\"/\">"
echo "<button id=\"a\" type=\"submit\" name=\"vote\" class=\"a\" value=\"a\">A</button>"
echo "<button id=\"b\" type=\"submit\" name=\"vote\" class=\"b\" value=\"b\">B</button>"
echo "</form>"
echo "<div id=\"tip\">"
echo "</div>"
echo "</div>"
echo "</div>"
echo "</div>"
echo "</body>"
echo "</html>"
Build with https://github.com/tinoschroeter/bash_on_steroids
$('.slide-link[data-slide="0"]').addClass('active');
it works down the tree
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
I had the same issue. I ended up re-importing the entire project to fix the problem.
In general I would consider setting up of an environment variable (like PYTHONPATH)
to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.
Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the
test environment as well, leading to situations like the tests running fine for a
particular developer but probably failing when some one launches the tests.
To answer your second question:
view.setPadding(0,padding,0,0);
like SpK and Jave suggested, will set the padding in pixels. You can set it in dp by calculating the dp value as follows:
int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);
Hope that helps!
As Xavier said, you can put your prebuilts in /src/main/jniLibs/ if you are using gradle 0.7.2+
taken from: https://groups.google.com/d/msg/adt-dev/nQobKd2Gl_8/ctDp9viWaxoJ
Run vim
from the terminal. For the basics, you're advised to run the command vimtutor
.
# On your terminal command line:
$ vim
If you have a specific file to edit, pass it as an argument.
$ vim yourfile.cpp
Likewise, launch the tutorial
$ vimtutor
First, pressing Enter inside a textarea does not submit the form unless you have script to make it do that. That's the behaviour the user expects and I'd recommend against changing it. However, if you must do this, the easiest approach would be to find the script that is making Enter submit the form and change it. The code will have something like
if (evt.keyCode == 13) {
form.submit();
}
... and you could just change it to
if (evt.keyCode == 13 && !evt.shiftKey) {
form.submit();
}
On the other hand, if you don't have access to this code for some reason, you need to do the following to make it work in all major browsers even if the caret is not at the end of the text:
jsFiddle: http://jsfiddle.net/zd3gA/1/
Code:
function pasteIntoInput(el, text) {
el.focus();
if (typeof el.selectionStart == "number"
&& typeof el.selectionEnd == "number") {
var val = el.value;
var selStart = el.selectionStart;
el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
el.selectionEnd = el.selectionStart = selStart + text.length;
} else if (typeof document.selection != "undefined") {
var textRange = document.selection.createRange();
textRange.text = text;
textRange.collapse(false);
textRange.select();
}
}
function handleEnter(evt) {
if (evt.keyCode == 13 && evt.shiftKey) {
if (evt.type == "keypress") {
pasteIntoInput(this, "\n");
}
evt.preventDefault();
}
}
// Handle both keydown and keypress for Opera, which only allows default
// key action to be suppressed in keypress
$("#your_textarea_id").keydown(handleEnter).keypress(handleEnter);
Add one more slash after file://
in the value of xsi:schemaLocation
. (You have two; you need three. Think protocol://host/path
where protocol
is 'file'
and host
is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path
. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.
xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"
Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:
file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd
If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.
If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.
Use also this way to represent image in base64 encode format...
find PHP function file_get_content
and next to use function base64_encode
and get result to prepare str as data:" . file_mime_type . " base64_encoded string
. Use it in img src attribute. see following code can I help for you.
// A few settings
$img_file = 'raju.jpg';
// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;
// Echo out a sample image
echo '<img src="'.$src.'">';
$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];
but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.
In the past I have created my XML Schema, then used a tool to generate C# classes which will serialize to that schema. The XML Schema Definition Tool is one example
http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx
There is a non-deprecated way to do this using DisplayMetrics (API 1), that avoids the try/catch messiness:
// initialize the DisplayMetrics object
DisplayMetrics deviceDisplayMetrics = new DisplayMetrics();
// populate the DisplayMetrics object with the display characteristics
getWindowManager().getDefaultDisplay().getMetrics(deviceDisplayMetrics);
// get the width and height
screenWidth = deviceDisplayMetrics.widthPixels;
screenHeight = deviceDisplayMetrics.heightPixels;
Your typedef
needs to be in the header file (or some other file that's #import
ed into your header), because otherwise the compiler won't know what size to make the PlayerState
ivar. Other than that, it looks ok to me.
There are Linq extension methods for DataTable.
Add reference to: System.Data.DataSetExtensions.dll
Then include the namespace: using System.Data.DataSetExtensions
Finally you can use Linq extensions on DataSet and DataTables:
var matches = myDataSet.Tables.First().Where(dr=>dr.Field<int>("id") == 1);
On .Net 2.0 you can still add generic method:
public static List<T> ConvertRowsToList<T>( DataTable input, Convert<DataRow, T> conversion) {
List<T> retval = new List<T>()
foreach(DataRow dr in input.Rows)
retval.Add( conversion(dr) );
return retval;
}
That's because you created a Web Site instead of a Web Application. The cs/vb
files can only be seen in a Web Application, but in a website you can't have a separate cs/vb
file.
Edit: In the website you can add a cs file behavior like..
<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>
~/Global.asax.cs:
namespace ApplicationName
{
public partial class MyApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
}
}
}
When you use autofilter to filter results, Excel doesn't even bother to hide them: it just sets the height of the row to zero (up to 2003 at least, not sure on 2007).
So the following custom function should give you a starter to do what you want (tested with integers, haven't played with anything else):
Function SumVis(r As Range)
Dim cell As Excel.Range
Dim total As Variant
For Each cell In r.Cells
If cell.Height <> 0 Then
total = total + cell.Value
End If
Next
SumVis = total
End Function
Edit:
You'll need to create a module in the workbook to put the function in, then you can just call it on your sheet like any other function (=SumVis(A1:A14)). If you need help setting up the module, let me know.
Came across this old question looking for solution myself.
Use psutil:
import psutil
import sys
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'your_script.py']:
sys.exit('Process found: exiting.')
print('Process not found: starting it.')
Popen(['python', 'your_script.py'])
The properties center
, bounds
and frame
are interlocked: changing one will update the others, so use them however you want. For example, instead of modifying the x/y params of frame
to recenter a view, just update the center
property.
For me didn't work the recognized solution from this post: https://stackoverflow.com/a/9619478/4507034.
Instead, I managed to solve the problem by importing the certification to my machine trusted certifications.
Steps:
https://localhost:8443/yourpath
) where the certification is not working. Manage computer certificates
Trusted Root Certification Authorities
-> Certificates
your_certification_name.cer
file. round() can take ints and negative numbers for places, which round to the left of the decimal. The return value is still a float, but a simple cast fixes that:
>>> int(round(5678,-1))
5680
>>> int(round(5678,-2))
5700
>>> int(round(5678,-3))
6000
Analogous to @Resh32, but without the need to use the USE
statement:
SELECT TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "database_name"
AND TABLE_NAME = "table_name"
AND REFERENCED_COLUMN_NAME IS NOT NULL;
Useful, e.g. using the ORM.
As others have said, in general you use @synthesize to have the compiler generate the getters and/ or settings for you, and @dynamic if you are going to write them yourself.
There is another subtlety not yet mentioned: @synthesize will let you provide an implementation yourself, of either a getter or a setter. This is useful if you only want to implement the getter for some extra logic, but let the compiler generate the setter (which, for objects, is usually a bit more complex to write yourself).
However, if you do write an implementation for a @synthesize'd accessor it must still be backed by a real field (e.g., if you write -(int) getFoo();
you must have an int foo;
field). If the value is being produce by something else (e.g. calculated from other fields) then you have to use @dynamic.
If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):
For Xpath:
http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html
Just for fun:
var mystring = "this,is,a,test"
var newchar = '|'
mystring = mystring.split(',').join(newchar);
The ');
ends the query, it doesn't start a comment. Then it drops the students table and comments the rest of the query that was supposed to be executed.
In my case I had to change the permissions of /home/user from 0755 to 0700 as well.
Another thing that helps improve the accuracy of what I do isn't really a management studio tip but one using t-sql itself.
Whenever I write an update or delete statement for the first time, I incorporate a select into it so that I can see what records will be affected.
Examples:
select t1.field1,t2.field2
--update t
--set field1 = t2.field2
from mytable t1
join myothertable t2 on t1.idfield =t2.idfield
where t2.field1 >10
select t1.*
--delete t1
from mytable t1
join myothertable t2 on t1.idfield =t2.idfield
where t2.field1 = 'test'
(note I used select * here just for illustration, I would normally only select the few fields I need to see that the query is correct. Sometimes I might need to see fields from the other tables inthe join as well as the records I plan to delete to make sure the join worked the way I thought it would)
When you run this code, you run the select first to ensure it is correct, then comment the select line(s) out and uncomment the delete or update parts. By doing it this way, you don't accidentally run the delete or update before you have checked it. Also you avoid the problem of forgetting to comment out the select causing the update to update all records in the database table that can occur if you use this syntax and uncomment the select to run it:
select t1.field1,t2.field2
update t
set field1 = t2.field2
--select t1.field1,t2.field2
from mytable t1
join myothertable t2 on t1.idfield =t2.idfield
where t2.field1 >10
As you can see from the example above, if you uncomment the select and forget to re-comment it out, oops you just updated the whole table and then ran a select when you thought to just run the update. Someone just did that in my office this week making it so only one person of all out clients could log into the client websites. So avoid doing this.
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
My test string for the following:
testing='12345,abc,123,54321,ab15234,123456,52341';
If I understand your question, you'd want ["12345", "54321", "15234", "52341"]
.
If JS engines supported regexp lookbehinds, you could do:
testing.match(/(?<!\d)\d{5}(?!\d)/g)
Since it doesn't currently, you could:
testing.match(/(?:^|\D)(\d{5})(?!\d)/g)
and remove the leading non-digit from appropriate results, or:
pentadigit=/(?:^|\D)(\d{5})(?!\d)/g;
result = [];
while (( match = pentadigit.exec(testing) )) {
result.push(match[1]);
}
Note that for IE, it seems you need to use a RegExp stored in a variable rather than a literal regexp in the while
loop, otherwise you'll get an infinite loop.
Here is a bulky but fast version :
def nbdigit ( x ):
if x >= 10000000000000000 : # 17 -
return len( str( x ))
if x < 100000000 : # 1 - 8
if x < 10000 : # 1 - 4
if x < 100 : return (x >= 10)+1
else : return (x >= 1000)+3
else: # 5 - 8
if x < 1000000 : return (x >= 100000)+5
else : return (x >= 10000000)+7
else: # 9 - 16
if x < 1000000000000 : # 9 - 12
if x < 10000000000 : return (x >= 1000000000)+9
else : return (x >= 100000000000)+11
else: # 13 - 16
if x < 100000000000000 : return (x >= 10000000000000)+13
else : return (x >= 1000000000000000)+15
Only 5 comparisons for not too big numbers.
On my computer it is about 30% faster than the math.log10
version and 5% faster than the len( str())
one.
Ok... no so attractive if you don't use it furiously.
And here is the set of numbers I used to test/measure my function:
n = [ int( (i+1)**( 17/7. )) for i in xrange( 1000000 )] + [0,10**16-1,10**16,10**16+1]
NB: it does not manage negative numbers, but the adaptation is easy...
The "0x" counts towards the eight character count. You need "%#010x"
.
Note that #
does not append the 0x to 0 - the result will be 0000000000
- so you probably actually should just use "0x%08x"
anyway.
Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:
If the message is "No name ... in module ...", use the search:
No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers
Or, to get fewer results:
"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers
GitHub will show you:
"E0611": (
"No name %r in module %r",
"no-name-in-module",
"Used when a name cannot be found in a module.",
You can then do:
from collections import Sequence # pylint: disable=no-name-in-module
Seems like getTime
is not function on above answer.
Date.parse(currentDate)/1000
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
First, if you are unfamiliar with the command line, try using phpmyadmin from your webbrowser. This will make sure you actually have a mysql database created and a username.
This is how you connect from the command line (bash):
mysql -h hostname -u username -p database_name
For example:
fabio@crunchbang ~ $ mysql -h 127.0.0.1 -u fabio -p fabiodb
This helped me understand / streamline, only what I needed to animate:
// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}
.base {
max-width: 0vw;
opacity: 0;
transition-property: max-width, opacity; // relative order
transition-duration: 2s, 4s; // effects relatively ordered animation properties
transition-delay: 6s; // effects delay of all animation properties
animation-timing-function: ease;
&:hover {
max-width: 100vw;
opacity: 1;
transition-duration: 5s; // effects duration of all aniomation properties
transition-delay: 2s, 7s; // effects relatively ordered animation properties
}
}
~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class
Try this:
lst = []
##use append to add items to the list.
lst.append({'A':0,'C':0,'G':0,'T':0})
lst.append({'A':1,'C':1,'G':1,'T':1})
##if u need to add n no of items to the list, use range with append:
for i in range(n):
lst.append({'A':0,'C':0,'G':0,'T':0})
print lst
Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm
You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking
In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))
In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]:
A B C D
12 0.491683 0.137766 0.859753 -1.041487
13 0.376200 0.575667 1.534179 1.247358
14 0.428739 1.539973 1.057848 -1.254489
In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]:
A 3
B 3
C 3
D 3
dtype: int64
In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3
I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.
Ex:
Declare @Temp Table(Data VarChar(20))
Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')
Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From @Temp
PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.
There are still ways this can fail. For a full explanation, I encourage you to read:
Extracting numbers with SQL Server
That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.
I dont program in C# but in C, we solve the same problem by making the socket non-blocking and then putting the fd in a select/poll loop with a timeout value equal to the amount of time we are willing to wait for the connect to succeed.
I found this for Visual C++ and the explanation there also bends towards the select/poll mechanism I explained before.
In my experience, you cannot change connect timeout values per socket. You change it for all (by tuning OS parameters).
With reflection.
public object tst() {
var a = new {
prop1 = "test1",
prop2 = "test2"
};
return a;
}
public string tst2(object anonymousObject, string propName) {
return anonymousObject.GetType().GetProperties()
.Where(w => w.Name == propName)
.Select(s => s.GetValue(anonymousObject))
.FirstOrDefault().ToString();
}
Sample:
object a = tst();
var val = tst2(a, "prop2");
Output:
test2
<div style="display:table;width:100%" >
<div style="display:table-cell;width:49%" id="div1">
content
</div>
<!-- space between divs - display table-cell -->
<div style="display:table-cell;width:1%" id="separated"></div>
<!-- //space between divs - display table-cell -->
<div style="display:table-cell;width:50%" id="div2">
content
</div>
</div>
Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)
Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:
#import "someFile.h"
Or in the case of frameworks:
#import <SomeLibrary/SomeFile.h>
Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include
statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h
and SomeFileB.h
; SomeFileA.h
includes SomeFileB.h
, and SomeFileB.h
includes SomeFileA.h
. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.
When using #import
, you don’t need to worry about this issue or write header guards to avoid it. However, #import
is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)
Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import
.
Returning to the previous example of importing a framework:
#import <SomeLibrary/SomeFile.h>
To import this library as a module, the code would be changed to:
@import SomeLibrary;
This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:
@import AwesomeLibrary.AwesomeObject;
For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import
and @import
statements in your code together without any concern.
Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.
This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter
i=0;
w_h = 0;
w_m = 0;
textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
hl.removeCallbacksAndMessages(null);
Thread.currentThread().isInterrupted();
}
});
}`
The bash script solution:
if ! xset q &>/dev/null; then
echo "No X server at \$DISPLAY [$DISPLAY]" >&2
exit 1
fi
Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:
#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
echo "X server running"
exit 1
fi
You can change /usr/lib/Xorg for only Xorg or the proper command on your system.
You can use checkedTextView instead.
http://developer.android.com/reference/android/widget/CheckedTextView.html
You don't need the 'values' clause when using a 'select' as your source.
insert into table1 (col1, col2)
select t1.col1, t2.col2 from oldtable1 t1, oldtable2 t2;
You can use ->child
to get a child element named child.
This element will contain the text of the child element.
But if you try var_dump()
on that variable, you will see it is not actually a PHP string.
The easiest way around this is to perform a strval(xml->child);
That will convert it to an actual PHP string.
This is useful when debugging when looping your XML and using var_dump()
to check the result.
So $s = strval($xml->child);
.
df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
does already return a dataframe, so you cannot loop over the groups anymore.
In general:
df.groupby(...)
returns a GroupBy
object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:
grouped = df.groupby('A')
for name, group in grouped:
...
When you apply a function on the groupby, in your example df.groupby(...).agg(...)
(but this can also be transform
, apply
, mean
, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).
If you use instanceof
, making your equals
implementation final
will preserve the symmetry contract of the method: x.equals(y) == y.equals(x)
. If final
seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object
class.
It's as easy as:
DECLARE @rv FLOAT;
SELECT @rv = rand();
And this will put a random number between 0-99 into a table:
CREATE TABLE R
(
Number int
)
DECLARE @rv FLOAT;
SELECT @rv = rand();
INSERT INTO dbo.R
(Number)
values((@rv * 100));
SELECT * FROM R
My solution is for colleagues who needs to make changes in config before launching docker-entrypoint-initdb.d
I was needed to change 'shared_preload_libraries' setting so during it's work postgres already has new library preloaded and code in docker-entrypoint-initdb.d can use it.
So I just patched postgresql.conf.sample file in Dockerfile:
RUN echo "shared_preload_libraries='citus,pg_cron'" >> /usr/share/postgresql/postgresql.conf.sample
RUN echo "cron.database_name='newbie'" >> /usr/share/postgresql/postgresql.conf.sample
And with this patch it become possible to add extension in .sql file in docker-entrypoint-initdb.d/:
CREATE EXTENSION pg_cron;
Another way:
li:before {
content: '\2014\00a0\00a0'; /* em-dash followed by two non-breaking spaces*/
}
li {
list-style: none;
text-indent: -1.5em;
padding-left: 1.5em;
}
Way to unlock the user :
$ sqlplus /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;
and open new terminal
SQL > sqlplus / as sysdba
connected
SQL > conn username/password //which username u gave before unlock
password:password
password:password
class Animal:
HUGE = "Huge"
BIG = "Big"
class Horse:
def printSize(self):
print(Animal.HUGE)
I have posted this as a separate answer as it is unrelated to my existing answer.
This issue recently cropped up again for accessing a parent from an iframe referencing a subdomain and the existing fixes did not work.
This time the answer was to modify the document.domain of the parent page and the iframe to be the same. This will fool the same origin policy checks into thinking they co-exist on exactly the same domain (subdomains are considered a different host and fail the same origin policy check).
Insert the following to the <head>
of the page in the iframe to match the parent domain (adjust for your doctype).
<script>
document.domain = "mydomain.com";
</script>
Please note that this will throw an error on localhost development, so use a check like the following to avoid the error:
if (!window.location.href.match(/localhost/gi)) {
document.domain = "mydomain.com";
}
Assuming that your branch was created off of master
, then while in the branch (that is, you have the branch checked out):
git cherry -v master
or
git log master..
If you are not in the branch, then you can add the branch name to the "git log" command, like this:
git log master..branchname
If your branch was made off of origin/master
, then say origin/master
instead of master
.
In a class you might call it like this:
public static string GetIPAddress(HttpRequestBase request)
{
string ip;
try
{
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
if (ip.IndexOf(",") > 0)
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
ip = ipRange[le];
}
} else
{
ip = request.UserHostAddress;
}
} catch { ip = null; }
return ip;
}
I used this in a razor app with great results.
Okay, redis is pretty user friendly but there are some gotchas.
Here are just some easy commands for working with redis on Ubuntu:
install:
sudo apt-get install redis-server
start with conf:
sudo redis-server <path to conf>
sudo redis-server config/redis.conf
stop with conf:
redis-ctl shutdown
(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)
log:
tail -f /var/log/redis/redis-server.log
Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:
/etc/redis/redis.conf
Then paste it at <path to conf>
, tweak as needed and you're good to go.
Add the below to your manifest:
<activity android:name=".AppPreferenceActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>