Try installing
psycopg2-binary
with
pip install psycopg2-binary --user
Edit /etc/yum.repos.d/Centos*
so that all lines that have enabled = 0
instead have enabled = 1
.
SWIFT 2.0
var tempJson : NSString = ""
do {
let arrJson = try NSJSONSerialization.dataWithJSONObject(arrInvitationList, options: NSJSONWritingOptions.PrettyPrinted)
let string = NSString(data: arrJson, encoding: NSUTF8StringEncoding)
tempJson = string! as NSString
}catch let error as NSError{
print(error.description)
}
NOTE:- use tempJson variable when you want to use.
Try this:
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Tempo"
End Sub
Or use a With
clause to avoid repeatedly calling out your object
Private Sub CreateSheet()
Dim ws As Worksheet
With ThisWorkbook
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
ws.Name = "Tempo"
End With
End Sub
Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.
Sub CreateSheet()
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
End With
End Sub
As of 3/10/2019, Anguar dropped the support of sass. No mater what option you passed to --style
when running ng new
, you always get .scss
files generated. It's a shame that sass support was dropped without any explanation.
"1" + "2" + "3"
or
["1", "2", "3"].join("")
The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string (""
).
parseInt("123")
Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)
123 + 100
(223).toString()
(parseInt("1" + "2" + "3") + 100).toString()
or
(parseInt(["1", "2", "3"].join("")) + 100).toString()
Use String.fromCharCode
. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.
var a = String.fromCharCode(97);
Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)
<table id="tableHeader" class="table" style="table-layout:fixed">
<thead>
<tr>
<th>Col1</th>
...
</tr>
</thead>
</table>
<div style="overflow-y:auto;">
<table id="tableData" class="table table-condensed" style="table-layout:fixed">
<tbody>
<tr>
<td>data</td>
...
</tr>
</tbody>
</table>
</div>
The content table div needs overflow-y:auto
, for vertical scroll bars. Had to use table-layout:fixed
, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.
Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.
// ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
$(function () {
//copy width of header cells to match width of cells with data
//so they line up properly
var tdHeader = document.getElementById("tableHeader").rows[0].cells;
var tdData = document.getElementById("tableData").rows[0].cells;
for (var i = 0; i < tdData.length; i++)
tdHeader[i].style.width = tdData[i].offsetWidth + 'px';
});
You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
display: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
_x000D_
nav.main ul li:hover ul {_x000D_
display: block;_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
animation: fade 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a></li>_x000D_
<li><a href="">Dolor</a></li>_x000D_
<li><a href="">Sit</a></li>_x000D_
<li><a href="">Amet</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Here is an update on your fiddle. https://jsfiddle.net/orax9d9u/1/
window.location
isn't a String, but it has a toString()
method. So you can do it like this:
(''+window.location).includes("franky")
or
window.location.toString().includes("franky")
From the old Mozilla docs:
Location objects have a toString method returning the current URL. You can also assign a string to window.location. This means that you can work with window.location as if it were a string in most cases. Sometimes, for example when you need to call a String method on it, you have to explicitly call toString.
var text = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);
This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().
I would like to add one more reliable way using UsedRange
to find the last used row:
lastRow = Sheet1.UsedRange.Row + Sheet1.UsedRange.Rows.Count - 1
Similarly to find the last used column you can see this
Result in Immediate Window:
?Sheet1.UsedRange.Row+Sheet1.UsedRange.Rows.Count-1
21
Try this :
var data =(from t1 in dataContext.Table1 join
t2 in dataContext.Table2 on
t1.field equals t2.field
orderby t1.Id select t1).ToList();
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($nested_object), true);
I have used JetBrains dotTrace and Redgate ANTS extensively. They are fairly similar in features and price. They both offer useful performance profiling and quite basic memory profiling.
dotTrace integrates with Resharper, which is really convenient, as you can profile the performance of a unit test with one click from the IDE. However, dotTrace often seems to give spurious results (e.g. saying that a method took several years to run)
I prefer the way that ANTS presents the profiling results. It shows you the source code and to the left of each line tells you how long it took to run. dotTrace just has a tree view.
EQATEC profiler is quite basic and requires you to compile special instrumented versions of your assemblies which can then be run in the EQATEC profiler. It is, however, free.
Overall I prefer ANTS for performance profiling, although if you use Resharper then the integration of dotTrace is a killer feature and means it beats ANTS in usability.
The free Microsoft CLR Profiler (.Net framework 2.0 / .Net Framework 4.0) is all you need for .NET memory profiling.
2011 Update:
The Scitech memory profiler has quite a basic UI but lots of useful information, including some information on unmanaged memory which dotTrace and ANTS lack - you might find it useful if you are doing COM interop, but I have yet to find any profiler that makes COM memory issues easy to diagnose - you usually have to break out windbg.exe
.
The ANTS profiler has come on in leaps and bounds in the last few years, and its memory profiler has some truly useful features which now pushed it ahead of dotTrace as a package in my estimation. I'm lucky enough to have licenses for both, but if you are going to buy one .Net profiler for both performance and memory, make it ANTS.
I higly recomend http-request built on apache http api.
For your case you can see example:
private static final HttpRequest<String.class> HTTP_REQUEST =
HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer())
.build();
public void sendRequest(String request){
String parameters = request.split("\\?")[1];
ResponseHandler<String> responseHandler =
HTTP_REQUEST.executeWithQuery(parameters);
System.out.println(responseHandler.getStatusCode());
System.out.println(responseHandler.get()); //prints response body
}
If you are not interested in the response body
private static final HttpRequest<?> HTTP_REQUEST =
HttpRequestBuilder.createPost("http://example.com/index.php").build();
public void sendRequest(String request){
ResponseHandler<String> responseHandler =
HTTP_REQUEST.executeWithQuery(parameters);
}
For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java
You can use URL Encoding Functions PHP has the
rawurlencode()
function
ASP has the
Server.URLEncode()
function
In JavaScript you can use the
encodeURIComponent()
function.
This is not possible; pseudo-elements are not part of the DOM at all so you can't bind any events directly to them, you can only bind to their parent elements.
If you must have a click handler on the red region only, you have to make a child element, like a span
, place it right after the opening <p>
tag, apply styles to p span
instead of p:before
, and bind to it.
You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)
>>> for field, values in fields.iteritems():
... print field, values
...
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']
Your problem was that you were looping over fields, which returns the keys of the dictionary.
>>> for field in fields:
... print field
...
first_names
last_name
There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?
Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:\YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf'
Is there a specific reason you want to use FileNameExtensionFilter
? I know this works..
private File[] getNewTextFiles() {
return dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
}
Here a solution with less line of code and easily understandable (or at least I like to think so).
If you want to keep order (match only if the smaller list is found in the same order on the bigger list):
def is_ordered_subset(l1, l2):
# First check to see if all element of l1 are in l2 (without checking order)
if not set(l1).issubset(l2):
return False
length = len(l1)
# Make sublist of same size than l1
list_of_sublist = [l2[i:i+length] for i, x in enumerate(l2)]
#Check if one of this sublist is l1
return l1 in list_of_sublist
This works for me:
File file = new File("c:\\myjar.jar");
URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");
I've found that this can happen due to a number of various reasons.
In my case when I scroll to the end of the SQL import "Report", under the "Post-execute (Success)" heading it will tell me how many rows were copied and it's usually the next row in sheet which has the issue. Also you can tell which column by the import messages (in your case it was "Copy of F2") so you can generally find out which was the offending cell in Excel.
I've seen this happen for very silly reasons such as the date format in Excel being different than previous rows. For example cell A2 being "05/02/2017" while A3 being "5/2/2017" or even "05-02-2017". It seems the import wants things to be perfectly consistent.
It even happens if the Excel formats are different so if B2 is "512" but an Excel "Number" format and B3 is "512" but an Excel "Text" format then the Cell will cause an error.
I've also had situations where I literally had to delete all the "empty" rows below my data rows in the Excel sheet. Sometimes they appear empty but Excel considers them having "blank" data or something like that so the import tries to import them as well. This usually happens if you've had previous data in your Excel sheet which you've cleared but haven't properly deleted the rows.
And then there's the obvious reasons of trying to import text value into an integer column or insert a NULL into a NOT NULL column as mentioned by the others.
func decorateText(sub:String, des:String)->NSAttributedString{
let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.darkText, NSAttributedStringKey.font: UIFont(name: "PTSans-Bold", size: 17.0)!]
let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont(name: "PTSans-Regular", size: 14.0)!]
let textPartOne = NSMutableAttributedString(string: sub, attributes: textAttributesOne)
let textPartTwo = NSMutableAttributedString(string: des, attributes: textAttributesTwo)
let textCombination = NSMutableAttributedString()
textCombination.append(textPartOne)
textCombination.append(textPartTwo)
return textCombination
}
//Implementation
cell.lblFrom.attributedText = decorateText(sub: sender!, des: " - \(convertDateFormatShort3(myDateString: datetime!))")
Some of the links provided are only settings for Windows 2003's version of "Scheduled Tasks"
In Windows Server 2008 the "Tasks" setup only has a box with options for "5 Minutes, 10 minutes, 15 minutes, 30 mins, and 1 hour" (screen shot: http://i46.tinypic.com/2gwx7r8.jpg)... where the Window 2003 was a "enter whatever number you want" textbox.
I thought doing an "Export" and editing the XML from: PT30M to PT2M
and importing that as a new task would "trick" Tasks into repeating every 2 mins, but it didn't like that
My workaround for getting a task to run every 2 mins in Windows 2008 was to (ugggh) setup 30 different "triggers" for my task repeating every hour but staring at :00, :02, :04, :06 and so on and so on.... took me 8-10 mins to setup but I only had to do it once :-)
I know this question has been answered, but just to point out what timeit
has to say about the solutions efficiency. Using these parameters:
size = 30
s = [str(random.randint(0, 9)) for i in range(size)] + (size/3) * ['-']
random.shuffle(s)
s = ''.join(['+'] + s)
timec = 1000
That is the "phone number" has 30 digits, 1 plus sing and 10 '-'. I've tested these approaches:
def justdigits(s):
justdigitsres = ""
for char in s:
if char.isdigit():
justdigitsres += str(char)
return justdigitsres
re_compiled = re.compile(r'\D')
print('Filter: %ss' % timeit.Timer(lambda : ''.join(filter(str.isdigit, s))).timeit(timec))
print('GE: %ss' % timeit.Timer(lambda : ''.join(n for n in s if n.isdigit())).timeit(timec))
print('LC: %ss' % timeit.Timer(lambda : ''.join([n for n in s if n.isdigit()])).timeit(timec))
print('For loop: %ss' % timeit.Timer(lambda : justdigits(s)).timeit(timec))
print('RE: %ss' % timeit.Timer(lambda : re.sub(r'\D', '', s)).timeit(timec))
print('REC: %ss' % timeit.Timer(lambda : re_compiled.sub('', s)).timeit(timec))
print('Translate: %ss' % timeit.Timer(lambda : s.translate(None, '+-')).timeit(timec))
And came out with these results:
Filter: 0.0145790576935s
GE: 0.0185861587524s
LC: 0.0151798725128s
For loop: 0.0242128372192s
RE: 0.0120108127594s
REC: 0.00868797302246s
Translate: 0.00118899345398s
Apparently GEs and LCs are still slower than a regex or a compiled regex. And apparently my CPython 2.6.6 didn't optimize the string addition that much. translate
appears to be the fastest (which is expected as the problem is stated as "ignore these two symbols", rather than "get these numbers" and I believe is quite low-level).
And for size = 100
:
Filter: 0.0357120037079s
GE: 0.0465779304504s
LC: 0.0428011417389s
For loop: 0.0733139514923s
RE: 0.0213229656219s
REC: 0.0103371143341s
Translate: 0.000978946685791s
And for size = 1000
:
Filter: 0.212141036987s
GE: 0.198996067047s
LC: 0.196880102158s
For loop: 0.365696907043s
RE: 0.0880808830261s
REC: 0.086804151535s
Translate: 0.00587010383606s
This is my version of a bash script. It takes database name as a parameter and converts all tables to another charset and collation (given by another parameters or default value defined in the script).
#!/bin/bash
# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables
DB="$1"
CHARSET="$2"
COLL="$3"
[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"
echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql
echo "USE $DB; SHOW TABLES;" | mysql -s | (
while read TABLE; do
echo $DB.$TABLE
echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
done
)
If the week number is in A1
and the year in A2
, you can try:
A1*7+DATE(A2,1,1)
Simple, you just open klik file -> import -> General -> existing project into workspace -> browse file in your directory.
(I'am used Eclipse Mars)
Well so far this is the best I could come up with.
It uses the ISBLANK
function to check if the cell is truly empty within an IF
statement.
If there is anything in the cell, A1
in this example, even a SPACE character, then the cell is not
EMPTY
and the calculation will result.
This will keep the calculation errors from showing until you have numbers to work with.
If the cell is EMPTY
then the calculation cell will not display the errors from the calculation.If the cell is NOT EMPTY
then the calculation results will be displayed.
This will throw an error if your data is bad, the dreaded #DIV/0
!
=IF(ISBLANK(A1)," ",STDEV(B5:B14))
Change the cell references and formula as you need to.
Since it wasn't mentioned, you can also use the CSS white-space property
body{
white-space:pre-wrap;
}
Which tells the browser to preserve whitespace so that
<body>
<?php
echo "hello\nthere";
?>
</body>
Would display
hello
there
%hash = map { $_ => 1 } @array;
It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.
What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.
If using jQuery is an option:
/**
* Trim the site input[type=text] fields globally by removing any whitespace from the
* beginning and end of a string on input .blur()
*/
$('input[type=text]').blur(function(){
$(this).val($.trim($(this).val()));
});
or simply:
$.trim(string);
I am using this function:
public static int[][] copy(final int[][] array) {
if (array != null) {
final int[][] copy = new int[array.length][];
for (int i = 0; i < array.length; i++) {
final int[] row = array[i];
copy[i] = new int[row.length];
System.arraycopy(row, 0, copy[i], 0, row.length);
}
return copy;
}
return null;
}
The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:
final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };
Try this lets say your form id is formID
$(".nextbutton").click(function() { $("form#formID").submit(); });
check if string(word/sentence...) contains specific word/character
if ( "write something here".indexOf("write som") > -1 ) { alert( "found it" ); }
Also, make sure when you write the query involving the linked server, you include brackets like this:
SELECT * FROM [LinkedServer].[RemoteDatabase].[User].[Table]
I've found that at least on 2000/2005 the [] brackets are necessary, at least around the server name.
try this
single function for all radio have class "radio-button"
work in chrome and FF
$('.radio-button').on("click", function(event){_x000D_
$('.radio-button').prop('checked', false);_x000D_
$(this).prop('checked', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
I searched for a simple solution and this works well for me:
//input data
view = new Uint8Array(data);
//output string
serialString = ua2text(view);
//convert UTF8 to string
function ua2text(ua) {
s = "";
for (var i = 0; i < ua.length; i++) {
s += String.fromCharCode(ua[i]);
}
return s;
}
Only issue I have is sometimes I get one character at a time. This might be by design with my source of the arraybuffer. I'm using https://github.com/xseignard/cordovarduino to read serial data on an android device.
You can use this javascript plugin
https://github.com/biggora/device-uuid
It can get a large list of information for you about mobiles and desktop machines including the uuid for example
var uuid = new DeviceUUID().get();
e9dc90ac-d03d-4f01-a7bb-873e14556d8e
var dua = [
du.language,
du.platform,
du.os,
du.cpuCores,
du.isAuthoritative,
du.silkAccelerated,
du.isKindleFire,
du.isDesktop,
du.isMobile,
du.isTablet,
du.isWindows,
du.isLinux,
du.isLinux64,
du.isMac,
du.isiPad,
du.isiPhone,
du.isiPod,
du.isSmartTV,
du.pixelDepth,
du.isTouchScreen
];
Alternative approach using npm-upgrade:
npm i -g npm-upgrade
Go to your project folder
npm-upgrade check
It will ask you if you wish to upgrade the package, select Yes
That's simple
It sounds like you want to convert the rownames to a proper column of the data.frame. eg:
# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF
# Row.Names id val vr2
# row_one row_one A 1 23
# row_two row_two A 2 24
# row_three row_three B 3 25
# row_four row_four C 4 26
If you want to then remove the original rownames:
rownames(myDF) <- NULL
myDF
# Row.Names id val vr2
# 1 row_one A 1 23
# 2 row_two A 2 24
# 3 row_three B 3 25
# 4 row_four C 4 26
Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames
myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat
# Names.of.Rows id val vr2
# row_one "A" "1" "23"
# row_two "A" "2" "24"
# row_three "B" "3" "25"
# row_four "C" "4" "26"
Wrap them in an extra pair of parens and you're good to go.
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
Create Spliterator
from Iterator
using Spliterators
class contains more than one function for creating spliterator, for example here am using spliteratorUnknownSize
which is getting iterator as parameter, then create Stream using StreamSupport
Spliterator<Model> spliterator = Spliterators.spliteratorUnknownSize(
iterator, Spliterator.NONNULL);
Stream<Model> stream = StreamSupport.stream(spliterator, false);
You can also use the void operator to obtain an undefined value:
if (input !== void 0) {
// do stuff
}
(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0
for testing global variables or adding var input
.)
I have some documents where …
was showing as …
and ê
was showing as ê
. This is how it got there (python code):
# Adam edits original file using windows-1252
windows = '\x85\xea'
# that is HORIZONTAL ELLIPSIS, LATIN SMALL LETTER E WITH CIRCUMFLEX
# Beth reads it correctly as windows-1252 and writes it as utf-8
utf8 = windows.decode("windows-1252").encode("utf-8")
print(utf8)
# Charlie reads it *incorrectly* as windows-1252 writes a twingled utf-8 version
twingled = utf8.decode("windows-1252").encode("utf-8")
print(twingled)
# detwingle by reading as utf-8 and writing as windows-1252 (it's really utf-8)
detwingled = twingled.decode("utf-8").encode("windows-1252")
assert utf8==detwingled
To fix the problem, I used python code like this:
with open("dirty.html","rb") as f:
dt = f.read()
ct = dt.decode("utf8").encode("windows-1252")
with open("clean.html","wb") as g:
g.write(ct)
(Because someone had inserted the twingled version into a correct UTF-8 document, I actually had to extract only the twingled part, detwingle it and insert it back in. I used BeautifulSoup for this.)
It is far more likely that you have a Charlie in content creation than that the web server configuration is wrong. You can also force your web browser to twingle the page by selecting windows-1252 encoding for a utf-8 document. Your web browser cannot detwingle the document that Charlie saved.
Note: the same problem can happen with any other single-byte code page (e.g. latin-1) instead of windows-1252.
Here's a one-liner using Maven:
mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38
Then, with default settings, it's available in:
$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar
Just replace the version number if you need a different one.
go to manage clinet page in :
http://www.instagram.com/developer/
set a redirect url
then :
use this code to get access token :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>tst</title>
<script src="../jq.js"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'https://api.instagram.com/oauth/authorize/?client_id=CLIENT-??ID&redirect_uri=REDI?RECT-URI&response_ty?pe=code'
dataType: 'jsonp'}).done(function(response){
var access = window.location.hash.substring(14);
//you have access token in access var
});
</script>
</head>
<body>
</body>
</html>
You are just missing the first argument to connect
, which is the mapStateToProps
method. Excerpt from the Redux todo app:
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
Although the tricky solution @tbaxter120 advised is good but I use this function and work like a charm, pString is a delimited string and pDelimiter is a delimiter character:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[DelimitedSplit]
--===== Define I/O parameters
(@pString NVARCHAR(MAX), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL -- does away with 0 base CTE, and the OR condition in one go!
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
---ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,50000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(@pString, l.N1, l.L1)
FROM cteLen l
;
Then for example you can call it in where clause as below:
WHERE [fieldname] IN (SELECT LTRIM(RTRIM(Item)) FROM [dbo].[DelimitedSplit]('2,5,11', ','))
Hope this help.
Actually you don't need gem for this, here is the step to install Bootstrap 3 in RoR
Download Bootstrap
Copy:
bootstrap-dist/css/bootstrap.css
and bootstrap-dist/css/bootstrap.min.css
To: vendor/assets/stylesheets
Copy:
bootstrap-dist/js/bootstrap.js
and bootstrap-dist/js/bootstrap.min.js
To: vendor/assets/javascripts
Update: app/assets/stylesheets/application.css
by adding:
*= require bootstrap.min
Update: app/assets/javascripts/application.js
by adding:
//= require bootstrap.min
With this you can update bootstrap any time you want, don't need to wait gem to be updated. Also with this approach assets pipeline will use minified versions in production.
But from what I understand xs:choice still only allows single element selection. Hence setting the MaxOccurs to unbounded like this should only mean that "any one" of the child elements can appear multiple times. Is this accurate?
No. The choice happens individually for every "repetition" of xs:choice
that occurs due to maxOccurs="unbounded"
. Therefore, the code that you have posted is correct, and will actually do what you want as written.
Please double check that jenkins is not blocking this import. Go to script approvals and check to see if it is blocking it. If it is click allow.
This can also be a issue when you enter wrong password for your sign key.
You have to check which Python you are using. I had the same problem because the Python I was using was not the same one that brew was using. In your command line:
which python
which brew
cd /usr/local/lib/python2.7/site-packages
ls
//you can see PyQt4 and sip are hereusr/local/lib/python2.7/site-packages
to your python path.open ~/.bash_profile
//you will open your bash_profile file in your editor'export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH'
to your bash file and save itpython
import PyQt4
// it is ok nowWe can also use ngClass to assign multiple CSS classes based on multiple conditions as below:
<div
[ngClass]="{
'class-name': trueCondition,
'other-class': !trueCondition
}"
></div>
You can insert the animated image into the DOM right before the AJAX call, and do an inline function to remove it...
$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />');
$('#message').load('index.php?pg=ajaxFlashcard', null, function() {
$("#myDiv").html('');
});
This will make sure your animation starts at the same frame on subsequent requests (if that matters). Note that old versions of IE might have difficulties with the animation.
Good luck!
When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.
There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
When the view is not loaded yet, you cannot scroll. You can do it 'later' with a post or sleep call as above, but this is not very elegant.
It is better to plan the scroll and do it on the next onLayout(). Example code here:
For Windows 10 64bit:
I have tried all the suggestions here, but finally got it running as follows:
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
You can submit the regex to preg_match
which will return false if the regex is not valid. Don't forget to use the @
to suppress error messages:
@preg_match($regexToTest, '');
//
. If selection is not important, it is better to use an ItemsControl wrapped in a ScrollViewer. This combination is more light-weight than the Listbox (which actually is derived from ItemsControl already) and using it would eliminate the need to use a cheap hack to override behavior that is already absent from the ItemsControl.
In cases where the selection behavior IS actually important, then this obviously will not work. However, if you want to change the color of the Selected Item Background in such a way that it is not visible to the user, then that would only serve to confuse them. In cases where your intention is to change some other characteristic to indicate that the item is selected, then some of the other answers to this question may still be more relevant.
Here is a skeleton of how the markup should look:
<ScrollViewer>
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
First thing printStackTrace() is not expensive as you state, because the stack trace is filled when the exception is created itself.
The idea is to pass anything that goes to logs through a logger framework, so that the logging can be controlled. Hence instead of using printStackTrace, just use something like Logger.log(msg, exception);
This usually occurs because either of the following are true:
Try getting some information about the certificate of the server and see if you need to install any specific certs on your client to get it to work.
Try something like this utilizing oneOfType
or PropTypes.node
import PropTypes from 'prop-types'
...
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired
}
or
static propTypes = {
children: PropTypes.node.isRequired,
}
The .bashrc file is in your home directory.
So from command line do:
cd
ls -a
This will show all the hidden files in your home directory. "cd" will get you home and ls -a will "list all".
In general when you see ~/ the tilda slash refers to your home directory. So ~/.bashrc is your home directory with the .bashrc file.
And the standard path to homebrew is in /usr/local/ so if you:
cd /usr/local
ls | grep -i homebrew
you should see the homebrew directory (/usr/local/homebrew). Source
Yes sometimes you may have to create this file and the typical format of a .bashrc file is:
# .bashrc
# User specific aliases and functions
. .alias
alias ducks='du -cks * | sort -rn | head -15'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
PATH=$PATH:/home/username/bin:/usr/local/homebrew
export PATH
If you create your own .bashrc file make sure that the following line is in your ~/.bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
HTML doesn't have a built-in editable dropdown list or combobox, but I implemented a mostly-CSS solution in an article.
You can see a full demo here but in summary, write HTML like this:
<span class="combobox withtextlist">
<input value="Fruit">
<span tabindex="-1" class="downarrow"></span>
<select size="10" class="sticky">
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
<option>Dewberry</option>
</select>
</span>
And use CSS like this to style it (this is designed for both comboboxes, which have a down-arrow ? button, and dropdown menus which open when clicked and may be styled differently):
/* ------------------------------------------ */
/* ----- combobox / dropdown list styling */
/* ------------------------------------------ */
.combobox {
/* Border slightly darker than Chrome's <select>, slightly lighter than FireFox's */
border: 1px solid #999;
padding-right: 1.25em; /* leave room for ? */
}
.dropdown, .combobox {
/* "relative" and "inline-block" (or just "block") are needed
here so that "absolute" works correctly in children */
position: relative;
display: inline-block;
}
.combobox > .downarrow, .dropdown > .downarrow {
/* ? Outside normal flow, relative to container */
display: inline-block;
position: absolute;
top: 0;
bottom: 0;
right: 0;
width: 1.25em;
cursor: default;
nav-index: -1; /* nonfunctional in most browsers */
border-width: 0px; /* disable by default */
border-style: inherit; /* copy parent border */
border-color: inherit; /* copy parent border */
}
/* Add a divider before the ? down arrow in non-dropdown comboboxes */
.combobox:not(.dropdown) > .downarrow {
border-left-width: 1px;
}
/* Auto-down-arrow if one is not provided */
.downarrow:empty::before {
content: '?';
}
.downarrow::before, .downarrow > *:only-child {
text-align: center;
/* vertical centering trick */
position: relative;
top: 50%;
display: block; /* transform requires block/inline-block */
transform: translateY(-50%);
}
.combobox > input {
border: 0
}
.dropdown > *:last-child,
.combobox > *:last-child {
/* Using `display:block` here has two desirable effects:
(1) Accessibility: it lets input widgets in the dropdown to
be selected with the tab key when the dropdown is closed.
(2) It lets the opacity transition work.
But it also makes the contents visible, which is undesirable
before the list drops down. To compensate, use `opacity: 0`
and disable mouse pointer events. Another side effect is that
the user can select and copy the contents of the hidden list,
but don't worry, the selected content is invisible. */
display: block;
opacity: 0;
pointer-events: none;
transition: 0.4s; /* fade out */
position: absolute;
left: 0;
top: 100%;
border: 1px solid #888;
background-color: #fff;
box-shadow: 1px 2px 4px 1px #666;
box-shadow: 1px 2px 4px 1px #4448;
z-index: 9999;
min-width: 100%;
box-sizing: border-box;
}
/* List of situations in which to show the dropdown list.
- Focus dropdown or non-last child of it => show last-child
- Focus .downarrow of combobox => show last-child
- Stay open for focus in last child, unless .less-sticky
- .sticky last child stays open on hover
- .less-sticky stays open on hover, ignores focus in last-child */
.dropdown:focus > *:last-child,
.dropdown > *:focus ~ *:last-child,
.combobox > .downarrow:focus ~ *:last-child,
.combobox > .sticky:last-child:hover,
.dropdown > .sticky:last-child:hover,
.combobox > .less-sticky:last-child:hover,
.dropdown > .less-sticky:last-child:hover,
.combobox > *:last-child:focus:not(.less-sticky),
.dropdown > *:last-child:focus:not(.less-sticky) {
display: block;
opacity: 1;
transition: 0.15s;
pointer-events: auto;
}
/* focus-within not supported by Edge/IE. Unsupported selectors cause
the entire block to be ignored, so we must repeat all styles for
focus-within separately. */
.combobox > *:last-child:focus-within:not(.less-sticky),
.dropdown > *:last-child:focus-within:not(.less-sticky) {
display: block;
opacity: 1;
transition: 0.15s;
pointer-events: auto;
}
/* detect Edge/IE and behave if though less-sticky is on for all
dropdowns (otherwise links won't be clickable) */
@supports (-ms-ime-align:auto) {
.dropdown > *:last-child:hover {
display: block;
opacity: 1;
pointer-events: auto;
}
}
/* detect IE and do the same thing. */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.dropdown > *:last-child:hover {
display: block;
opacity: 1;
pointer-events: auto;
}
}
.dropdown:not(.sticky) > *:not(:last-child):focus,
.downarrow:focus, .dropdown:focus {
pointer-events: none; /* Causes second click to close */
}
.downarrow:focus {
outline: 2px solid #8BF; /* Edge/IE can't do outline transparency */
outline: 2px solid #48F8;
}
/* ---------------------------------------------- */
/* Optional extra styling for combobox / dropdown */
/* ---------------------------------------------- */
*, *:before, *:after {
/* See https://css-tricks.com/international-box-sizing-awareness-day/ */
box-sizing: border-box;
}
.combobox > *:first-child {
display: inline-block;
width: 100%;
box-sizing: border-box; /* so 100% includes border & padding */
}
/* `.combobox:focus-within { outline:...}` doesn't work properly
in Firefox because the focus box is expanded to include the
(possibly hidden) drop list. As a workaround, put focus box on
the focused child. It is barely-visible so that it doesn't look
TOO ugly if the child isn't the same size as the parent. It
may be uglier if the first child is not styled as width:100% */
.combobox > *:not(:last-child):focus {
outline: 2px solid #48F8;
}
.combobox {
margin: 5px;
}
You also need some JavaScript to synchronize the list with the textbox:
function parentComboBox(el) {
for (el = el.parentNode; el != null && Array.prototype.indexOf.call(el.classList, "combobox") <= -1;)
el = el.parentNode;
return el;
}
// Uses jQuery
$(".combobox.withtextlist > select").change(function() {
var textbox = parentComboBox(this).firstElementChild;
textbox.value = this[this.selectedIndex].text;
});
$(".combobox.withtextlist > select").keypress(function(e) {
if (e.keyCode == 13) // Enter pressed
parentComboBox(this).firstElementChild.focus(); // Closes the popup
});
Here is the swift 3 updated answer
var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0) Backslash (\\) Horizontal Tab (\t) Line Feed (\n) Carriage Return (\r) Double Quote (\") Single Quote (\') Unicode scalar (\u{n})
<target name="check-abc">
<available file="abc.txt" property="abc.present"/>
</target>
<target name="do-if-abc" depends="check-abc" if="abc.present">
...
</target>
Not possible without iterating to build a new list. You can wrap the list in a container that implements IList.
You can use LINQ to get a lazy evaluated version of IEnumerable<string>
from an object list like this:
var stringList = myList.OfType<string>();
You could do an SQLDump
of the database (and its data) then search that file.
copy the column paste it into notepad copy it again paste special as Text
jQuery will encode and decode for you. However, you need to use a textarea tag, not a div.
var str1 = 'One & two & three';_x000D_
var str2 = "One & two & three";_x000D_
_x000D_
$(document).ready(function() {_x000D_
$("#encoded").text(htmlEncode(str1)); _x000D_
$("#decoded").text(htmlDecode(str2));_x000D_
});_x000D_
_x000D_
function htmlDecode(value) {_x000D_
return $("<textarea/>").html(value).text();_x000D_
}_x000D_
_x000D_
function htmlEncode(value) {_x000D_
return $('<textarea/>').text(value).html();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="encoded"></div>_x000D_
<div id="decoded"></div>
_x000D_
merge into t2 t2
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
t2.c1 = t1.c1
, t2.c2 = t1.c2
date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM
Refer this link for other Formatters in DateTime.
In Android Studio we can get the repositories of svn using the VCS->Subversion and the extract the repository and work on the code
This is always fascinating. I am not a cloud developer, but based on my research there is nothing significantly different than what many of us have been doing off and on for decades. The server is platform specific. If you want to write platform agnostic code for your server that is fine, but unnecessary based on whoever your cloud server provider is. I think the biggest difference I've seen so far is the concept of providing a large set of services for the front end client to process. the front end, I'm assuming is predominantly web or web app development. As most browsers can handle LAMP vs Microsoft stack well enough, then you are still back to whatever your flavor of the month is. The only difference I truly am seeing from what I did 20 years ago in a highly distributed network environment are higher level protocol (HTTP vs. TCP/UDP). Maybe I am wrong and would welcome the education, but then again I've been doing this a long time and still have not seen anything I would consider revolutionary or significantly different, though languages like Java, C#, Python, Ruby, etc are significantly simpler to program in which is a mixed bag as the bar is lowered for those are are not familiar with writing optimized code. PAAS and SAAS to me seem to be some of the keys in the new technology, but been doing some of this to off and on for 20 years :)
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
You can return FileResult with this methods:
1: Return FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = fileName
};
}
2: Return FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
You can also use ...
spread syntax using forEach
something like this:
let obj = { a: 1, b: "b", c: undefined, d: null };
let cleanObj = {};
Object.keys(obj).forEach(val => {
const newVal = obj[val];
cleanObj = newVal ? { ...cleanObj, [val]: newVal } : cleanObj;
});
console.info(cleanObj);
You can do this pretty easily with Javascript+Jquery as below. If you want to exclude some column, just write an if statement inside the for loops to skip those columns. Hope this helps!
//Sample JSON 2D array_x000D_
var json = [{_x000D_
"Total": "34",_x000D_
"Version": "1.0.4",_x000D_
"Office": "New York"_x000D_
}, {_x000D_
"Total": "67",_x000D_
"Version": "1.1.0",_x000D_
"Office": "Paris"_x000D_
}];_x000D_
_x000D_
// Get Table headers and print_x000D_
for (var k = 0; k < Object.keys(json[0]).length; k++) {_x000D_
$('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');_x000D_
}_x000D_
_x000D_
// Get table body and print_x000D_
for (var i = 0; i < Object.keys(json).length; i++) {_x000D_
$('#table_content').append('<tr>');_x000D_
for (var j = 0; j < Object.keys(json[0]).length; j++) {_x000D_
$('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');_x000D_
}_x000D_
$('#table_content').append('</tr>');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<thead>_x000D_
<tr id="table_head">_x000D_
_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody id="table_content">_x000D_
_x000D_
</tbody>_x000D_
</table>
_x000D_
stripslashes(htmlspecialchars(JSON_DATA))
Simply cast your timestamp AS DATE
, like this:
SELECT CAST(tstamp AS DATE)
In other words, your statement would look like this:
SELECT SUM(transaction_amount)
FROM mytable
WHERE Card_No='123'
AND CAST(transaction_date AS DATE) = target_date
What is nice about CAST
is that it works exactly the same on most SQL engines (SQL Server, PostgreSQL, MySQL), and is much easier to remember how to use it.
Methods using CONVERT()
or TO_DATE()
are specific to each SQL engine and make your code non-portable.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.
This answer assumes you have some JavaScript that you don't want to convert to TypeScript, but you want to benefit from type checking with minimal changes to your .js
.
A .d.ts
file is very much like a C or C++ header file. Its purpose is to define an interface. Here is an example:
mashString.d.ts
/** Makes a string harder to read. */
declare function mashString(
/** The string to obscure */
str: string
):string;
export = mashString;
mashString.js
// @ts-check
/** @type {import("./mashString")} */
module.exports = (str) => [...str].reverse().join("");
main.js
// @ts-check
const mashString = require("./mashString");
console.log(mashString("12345"));
The relationship here is: mashString.d.ts
defines an interface, mashString.js
implements the interface and main.js
uses the interface.
To get the type checking to work you add // @ts-check
to your .js
files.
But this only checks that main.js
uses the interface correctly. To also ensure that mashString.js
implements it correctly we add /** @type {import("./mashString")} */
before the export.
You can create your initial .d.ts
files using tsc -allowJs main.js -d
then edit them as required manually to improve the type checking and documentation.
In most cases the implementation and interface have the same name, here mashString
. But you can have alternative implementations. For example we could rename mashString.js
to reverse.js
and have an alternative encryptString.js
.
Why don't you just make it easy and simple. If I need to know the number of days between today and say, March 10th, 2015, I can just enter the simple formula.
Lets say the static date is March 10th, 2015, and is in cell O5.
The formula to determine the number of days between today and O5 would be, =O5-Today()
Nothing fancy or DATEDIF stuff. Obviously, the cell where you type this formula in must have a data type of 'number'. Just type your date in normally in the reference cell, in this case O5.
For anyone having same error for the same reason in ADOS CI Build:
This question was the first I found when looking for help. I have an ADOS CI build pipeline where first Node.js tool installer task is used to install Node. Then npm task is used to install gulp (npm install -g gulp). Then the following Gulp task runs default-task from gulpfile.js. There's some gulp-sass stuff in it.
When I changed the Node.js tool to install 12.x latest node instead of an older one and the latest gulp version was 4.0.2. The result was the same error as described in the question.
What worked for me in this case was to downgrade node.js to latest 11.x version as was already suggested by Alphonse R. Dsouza and Aymen Yaseen. In this case though there's no need to use any commands they suggested, but rather just set the Node.js tool installer version spec to latest Node version from 11.x.
The exact version of Node.js that got installed and is working was 11.15.0. I didn't have to downgrade the Gulp.
Let's say you have a button with the text, "Click Me". What width should that button be?
First, you definitely don't want the button to be smaller than the text. Otherwise, the text would be clipped. This is the horizontal compression resistance priority.
Second, you don't want the button to be bigger than it needs to be. A button that looked like this, [ Click Me ], is obviously too big. You want the button to "hug" its contents without too much padding. This is the horizontal content hugging priority. For a button, it isn't as strong as the horizontal compression resistance priority.
You need to do
Update table_xpto
set column_xpto = x.xpto_New
,column2 = x.column2New
from table_xpto xpto
inner join table_xptoNew xptoNew ON xpto.bla = xptoNew.Bla
where <clause where>
If you need a better answer, you can give us more information :)
You can do this by using cors. cors will handle your CORS response
var cors = require('cors')
app.use(cors());
You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.
>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
3
>>> a
[1, 4, 5]
>>>
In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():
View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);
Now you can access your views via 'view' and cast them to your view type:
myImage = (ImageView) view.findViewById(R.id.my_image);
This is a simple MaxHeap
implementation based on heapq
. Though it only works with numeric values.
import heapq
from typing import List
class MaxHeap:
def __init__(self):
self.data = []
def top(self):
return -self.data[0]
def push(self, val):
heapq.heappush(self.data, -val)
def pop(self):
return -heapq.heappop(self.data)
Usage:
max_heap = MaxHeap()
max_heap.push(3)
max_heap.push(5)
max_heap.push(1)
print(max_heap.top()) # 5
first , you dont need to use a local assigment for your job, just check the above answer
second, its simple to use locals() and globals() to got the variables table and then change the value
check this sample code:
print [locals().__setitem__('x', 'Hillo :]'), x][-1]
if you need to change the add a global variable to your environ, try to replace locals() with globals()
python's list comp is cool but most of the triditional project dont accept this(like flask :[)
hope it could help
Just walk through all Files using Files.walkFileTree
(Java 7)
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("file: " + file);
return FileVisitResult.CONTINUE;
}
});
This error also occurs when you have enabled the SSL module (i.e. you have run e.g. a2enmod ssl
) but not yet enabled any SSL site entries (i.e you have not run e.g. a2ensite default-ssl
).
There isn't anything native to java that lets you do this like async/await keywords, but what you can do if you really want to is use a CountDownLatch. You could then imitate async/await by passing this around (at least in Java7). This is a common practice in Android unit testing where we have to make an async call (usually a runnable posted by a handler), and then await for the result (count down).
Using this however inside your application as opposed to your test is NOT what I am recommending. That would be extremely shoddy as CountDownLatch depends on you effectively counting down the right number of times and in the right places.
Git rebase is used to make the branching paths in history cleaner and repository structure linear.
It is also used to keep the branches created by you private, as after rebasing and pushing the changes to the server, if you delete your branch, there will be no evidence of branch you have worked on. So your branch is now your local concern.
After doing rebase we also get rid of an extra commit which we used to see if we do a normal merge.
And yes, one still needs to do merge after a successful rebase as the rebase command just puts your work on top of the branch you mentioned during rebase, say master, and makes the first commit of your branch as a direct descendant of the master branch. This means we can now do a fast forward merge to bring changes from this branch to the master branch.
You can also get value by name instead of id like this:
var message = $('textarea:input[name=message]').val();
You have to increase client_max_body_size in nginx.conf
file. This is the basic step. But if your backend laravel
then you have to do some changes in the php.ini
file as well. It depends on your backend. Below I mentioned file location and condition name.
sudo vim /etc/nginx/nginx.conf.
After open the file adds this into HTTP section.
client_max_body_size 100M;
As stated from David Cournapeau, use figure().
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
Or subplot(121) / subplot(122) for the same plot, different position.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:
// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");
For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open
options for customization.
Update:
You would need something along:
$(document).ready(function() {
$(".product-item").click(function() {
var productLink = $(this).find("a");
productLink.attr("target", "_blank");
window.open(productLink.attr("href"));
return false;
});
});
Note the usage of .attr()
:
$element.attr("attribute_name") // Get value of attribute.
$element.attr("attribute_name", attribute_value) // Set value of attribute.
url ='http://www.test.com/page/TEST2'.split('/')[4]
print url
Output: TEST2
.
The following will do the trick
void splitNumber(std::list<int>& digits, int number) {
if (0 == number) {
digits.push_back(0);
} else {
while (number != 0) {
int last = number % 10;
digits.push_front(last);
number = (number - last) / 10;
}
}
}
Vanilla R has a naive difftime class, but the Lubridate CRAN package lets you do what you ask:
require(lubridate)
d <- ymd(as.Date('2004-01-01')) %m+% months(1)
d
[1] "2004-02-01"
Hope that helps.
I've written my own little extension for toggleText. It may come in handy.
Fiddle: https://jsfiddle.net/b5u14L5o/
jQuery Extension:
jQuery.fn.extend({
toggleText: function(stateOne, stateTwo) {
return this.each(function() {
stateTwo = stateTwo || '';
$(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo)
: $(this).text(stateOne);
});
}
});
Usage:
...
<button>Unknown</button>
...
//------- BEGIN e.g. 1 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText('Show', 'Hide'); // Hide, Show, Hide ... and so on.
});
//------- END e.g. 1 -------
//------- BEGIN e.g. 2 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText('Unknown', 'Hide'); // Hide, Unknown, Hide ...
});
//------- END e.g. 2 -------
//------- BEGIN e.g. 3 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText(); // Unknown, Unknown, Unknown ...
});
//------- END e.g.3 -------
//------- BEGIN e.g.4 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText('Show'); // '', Show, '' ...
});
//------- END e.g.4 -------
I think you can use Step 1: Select text Step 2: Ctrl + Shift + P Step 3: Enter Uppercae
HashMap<String,Integer> hm = new HashMap();
hm.put("A",1);
hm.put("B",2);
hm.put("C",3);
hm.put("D",4);
hm.forEach((key,value)->{
System.out.println("Key: "+key + " value: "+value);
});
Starting Mongo 4.2
, db.collection.update()
can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:
// { firstName: "Hello", lastName: "World" }
db.collection.update(
{},
[{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }],
{ multi: true }
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
The first part {}
is the match query, filtering which documents to update (in our case all documents).
The second part [{ $set: { name: { ... } }]
is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set
is a new aggregation operator and an alias of $addFields
.
Don't forget { multi: true }
, otherwise only the first matching document will be updated.
Somehow exiting Visual Studio and re-opening it solved this for me.
_splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w
This is Windows (Platform SDK) only
I'm coming at this from C#, but should be very similar in vb.net.
In your main program file, in the Main method, you will have something like:
Application.Run(new MainForm());
This creates a new main form and limits the lifetime of the application to the lifetime of the main form.
However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.
Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show()
or Form.Hide()
from handlers of NotifyIcon events will show and hide the form respectively.
If this is for debugging purposes, I would advise you use a JavaScript debugger such as Firebug. It will let you view the entire contents of arrays and much more, including modifying array entries and stepping through code.
I'm assuming you want to store the interestKeys in a list.
Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
Try this:
colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
Right now, there is no option to select the parent of an element in CSS (not even CSS3). But with CSS4, the most important news in the current W3C draft is the support for the parent selector.
$ul li:hover{
background: #fff;
}
Using the above, when hovering an list element, the whole unordered list will be highlighted by adding a white background to it.
Official documentation: https://www.w3.org/TR/2011/WD-selectors4-20110929/#overview (last row).
In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").
Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).
Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.
HTH.
Give your body
tag an overflow: scroll;
body {
overflow: scroll;
}
or if you only want a vertical scrollbar use overflow-y
body {
overflow-y: scroll;
}
You must group both columns, group and sub-group, then use the aggregate function COUNT()
.
SELECT
group, subgroup, COUNT(*)
FROM
groups
GROUP BY
group, subgroup
You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.
A previous reply to this question has given a great explanation of what the various types are.
You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.
http://www.softwareverify.com/cpp/memory/index.html
Disclaimer: I designed Memory Validator.
Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.
My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.
At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.
First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox
style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.
<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox
in a different name. So let's look at that parent style.
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">@android:drawable/btn_check_label_background</item>
<item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>
This style references both a background and button drawable. btn_check_label_background
is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple
indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox
.
As listChoiceIndicatorMultiple
is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):
<style name="Theme">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
...
</style>
<style name="Theme.Holo">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
...
</style>
<style name="Theme.Holo.Light" parent="Theme.Light">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
...
</style>
So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple
attribute, the actual appearance of the CheckBox
is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo
, you will always get the CheckBox
appearance matching the theme.
Now, if you want to change your CheckBox
's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.
As for your second question:
Also can you set styles to individual widgets if you set a style to the application?
Absolutely, and they will override any activity- or application-set styles.
Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?
Update:
Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.
However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:
int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);
The first line will actually return the resource id of the btn_check_holo_light
drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox
, we can set it as 'button drawable' on the widget. The result is a CheckBox
with the appearance of the Holo.Light
version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.
Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo
styling (non-light, that is).
Update2:
With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):
Lollipop added the ability to overwrite the theme at a view by view level by using the
android:theme
XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to useandroid:theme
for Toolbars (deprecating theapp:theme
used previously) and, even better, bringsandroid:theme
support to all views on API 11+ devices.
In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:
<CheckBox
...
android:theme="@android:style/Theme.Holo" />
<CheckBox
...
android:theme="@android:style/Theme.Holo.Light" />
The first CheckBox
is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.
Of course you should no longer be using the Holo theme, but instead use Material.
Button button= (Button)findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
// click handling code
}
});
double quotes worked in oracle when I had the keyword as one of the column name.
eg:
select t."size" from table t
This is an old post, but thanks to this post I have found this:
\! echo 'some text';
Tested with MySQL 8 and working correctly. Cool right? :)
If you want to search a file for a substring and add a new text to the next line, one of the elegant ways to do it is the following:
import fileinput
for line in fileinput.FileInput(file_path,inplace=1):
if "TEXT_TO_SEARCH" in line:
line=line.replace(line,line+"NEW_TEXT")
print line,
One already exists. If you cannot get over the "Move" syntax of the System.IO
namespace. There is a static class FileSystem
within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory
and RenameFile
already within it.
As mentioned by SLaks, this is just a wrapper for Directory.Move
and File.Move
.
#!/bin/bash
IFS=$'\n' wordsArray=($(<$1))
numWords=${#wordsArray[@]}
sizeOfNumWords=${#numWords}
while [ True ]
do
for ((i=0; i<$sizeOfNumWords; i++))
do
let ranNumArray[$i]=$(( ( $RANDOM % 10 ) + 1 ))-1
ranNumStr="$ranNumStr${ranNumArray[$i]}"
done
if [ $ranNumStr -le $numWords ]
then
break
fi
ranNumStr=""
done
noLeadZeroStr=$((10#$ranNumStr))
echo ${wordsArray[$noLeadZeroStr]}
I have to ask a question in return: is your GenSet
"checked" or "unchecked"?
What does that mean?
Checked: strong typing. GenSet
knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E>
argument, and methods will throw an exception when they are passed arguments that are not of type E
. See Collections.checkedCollection
.
-> in that case, you should write:
public class GenSet<E> {
private E[] a;
public GenSet(Class<E> c, int s) {
// Use Array native method to create array
// of a type only known at run time
@SuppressWarnings("unchecked")
final E[] a = (E[]) Array.newInstance(c, s);
this.a = a;
}
E get(int i) {
return a[i];
}
}
Unchecked: weak typing. No type checking is actually done on any of the objects passed as argument.
-> in that case, you should write
public class GenSet<E> {
private Object[] a;
public GenSet(int s) {
a = new Object[s];
}
E get(int i) {
@SuppressWarnings("unchecked")
final E e = (E) a[i];
return e;
}
}
Note that the component type of the array should be the erasure of the type parameter:
public class GenSet<E extends Foo> { // E has an upper bound of Foo
private Foo[] a; // E erases to Foo, so use Foo[]
public GenSet(int s) {
a = new Foo[s];
}
...
}
All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.
On macOS, one option is to install FUSE for macOS and use sshfs
to mount a remote directory:
mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir
Some caveats apply with mounting network volumes, so YMMV.
user: root
password: [blank]
XAMPP v3.2.2
It exists a property called XmlElementAttribute.IsNullable
If the IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to a null reference.
The following example shows a field with the XmlElementAttribute
applied to it, and the IsNullable property set to false.
public class MyClass
{
[XmlElement(IsNullable = false)]
public string Group;
}
You can have a look to other XmlElementAttribute
for changing names in serialization etc.
To get the plugin directory you can use the Wordpress function plugin_basename($file)
. So you would use is as follows to extract the folder and filename of the plugin:
$plugin_directory = plugin_basename(__FILE__);
You can combine this with the URL or the server path of the plugin directory. Therefor you can use the constants WP_PLUGIN_URL
to get the plugin directory url or WP_PLUGIN_DIR
to get the server path. But as Mark Jaquith mentioned in a comment below this only works if the plugins resides in the Wordpress plugin directory.
Read more about it in the Wordpress codex.
This can be done using cut:
echo "http://www.suepearson.co.uk/product/174/71/3816/" | cut -d'/' -f1-3
In most cases the slug should not change, so you really only want to calculate it on first save:
class Test(models.Model):
q = models.CharField(max_length=30)
s = models.SlugField(editable=False) # hide from admin
def save(self):
if not self.id:
self.s = slugify(self.q)
super(Test, self).save()
Maybe you can write a function in ~/.zshrc, ~/.bashrc .
# set my env
[ -s ~/.env ] && export MYENV=`cat ~/.env`
function myenv() { [[ -s ~/.env ]] && echo $argv > ~/.env && export MYENV=$argv }
Beacause of use variable outside, you can avoid write script file.
This will do it:
window.history.pushState(null,null,'https://www.google.com');
Tools -> Options -> Show All Settings -> Text Editor -> All Languages -> Line Numbers
You can use std::filesystem::recursive_directory_iterator
. But beware, this includes symbolic (soft) links. If you want to avoid them you can use is_symlink
. Example usage:
size_t directory_size(const std::filesystem::path& directory)
{
size_t size{ 0 };
for (const auto& entry : std::filesystem::recursive_directory_iterator(directory))
{
if (entry.is_regular_file() && !entry.is_symlink())
{
size += entry.file_size();
}
}
return size;
}
The only reason to have a return in a void function would be to exit early due to some conditional statement:
void foo(int y)
{
if(y == 0) return;
// do stuff with y
}
As unwind said: when the code ends, it ends. No need for an explicit return at the end.
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
You can drop
columns in index:
df[df.columns.drop('b')]
Output:
a c d
0 0.418762 0.869203 0.972314
1 0.991058 0.594784 0.534366
2 0.407472 0.396664 0.894202
3 0.726168 0.324932 0.906575
For those stuck with legacy issues, find the line throwing the error and add {passive: true}
- eg:
this.element.addEventListener(t, e, !1)
becomes
this.element.addEventListener(t, e, { passive: true} )
A postback is triggered after a form submission, so it's related to a client action... take a look here for an explanation: ASP.NET - Is it possible to trigger a postback from server code?
and here for a solution: http://forums.asp.net/t/928411.aspx/1
The answer is "nowhere" since the date formatting is proprietary functionality. I don't think the toString functions are intended to conform to a specific format. e.g. in the ECMAScript 5.1 spec (http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, 2/8/2013, page 173), the toString function is documented as follows:
"The contents of the String are implementation-dependent"
Functions such as the samples below could be used to accomplish formatting fairly easily.
function pad(toPad, padWith) {
return (String(padWith) + String(toPad)).slice(-1 * padWith.length);
}
function dateAsInputValue(toFormat) {
if(!(toFormat instanceof Date)) return null;
return toFormat.getFullYear() + "-" + pad(toFormat.getMonth() + 1, "00") + "-" + pad(toFormat.getDate(), "00");
}
function timeAsInputValue(toFormat) {
if(!(toFormat instanceof Date)) return null;
return pad(toFormat.getHours(), "00") + ":" + pad(toFormat.getMinutes(), "00") + ":" + pad(toFormat.getSeconds(), "00");
}
You could use the following code.
print_r($_SESSION);
You can set a data-*
attribute on an elm using attr()
, and then select using that attribute:
var elm = $('a').attr('data-test',123); //assign 123 using attr()
elm = $("a[data-test=123]"); //select elm using attribute
and now for that elm, both attr()
and data()
will yield 123:
console.log(elm.attr('data-test')); //123
console.log(elm.data('test')); //123
However, if you modify the value to be 456 using attr()
, data()
will still be 123:
elm.attr('data-test',456); //modify to 456
elm = $("a[data-test=456]"); //reselect elm using new 456 attribute
console.log(elm.attr('data-test')); //456
console.log(elm.data('test')); //123
So as I understand it, seems like you probably should steer clear of intermingling attr()
and data()
commands in your code if you don't have to. Because attr()
seems to correspond directly with the DOM whereas data()
interacts with the 'memory', though its initial value can be from the DOM. But the key point is that the two are not necessarily in sync at all.
So just be careful.
At any rate, if you aren't changing the data-*
attribute in the DOM or in the memory, then you won't have a problem. Soon as you start modifying values is when potential problems can arise.
Thanks to @Clarence Liu to @Ash's answer, as well as this post.
try to add display: block;
(or replace the <span>
by a <div>
) (note that this could cause other problems becuase a <span>
is inline by default - but you havn't posted the rest of your html)
You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:
pip install some-package.whl
If you have problem to install the wheel read this answer
Why not pass an object to v-bind:class to dynamically toggle the class:
<div v-bind:class="{ disabled: order.cancelled_at }"></div>
This is what is recommended by the Vue docs.
From the spring docs
Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.
The <context-param>
:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
You can then use the WebApplicationContext to get a handle on your beans.
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info
See these test cases http://jsperf.com/last-item-method The most effective way is throug .pop method (in V8), but loses the last element of the array
This works because you have multiple classes in different jar files. Removing and re-adding the jre lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.
I know I am late it the game, but the issue still exists even after google has made fix on the android.support.v7.widget.RecyclerView
The issue I get now is RecyclerView
with layout_height=wrap_content
not taking height of all the items issue inside ScrollView
that only happens on Marshmallow and Nougat+ (API 23, 24, 25) versions.
(UPDATE: Replacing ScrollView
with android.support.v4.widget.NestedScrollView
works on all versions. I somehow missed testing accepted solution. Added this in my github project as demo.)
After trying different things, I have found workaround that fixes this issue.
Here is my layout structure in a nutshell:
<ScrollView>
<LinearLayout> (vertical - this is the only child of scrollview)
<SomeViews>
<RecyclerView> (layout_height=wrap_content)
<SomeOtherViews>
The workaround is the wrap the RecyclerView
with RelativeLayout
. Don't ask me how I found this workaround!!! ¯\_(?)_/¯
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Complete example is available on GitHub project - https://github.com/amardeshbd/android-recycler-view-wrap-content
Here is a demo screencast showing the fix in action:
Using fs-extra package is quite simple:
Sync:
const fs = require('fs-extra')
const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version)
Async:
const fs = require('fs-extra')
const packageObj = await fs.readJson('./package.json')
console.log(packageObj.version)
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
This will add ONE class or MULTIPLE classes :
addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
When using Redis, TTL can be set in properties file like this:
spring.cache.redis.time-to-live=1d # 1 day
spring.cache.redis.time-to-live=5m # 5 minutes
spring.cache.redis.time-to-live=10s # 10 seconds
Since you're using Spring Boot, I assume you'd prefer to rely on Spring's auto configuration where possible. To add additional custom configuration like your interceptors, just provide a configuration or bean of WebMvcConfigurerAdapter
.
Here's an example of a config class:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
HandlerInterceptor yourInjectedInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(...)
...
registry.addInterceptor(getYourInterceptor());
registry.addInterceptor(yourInjectedInterceptor);
// next two should be avoid -- tightly coupled and not very testable
registry.addInterceptor(new YourInterceptor());
registry.addInterceptor(new HandlerInterceptor() {
...
});
}
}
NOTE do not annotate this with @EnableWebMvc, if you want to keep Spring Boots auto configuration for mvc.
When I'm confronted with this problem, there are a couple of questions that I try to find the answers to first:
The simplest way to do this is with Enum.GetValue
(and support round-tripping using Enum.Parse
). It's also often worth building a TypeConverter
, as Steve Mitcham suggests, to support UI binding. (It's not necessary to build a TypeConverter
when you're using property sheets, which is one of the nice things about property sheets. Though lord knows they have their own issues.)
In general, if the answers to the above questions suggest that's not going to work, my next step is to create and populate a static Dictionary<MyEnum, string>
, or possibly a Dictionary<Type, Dictionary<int, string>>
. I tend to skip the intermediate decorate-the-code-with-attributes step because what's usually coming down the pike next is the need to change the friendly values after deployment (often, but not always, because of localization).
Add a random query string to the src
You could either do this manually by incrementing the querystring each time you make a change:
<script src="test.js?version=1"></script>
Or if you are using a server side language, you could automatically generate this:
ASP.NET:
<script src="test.js?rndstr=<%= getRandomStr() %>"></script>
More info on cache-busting can be found here:
https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/
for a non-nested dict (since the title does not mention that case, it might be interesting for other people)
{str(k): str(v) for k, v in my_dict.items()}
Something more to the point for me..
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
document.write(contact.phone[1]);
// Output:
// Aaberg, Jesper
// 555-0100
Reference: https://docs.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript
jQuery now has a CDN access:
code.jquery.com/ui/[version]/themes/[theme name]/jquery-ui.css
And to make this a little more easy, Here you go:
There is no need for jQuery here, regular JavaScript will do:
var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
Or, the .split()
and .pop()
version:
var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
Or, the regex version (several variants of this):
var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
I found my actual problem and it was not mentioned in any answer: some of my unit-tests were causing logging initialization code to be run multiple times within the same test suite, messing up the logging on the later tests.
Instead of using re.search
use re.findall
it will return you all matches in a List
. Or you could also use re.finditer
(which i like most to use) it will return an Iterator Object
and you can just use it to iterate over all found matches.
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
print match.group(1)
The definition of SIZE_T
is found at:
https://msdn.microsoft.com/en-us/library/cc441980.aspx and https://msdn.microsoft.com/en-us/library/cc230394.aspx
Pasting here the required information:
SIZE_T
is a ULONG_PTR
representing the maximum number of bytes to which a pointer can point.
This type is declared as follows:
typedef ULONG_PTR SIZE_T;
A ULONG_PTR
is an unsigned long type used for pointer precision. It is used when casting a pointer to a long type to perform pointer arithmetic.
This type is declared as follows:
typedef unsigned __int3264 ULONG_PTR;
iOS 13> swift 5
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {view.tintColor = UIColor.red }
Go into Window > Preferences > Java > Installed JREs > and check your installed JREs. You should have an entry with a JDK there.
try:
%matplotlib notebook
EDIT for JupyterLab users:
Follow the instructions to install jupyter-matplotlib
Then the magic command above is no longer needed, as in the example:
# Enabling the `widget` backend.
# This requires jupyter-matplotlib a.k.a. ipympl.
# ipympl can be install via pip or conda.
%matplotlib widget
# aka import ipympl
import matplotlib.pyplot as plt
plt.plot([0, 1, 2, 2])
plt.show()
Finally, note Maarten Breddels' reply; IMHO ipyvolume is indeed very impressive (and useful!).
When you need to toggle an element away, and you don't need to animate the margin property. You could try margin-top: -999999em
. Just don't transition all.
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
Here's a twist on @user65157's answer (+1 for that, BTW):
I created an IDisposable wrapper for the pinned object:
class AutoPinner : IDisposable
{
GCHandle _pinnedArray;
public AutoPinner(Object obj)
{
_pinnedArray = GCHandle.Alloc(obj, GCHandleType.Pinned);
}
public static implicit operator IntPtr(AutoPinner ap)
{
return ap._pinnedArray.AddrOfPinnedObject();
}
public void Dispose()
{
_pinnedArray.Free();
}
}
then use it like thusly:
using (AutoPinner ap = new AutoPinner(MyManagedObject))
{
UnmanagedIntPtr = ap; // Use the operator to retrieve the IntPtr
//do your stuff
}
I found this to be a nice way of not forgetting to call Free() :)
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
According to the documentation, timestamp
is a synonym for rowversion
- it's automatically generated and guaranteed1 to be unique. datetime
isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.
1 Assuming you use it properly, of course. See comments.
Use a document.ready()
event around your call.
$(document).ready(function () {
$('#memberModal').modal('show');
});
jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/
$(document).on('change','.radio-button', function(){
const radio = $(this);
if (radio.is(':checked')) {
console.log(radio)
}
});
I created a trim.strings ()
function to trim leading and/or trailing whitespace as:
# Arguments: x - character vector
# side - side(s) on which to remove whitespace
# default : "both"
# possible values: c("both", "leading", "trailing")
trim.strings <- function(x, side = "both") {
if (is.na(match(side, c("both", "leading", "trailing")))) {
side <- "both"
}
if (side == "leading") {
sub("^\\s+", "", x)
} else {
if (side == "trailing") {
sub("\\s+$", "", x)
} else gsub("^\\s+|\\s+$", "", x)
}
}
For illustration,
a <- c(" ABC123 456 ", " ABC123DEF ")
# returns string without leading and trailing whitespace
trim.strings(a)
# [1] "ABC123 456" "ABC123DEF"
# returns string without leading whitespace
trim.strings(a, side = "leading")
# [1] "ABC123 456 " "ABC123DEF "
# returns string without trailing whitespace
trim.strings(a, side = "trailing")
# [1] " ABC123 456" " ABC123DEF"
Another option is to use a dictionary with values you don't care about. E.g.,
poor_man_set = {}
poor_man_set[1] = None
poor_man_set[2] = None
poor_man_set[3] = None
...
You can treat the keys as a set except that they're just an array:
keys = poor_man_set.keys()
print "Some key = %s" % keys[0]
A side effect of this choice is that your code will be backwards compatible with older, pre-set
versions of Python. It's maybe not the best answer but it's another option.
Edit: You can even do something like this to hide the fact that you used a dict instead of an array or set:
poor_man_set = {}
poor_man_set[1] = None
poor_man_set[2] = None
poor_man_set[3] = None
poor_man_set = poor_man_set.keys()
For anyone who comes across this issue in the future, I had to add
perspective: 1px;
to the element that I was applying the border radius to. Final working code:
.ele-with-border-radius {
border-radius: 15px;
overflow: hidden;
perspective: 1px;
}
Firstable, make sure that you Antivirus software doesn't block SSL2.
Because I could not solve a problem for a long time and only disabling the antivirus helped me
You can try something like this:
Image logo = Image.GetInstance("pathToTheImage")
logo.ScaleAbsolute(500, 300)
The following class allows you to copy/paste a String to/from the clipboard.
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;
public class SystemClipboard
{
public static void copy(String text)
{
Clipboard clipboard = getSystemClipboard();
clipboard.setContents(new StringSelection(text), null);
}
public static void paste() throws AWTException
{
Robot robot = new Robot();
int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
robot.keyPress(controlKey);
robot.keyPress(VK_V);
robot.keyRelease(controlKey);
robot.keyRelease(VK_V);
}
public static String get() throws Exception
{
Clipboard systemClipboard = getSystemClipboard();
DataFlavor dataFlavor = DataFlavor.stringFlavor;
if (systemClipboard.isDataFlavorAvailable(dataFlavor))
{
Object text = systemClipboard.getData(dataFlavor);
return (String) text;
}
return null;
}
private static Clipboard getSystemClipboard()
{
Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
return defaultToolkit.getSystemClipboard();
}
}
I picked up the content using JavaScript and created a window that I could print in stead...
Yes,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
It is the same as super
in Java, except it allows calling implementations from different bases when you have multiple inheritance.
class Foo {
public:
virtual void foo() {
...
}
};
class Baz {
public:
virtual void foo() {
...
}
};
class Bar : public Foo, public Baz {
public:
virtual void foo() {
// Choose one, or even call both if you need to.
Foo::foo();
Baz::foo();
}
};
To use the else
in list comprehensions in python programming you can try out the below snippet. This would resolve your problem, the snippet is tested on python 2.7 and python 3.5.
obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
Simply use title in tag like
<i class="fa fa-edit" title="Edit Mode"></i>
This will show 'Edit Mode' when hover that icon.
I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.
What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).
<script language="javascript" type="text/javascript">
window.onbeforeunload = function () {
// This function does nothing. It won't spawn a confirmation dialog
// But it will ensure that the page is not cached by the browser.
}
</script>
This has disabled all caching in all browsers for me without fail.
Try these ...
Option1
window.location=document.referrer;
Option2
window.location.reload(history.back());
If you want to rotate 45 degrees, you can use the CSS transform property:
.fa-rotate-45 {
-ms-transform:rotate(45deg); /* Internet Explorer 9 */
-webkit-transform:rotate(45deg); /* Chrome, Safari, Opera */
transform:rotate(45deg); /* Standard syntax */
}
You can use COLLATE NOCASE
in your SELECT
query:
SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE
Additionaly, in SQLite, you can indicate that a column should be case insensitive when you create the table by specifying collate nocase
in the column definition (the other options are binary
(the default) and rtrim
; see here). You can specify collate nocase
when you create an index as well. For example:
create table Test ( Text_Value text collate nocase ); insert into Test values ('A'); insert into Test values ('b'); insert into Test values ('C'); create index Test_Text_Value_Index on Test (Text_Value collate nocase);
Expressions involving Test.Text_Value
should now be case insensitive. For example:
sqlite> select Text_Value from Test where Text_Value = 'B'; Text_Value ---------------- b sqlite> select Text_Value from Test order by Text_Value; Text_Value ---------------- A b C sqlite> select Text_Value from Test order by Text_Value desc; Text_Value ---------------- C b A
The optimiser can also potentially make use of the index for case-insensitive searching and matching on the column. You can check this using the explain
SQL command, e.g.:
sqlite> explain select Text_Value from Test where Text_Value = 'b'; addr opcode p1 p2 p3 ---------------- -------------- ---------- ---------- --------------------------------- 0 Goto 0 16 1 Integer 0 0 2 OpenRead 1 3 keyinfo(1,NOCASE) 3 SetNumColumns 1 2 4 String8 0 0 b 5 IsNull -1 14 6 MakeRecord 1 0 a 7 MemStore 0 0 8 MoveGe 1 14 9 MemLoad 0 0 10 IdxGE 1 14 + 11 Column 1 0 12 Callback 1 0 13 Next 1 9 14 Close 1 0 15 Halt 0 0 16 Transaction 0 0 17 VerifyCookie 0 4 18 Goto 0 1 19 Noop 0 0
Pro-tip Note: for some reason, CSS syntax needs the :active
snippet after the :hover
for the same element in order to be effective
I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).
I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.
I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.
Hope this helps!
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
Use CHAR
:
=Char(34)&"This is in quotes"&Char(34)
Should evaluate to:
"This is in quotes"