Changing
RestResponse response = client.Execute(request);
to
IRestResponse response = client.Execute(request);
worked for me.
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
Forget datalist element that good solution for autocomplete function, but not for combobox feature.
css:
.combobox {
display: inline-block;
position: relative;
}
.combobox select {
display: none;
position: absolute;
overflow-y: auto;
}
html:
<div class="combobox">
<input type="number" name="" value="" min="" max="" step=""/><br/>
<select size="3">
<option value="0"> 0</option>
<option value="25"> 25</option>
<option value="40"> 40</option>
</select>
</div>
js (jQuery):
$('.combobox').each(function() {
var
$input = $(this).find('input'),
$select = $(this).find('select');
function hideSelect() {
setTimeout(function() {
if (!$select.is(':focus') && !$input.is(':focus')) {
$select
.hide()
.css('z-index', 1);
}
}, 20);
}
$input
.focusin(function() {
if (!$select.is(':visible')) {
$select
.outerWidth($input.outerWidth())
.show()
.css('z-index', 100);
}
})
.focusout(hideSelect)
.on('input', function() {
$select.val('');
});
$select
.change(function() {
$input.val($select.val());
})
.focusout(hideSelect);
});
This works properly even when you use text input instead of number.
From ggplot2 2.0.0
you can use the margin =
argument of element_text()
to change the distance between the axis title and the numbers. Set the values of the margin
on t
op, r
ight, b
ottom, and l
eft side of the element.
ggplot(mpg, aes(cty, hwy)) + geom_point()+
theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin
can also be used for other element_text
elements (see ?theme
), such as axis.text.x
, axis.text.y
and title
.
addition
in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top")
, you'll need a different theme setting - e.g. axis.title.x.top
. See https://github.com/tidyverse/ggplot2/issues/4343.
In python 3, you can use:
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )
Output
'$1,234.50'
Use doubleValue method present in BigDecimal class :
double doubleValue()
Converts this BigDecimal
to a double
.
None of these actually worked for me, but running
python -m pip install -U pip
and then adding the specified directory to the PATH as suggested got it working
It's worth noting that there are libraries for most languages that do this for you, often built into the standard library. And those libraries are likely to get updated a lot more often than code that you copied off a Stack Overflow answer four years ago and forgot about. And of course they'll also generally parse the address into some usable form, rather than just giving you a match with a bunch of groups.
For example, detecting and parsing IPv4 in (POSIX) C:
#include <arpa/inet.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
for (int i=1; i!=argc; ++i) {
struct in_addr addr = {0};
printf("%s: ", argv[i]);
if (inet_pton(AF_INET, argv[i], &addr) != 1)
printf("invalid\n");
else
printf("%u\n", addr.s_addr);
}
return 0;
}
Obviously, such functions won't work if you're trying to, e.g., find all valid addresses in a chat message—but even there, it may be easier to use a simple but overzealous regex to find potential matches, and then use the library to parse them.
For example, in Python:
>>> import ipaddress
>>> import re
>>> msg = "My address is 192.168.0.42; 192.168.0.420 is not an address"
>>> for maybeip in re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', msg):
... try:
... print(ipaddress.ip_address(maybeip))
... except ValueError:
... pass
static bool FileInUse(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
fs.CanWrite
}
return false;
}
catch (IOException ex)
{
return true;
}
}
string filePath = "C:\\Documents And Settings\\yourfilename";
bool isFileInUse;
isFileInUse = FileInUse(filePath);
// Then you can do some checking
if (isFileInUse)
Console.WriteLine("File is in use");
else
Console.WriteLine("File is not in use");
Hope this helps!
Because Xcode subsumes the CLI tools if installed first, I use the following hybrid which has been validated on 10.12 and 10.14. I expect it works on a lot of other versions:
installed=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables 2>/dev/null || pkgutil --pkg-info=com.apple.pkg.Xcode)
Salt with awk
to taste for branching logic.
Of course xcode-select -p
handles the variations with a really short command but fails to give the detailed package, version, and installation date metadata.
In Python, every value is a reference (a pointer to an object), just like non-primitives in Java. Also, like Java, Python only has pass by value. So, semantically, they are pretty much the same.
Since you mention Java in your question, I would like to see how you achieve what you want in Java. If you can show it in Java, I can show you how to do it exactly equivalently in Python.
You have two options for concatenating strings in Oracle:
CONCAT example:
CONCAT(
CONCAT(
CONCAT(
CONCAT(
CONCAT('I like ', t.type_desc_column),
' cake with '),
t.icing_desc_column),
' and a '),
t.fruit_desc_column)
Using ||
example:
'I like ' || t.type_desc_column || ' cake with ' || t.icing_desc_column || ' and a ' || t.fruit_desc_column
Although this question was posted 10 years ago, I believe that it still needs some improvements. So here is my solution.
$(document).on('propertychange change click keyup input paste', 'selector', function (e) {
// Do something here
});
The only problem with this solution is, it won't trigger if the value changes from javascript like $('selector').val('some value')
. You can fire any event to your selector when you change the value from javascript.
$(selector).val('some value');
// fire event
$(selector).trigger('change');
It's a lot easier than that:
List = open("filename.txt").readlines()
This returns a list of each line in the file.
This one builds on @alockwood05's answer and provides both get and set functionality for a caret with nested tags inside the contenteditable div as well as the offsets within nodes so that you have a solution that is both serializable and de-serializable by offsets as well.
I'm using this solution in a cross-platform code editor that needs to get the caret start/end position prior to syntax highlighting via a lexer/parser and then set it back immediately afterward.
function countUntilEndContainer(parent, endNode, offset, countingState = {count: 0}) {
for (let node of parent.childNodes) {
if (countingState.done) break;
if (node === endNode) {
countingState.done = true;
countingState.offsetInNode = offset;
return countingState;
}
if (node.nodeType === Node.TEXT_NODE) {
countingState.offsetInNode = offset;
countingState.count += node.length;
} else if (node.nodeType === Node.ELEMENT_NODE) {
countUntilEndContainer(node, endNode, offset, countingState);
} else {
countingState.error = true;
}
}
return countingState;
}
function countUntilOffset(parent, offset, countingState = {count: 0}) {
for (let node of parent.childNodes) {
if (countingState.done) break;
if (node.nodeType === Node.TEXT_NODE) {
if (countingState.count <= offset && offset < countingState.count + node.length)
{
countingState.offsetInNode = offset - countingState.count;
countingState.node = node;
countingState.done = true;
return countingState;
}
else {
countingState.count += node.length;
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
countUntilOffset(node, offset, countingState);
} else {
countingState.error = true;
}
}
return countingState;
}
function getCaretPosition()
{
let editor = document.getElementById('editor');
let sel = window.getSelection();
if (sel.rangeCount === 0) { return null; }
let range = sel.getRangeAt(0);
let start = countUntilEndContainer(editor, range.startContainer, range.startOffset);
let end = countUntilEndContainer(editor, range.endContainer, range.endOffset);
let offsetsCounts = { start: start.count + start.offsetInNode, end: end.count + end.offsetInNode };
let offsets = { start: start, end: end, offsets: offsetsCounts };
return offsets;
}
function setCaretPosition(start, end)
{
let editor = document.getElementById('editor');
let sel = window.getSelection();
if (sel.rangeCount === 0) { return null; }
let range = sel.getRangeAt(0);
let startNode = countUntilOffset(editor, start);
let endNode = countUntilOffset(editor, end);
let newRange = new Range();
newRange.setStart(startNode.node, startNode.offsetInNode);
newRange.setEnd(endNode.node, endNode.offsetInNode);
sel.removeAllRanges();
sel.addRange(newRange);
return true;
}
DateTime.Now.ToShortTimeString().ToString()
This Will give you DateTime as 10:50PM
eloone did it file by file with
git checkout <commit-hash> <filename>
but you could checkout all files more easily by doing
git checkout <commit-hash> .
This happens whenever you are trying to load a fragment but the activity has changed its state to onPause().This happens for example when you try to fetch data and load it to the activity but by the time the user has clicked some button and has moved to next activity.
You can solve this in two ways
You can use transaction.commitAllowingStateLoss() instead of transaction.commit() to load fragment but you may end up losing commit operation that is done.
or
Make sure that activity is in resume and not going to pause state when loading a fragment. Create a boolean and check if activity is not going to onPause() state.
@Override
public void onResume() {
super.onResume();
mIsResumed = true;
}
@Override
public void onPause() {
mIsResumed = false;
super.onPause();
}
then while loading fragment check if activity is present and load only when activity is foreground.
if(mIsResumed){
//load the fragment
}
Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]);
You can do as
body{
background:url('equote.png'),url('equote.png');
background-size:400px 100px,50px 50px;
}
I would use to table header tag below for a text in a table to make it standout from the rest of the table content.
<table>
<tr>
<th>Dimension:</th>
<td>98cm x 71cm</td>
</tr>
</table
you can get the index via grep
and colnames
:
grep("B", colnames(df))
[1] 2
or use
grep("^B$", colnames(df))
[1] 2
to only get the columns called "B" without those who contain a B e.g. "ABC".
Serialize both objects, then calculate Hash Code, then compare.
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
Basically you need to have loading image Download free one from here http://www.ajaxload.info/
$(function() {
$("#client").on("change", function() {
var clientid=$("#client").val();
$('#loadingmessage').show();
$.ajax({
type:"post",
url:"clientnetworkpricelist/yourfile.php",
data:"title="+clientid,
success:function(data){
$('#loadingmessage').hide();
$("#result").html(data);
}
});
});
});
On html body
<div id='loadingmessage' style='display:none'>
<img src='img/ajax-loader.gif'/>
</div>
Probably this could help you
use like this :-
gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();
I hope it helps!!
ord()
will not work because your end string is two characters long.
Returns the ASCII value of the first character of string.
From my testing, you need to check that the end
string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.
Code: (Demo)
function excelCols($letter,$end,$step=1){ // function doesn't check that $end is "later" than $letter
if($step==0)return []; // prevent infinite loop
do{
$letters[]=$letter; // store letter
for($x=0; $x<$step; ++$x){ // increment in accordance with $step declaration
if($letter===$end)break(2); // break if end is "stepped on"
++$letter;
}
}while(true);
return $letters;
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));
Output:
A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
---
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
---
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
---
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX
Here is an array-functions approach:
Code: (Demo)
$start='C';
$end='DD';
$step=4;
// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1); // store A - Z as $array and $result
foreach($array as $a){
foreach($array as $b){
$result[]="$a$b"; // store double letter combinations
if(in_array($end,$result)){break(2);} // stop asap
}
}
//echo implode(' ',$result),"\n\n";
// slice away from the front of the array
$result=array_slice($result,array_search($start,$result)); // reindex keys
//echo implode(' ',$result),"\n\n";
// punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo
// result is ready
echo implode(' ',$result);
Output:
C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC
ASP.NET grants access from the configuration file as a matter of precedence. In case of a potential conflict, the first occurring grant takes precedence. So,
deny user="?"
denies access to the anonymous user. Then
allow users="dan,matthew"
grants access to that user. Finally, it denies access to everyone. This shakes out as everyone except dan,matthew is denied access.
Edited to add: and as @Deviant points out, denying access to unauthenticated is pointless, since the last entry includes unauthenticated as well. A good blog entry discussing this topic can be found at: Guru Sarkar's Blog
For the first question I think answer would be:
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
or
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:
Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]
This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
ZoneId z = ZoneId.of( "America/Montreal" ); // A date only has meaning within a specific time zone. At any given moment, the date varies around the globe by zone.
LocalDate ld =
givenJavaUtilDate.toInstant() // Convert from legacy class `Date` to modern class `Instant` using new methods added to old classes.
.atZone( z ) // Adjust into the time zone in order to determine date.
.toLocalDate(); // Extract date-only value.
LocalDate today = LocalDate.now( z ); // Get today’s date for specific time zone.
LocalDate kwanzaaStart = today.withMonth( Month.DECEMBER ).withDayOfMonth( 26 ); // Kwanzaa starts on Boxing Day, day after Christmas.
LocalDate kwanzaaStop = kwanzaaStart.plusWeeks( 1 ); // Kwanzaa lasts one week.
Boolean isDateInKwanzaaThisYear = (
( ! today.isBefore( kwanzaaStart ) ) // Short way to say "is equal to or is after".
&&
today.isBefore( kwanzaaStop ) // Half-Open span of time, beginning inclusive, ending is *exclusive*.
)
Date-time work commonly employs the "Half-Open" approach to defining a span of time. The beginning is inclusive while the ending is exclusive. So a week starting on a Monday runs up to, but does not include, the following Monday.
Java 8 and later comes with the java.time
framework built-in. Supplants the old troublesome classes including java.util.Date/.Calendar
and SimpleDateFormat
. Inspired by the successful Joda-Time library. Defined by JSR 310. Extended by the ThreeTen-Extra project.
An Instant
is a moment on the timeline in UTC with nanosecond resolution.
Instant
Convert your java.util.Date
objects to Instant objects.
Instant start = myJUDateStart.toInstant();
Instant stop = …
If getting java.sql.Timestamp
objects through JDBC from a database, convert to java.time.Instant in a similar way. A java.sql.Timestamp
is already in UTC so no need to worry about time zones.
Instant start = mySqlTimestamp.toInstant() ;
Instant stop = …
Get the current moment for comparison.
Instant now = Instant.now();
Compare using the methods isBefore, isAfter, and equals.
Boolean containsNow = ( ! now.isBefore( start ) ) && ( now.isBefore( stop ) ) ;
LocalDate
Perhaps you want to work with only the date, not the time-of-day.
The LocalDate
class represents a date-only value, without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;
To get the current date, specify a time zone. At any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
We can use the isEqual
, isBefore
, and isAfter
methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.
Boolean containsToday = ( ! today.isBefore( start ) ) && ( today.isBefore( stop ) ) ;
Interval
If you chose to add the ThreeTen-Extra library to your project, you could use the Interval
class to define a span of time. That class offers methods to test if the interval contains, abuts, encloses, or overlaps other date-times/intervals.
The Interval
class works on Instant
objects. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
We can adjust the LocalDate
into a specific moment, the first moment of the day, by specifying a time zone to get a ZonedDateTime
. From there we can get back to UTC by extracting a Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Interval interval =
Interval.of(
start.atStartOfDay( z ).toInstant() ,
stop.atStartOfDay( z ).toInstant() );
Instant now = Instant.now();
Boolean containsNow = interval.contains( now );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time
classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time
classes?
java.time
functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.The ThreeTen-Extra project extends java.time
with additional classes. This project is a proving ground for possible future additions to java.time
. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
import win32api # if active state python is installed or install pywin32 package seperately
try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
except: pass
None of the answers here worked for me out of the box, here is what worked for me:
Create pipes/keys.ts
with contents:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform
{
transform(value:any, args:string[]): any {
let keys:any[] = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
Add to app.module.ts
(Your main module):
import { KeysPipe } from './pipes/keys';
and then add to your module declarations array something like this:
@NgModule({
declarations: [
KeysPipe
]
})
export class AppModule {}
Then in your view template you can use something like this:
<option *ngFor="let entry of (myData | keys)" value="{{ entry.key }}">{{ entry.value }}</option>
Here is a good reference I found if you want to read more.
function randomRange(min, max) {
return ~~(Math.random() * (max - min + 1)) + min
}
Alternative if you are using Underscore.js you can use
_.random(min, max)
Also make sure the page is valid. You can check this in the browsers developer tools (F12)
In the Console tab select the correct Target/Frame and check for the [Page_IsValid] property
If the page is not valid the form will not submit and therefore not fire the event.
return; // Prematurely return from the method (same keword works in VB, by the way)
When you write "tests defined as class methods", do you really mean class methods (methods which receive its class as first parameter) or just regular methods (methods which receive an instance as first parameter)?
Since your example uses self
for the test methods I'm assuming the latter, so you just need to use setup_method
instead:
class Test:
def setup_method(self, test_method):
# configure self.attribute
def teardown_method(self, test_method):
# tear down self.attribute
def test_buttons(self):
# use self.attribute for test
The test method instance is passed to setup_method
and teardown_method
, but can be ignored if your setup/teardown code doesn't need to know the testing context. More information can be found here.
I also recommend that you familiarize yourself with py.test's fixtures, as they are a more powerful concept.
i would recommend Modern UI for WPF .
It has a very active maintainer it is awesome and free!
I'm currently porting some projects to MUI, first (and meanwhile second) impression is just wow!
To see MUI in action you could download XAML Spy which is based on MUI.
EDIT: Using Modern UI for WPF a few months and i'm loving it!
To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
The best value is the one that is right for the data as defined in the underlying domain.
For some domains, VARCHAR(10)
is right for the Name
attribute, for other domains VARCHAR(255)
might be the best choice.
I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm
Which works nicely. :)
Look here for a description of the statusVar variable.
You can do something like below, where the "status" variable contains the current status of the iteration. This is very useful if you need special annotations for the first and last iteraton. In the case below I want to ommit the comma behind the last tag. Of course you can replace status.last
with status.first
to do something special on the first itteration:
<td>
<c:forEach var="tag" items="${idea.tags}" varStatus="status">
<span>${tag.name not status.last ? ', ' : ''}</span>
</c:forEach>
</td>
Possible options are: current, index, count, first, last, begin, step,
and end
You can add and remove classes with jQuery like so:
$(".first").addClass("second")
// remove a class
$(".first").removeClass("second")
By the way you can set multiple classes in your markup right away separated with a whitespace
<div class="second first"></div>
try this function $('div.total-title').text('test');
I think it has mostly to do with scope of awareness for the developer. The IDE provides a macroscopic view of the developer's work context. You can simultaneously see class hierarchies, referenced resources, database schemas, SDK help references, etc. And with so many things affected by, and affecting, your keystrokes, and the expanding volume of architectures and architectural intersections, it gets more and more difficult to work solely from one island of code at a time.
OTOH, "just me and vim and the man pages" gives me a much leaner microscopic - but intense and precise - view of my work. This is ok if I have a well-designed, well-partitioned, sparsely coupled highly cohesive codebase built in one language with one set of static libraries to work from - not your typical situation, especially as dev team sizes grow and reshape the code structure over time, distance, and personal preference.
I'm currently working on projects in Flex and .NET. One of the nicer things about Flex is how few different ways there are to accomplish a standard thing - pull data from a database, open/close/read/write a file, etc. (Yet I'm using the Flex Builder/Eclipse IDE - a typical heavy-weight example like VS, because I'm still learning the basics and I need the training wheels. I expect to evolve back to vim once I'm confident of my patterns.) In this view, I can do what I need to do professionally by knowing a few things really really well.
OTOH, I can't imagine getting to that point with .NET because the view I'm expected to maintain keeps expanding and shifting. There much less conceptual integrity, and over several developers on a project over several months, much less consistency - but the IDE supports that, maybe encourages it. So the developer really needs to (and can more easily) know many more things adequately. Which also has the benefit of helping them answer (or even understand) a lot higher percentage of the questions on StackOverflow. I.e. we can have a deeper knowledge stack. And we can respond to a wider variety of help-wanted ads.
Things can go too far in both directions. Maybe with the "editor-only" scope, it's like "if you only have a hammer, everything looks like a nail". With the IDE approach, for whatever you want to fasten together, you have a broad selection of fasteners and associated ranges of tools to choose from - nals/hammers, screws/screwdrivers, bolts/wrenches, adhesives/glue-guns/clamps, magnets, and on and on - all at your fingertips (with a wizard to help you get started).
IF EXISTS()
is semantically incorrect. EXISTS
condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:
declare
l_exst number(1);
begin
select case
when exists(select ce.s_regno
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1
)
then 1
else 0
end into l_exst
from dual;
if l_exst = 1
then
DBMS_OUTPUT.put_line('YES YOU CAN');
else
DBMS_OUTPUT.put_line('YOU CANNOT');
end if;
end;
Or you can simply use count
function do determine the number of rows returned by the query, and rownum=1
predicate - you only need to know if a record exists:
declare
l_exst number;
begin
select count(*)
into l_exst
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1;
if l_exst = 0
then
DBMS_OUTPUT.put_line('YOU CANNOT');
else
DBMS_OUTPUT.put_line('YES YOU CAN');
end if;
end;
Or see cut_number
from the ggplot2
package, e.g.
das$wt_2 <- as.numeric(cut_number(das$wt,3))
Note that cut(...,3)
divides the range of the original data into three ranges of equal lengths; it doesn't necessarily result in the same number of observations per group if the data are unevenly distributed (you can replicate what cut_number
does by using quantile
appropriately, but it's a nice convenience function). On the other hand, Hmisc::cut2()
using the g=
argument does split by quantiles, so is more or less equivalent to ggplot2::cut_number
. I might have thought that something like cut_number
would have made its way into dplyr
by so far, but as far as I can tell it hasn't.
Here's a quick and dirty json pickle alternative
import json
class User:
def __init__(self, name, username):
self.name = name
self.username = username
def to_json(self):
return json.dumps(self.__dict__)
@classmethod
def from_json(cls, json_str):
json_dict = json.loads(json_str)
return cls(**json_dict)
# example usage
User("tbrown", "Tom Brown").to_json()
User.from_json(User("tbrown", "Tom Brown").to_json()).to_json()
Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait,
and wait short time in every loop.
This will result in something like
max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
if [ -f /tmp/st_new.tmp ]; then
break # call results.sh outside loop
else
(( retry = retry + 1 ))
sleep 1
fi
done
if [ -f /tmp/st_new.tmp ]; then
source ../../results.sh
rm -f /tmp/st_new.tmp
else
echo Something wrong with st_new.sh
fi
with open(filename, 'a') as f:
df.to_csv(f, header=f.tell()==0)
According to Effective Java 2nd edition (Item 13):
"If a package-private top-level class (or interface) is used by only one class, consider making the top-level class a private nested class of the sole class that uses it (Item 22). This reduces its accessibility from all the classes in its package to the one class that uses it. But it is far more important to reduce the accessibility of a gratuitously public class than a package-private top-level class: ... "
The nested class may be static or non-static based on whether the member class needs access to the enclosing instance (Item 22).
I was having alot of trouble with this because I was using:
if($.cookie('token') === null || $.cookie('token') === "")
{
//no cookie
}
else
{
//have cookie
}
The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.
if($.cookie('token') === null || $.cookie('token') === ""
|| $.(cookie('token') === "null" || $.cookie('token') === undefined)
{
//no cookie
}
else
{
//have cookie
}
content: "";
background-image: url("yourimage.jpg");
background-size: 30px, 30px;
Here is an option for people who use DataBinding
for RecyclerView
.
I have var recyclerViewState: Parcelable?
in my adapter. And I use a BindingAdapter
with a variation of @DawnYu's answer to set and update data in the RecyclerView
:
@BindingAdapter("items")
fun setRecyclerViewItems(
recyclerView: RecyclerView,
items: List<RecyclerViewItem>?
) {
var adapter = (recyclerView.adapter as? RecyclerViewAdapter)
if (adapter == null) {
adapter = RecyclerViewAdapter()
recyclerView.adapter = adapter
}
adapter.recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState()
// the main idea is in this call with a lambda. It allows to avoid blinking on data update
adapter.submitList(items.orEmpty()) {
adapter.recyclerViewState?.let {
recyclerView.layoutManager?.onRestoreInstanceState(it)
}
}
}
Finally, the XML part looks like:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/possible_trips_rv"
android:layout_width="match_parent"
android:layout_height="0dp"
app:items="@{viewState.yourItems}"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
Get image size with jQuery
function getMeta(url){
$("<img/>",{
load : function(){
alert(this.width+' '+this.height);
},
src : url
});
}
Get image size with JavaScript
function getMeta(url){
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = url;
}
Get image size with JavaScript (modern browsers, IE9+ )
function getMeta(url){
var img = new Image();
img.addEventListener("load", function(){
alert( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = url;
}
Use the above simply as: getMeta( "http://example.com/img.jpg" );
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
I prefer elegant solutions
In Template
<td>Total: {{ totalSum }}</td>
In Controller
$scope.totalSum = Object.keys(cart.products).map(function(k){
return +cart.products[k].price;
}).reduce(function(a,b){ return a + b },0);
If you're using ES2015 (aka ES6)
$scope.totalSum = Object.keys(cart.products)
.map(k => +cart.products[k].price)
.reduce((a, b) => a + b);
This is impossible without using git fetch
or git pull
. How can you know whether or not the repository is "up-to-date" without going to the remote repository to see what "up-to-date" even means?
You can actually grab the value straight from the event. Its a bit obtuse how to get to it though.
Return false if you don't want it to go through.
$(this).on('paste', function(e) {
var pasteData = e.originalEvent.clipboardData.getData('text')
});
The solution on this site worked for me https://crunchify.com/java-how-to-configure-log4j-logger-property-correctly/. I now see no warnings at all from log4j
I put this in a log4j.properties file that I put in src/main/resources
# This sets the global logging level and specifies the appenders
log4j.rootLogger=INFO, theConsoleAppender
# settings for the console appender
log4j.appender.theConsoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.theConsoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.theConsoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
Copy conditionally formatted cells into Word (using CTRL+C, CTRL+V). Copy them back into Excel, keeping the source formatting. Now the conditional formatting is lost but you still have the colors and can check the RGB choosing Home > Fill color (or Font color) > More colors.
Seems like now it's free for small teams and students, according to Scott Hanselman post https://twitter.com/shanselman/status/715568774418595840
https://visualstudio.microsoft.com/vs/pricing/
Visual Studio Community
FREEA free, full-featured and extensible IDE for Windows users to create Android and iOS apps with Xamarin, as well as Windows apps, web apps, and cloud services.
- Students
- OSS development
- Small teams
and
Xamarin Studio Community FREE
A free, full-featured IDE for Mac users to create Android and iOS apps using Xamarin.
- Students
- OSS development
- Small teams
AtomicInteger
Maybe this is of some worth also: there is a Java class called AtomicInteger
.
This class has some useful methods like addAndGet(int delta)
or incrementAndGet()
(and their counterparts) which allow you to increment/decrement the value of the same instance. Though the class is designed to be used in the context of concurrency, it's also quite useful in other scenarios and probably fits your need.
final AtomicInteger count = new AtomicInteger( 0 ) ;
…
count.incrementAndGet(); // Ignoring the return value.
There are many way you can do this. Those are given bellow:
Suppose your original number is given bellow: double number = 2354548.235;
Using NumberFormat
and Rounding mode
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
decimalFormatter.setRoundingMode(RoundingMode.CEILING);
String fString = decimalFormatter.format(number);
System.out.println(fString);
Using String formatter
System.out.println(String.format("%1$,.2f", number));
In all cases the output will be: 2354548.24
Note:
During rounding you can add RoundingMode
in your formatter. Here are some Rounding mode given bellow:
decimalFormat.setRoundingMode(RoundingMode.CEILING);
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setRoundingMode(RoundingMode.UP);
Here are the imports:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
This is a sample simplelogger.properties
which you can place on the classpath (uncomment the properties you wish to use):
# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=
# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false
# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true
# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true
# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false
Thread.sleep()
is simple for the beginners and may be appropriate for unit tests and proofs of concept.
But please DO NOT use sleep()
for production code. Eventually sleep()
may bite you badly.
Best practice for multithreaded/multicore java applications to use the "thread wait" concept. Wait releases all the locks and monitors held by the thread, which allows other threads to acquire those monitors and proceed while your thread is sleeping peacefully.
Code below demonstrates that technique:
import java.util.concurrent.TimeUnit;
public class DelaySample {
public static void main(String[] args) {
DelayUtil d = new DelayUtil();
System.out.println("started:"+ new Date());
d.delay(500);
System.out.println("half second after:"+ new Date());
d.delay(1, TimeUnit.MINUTES);
System.out.println("1 minute after:"+ new Date());
}
}
DelayUtil
implementation:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class DelayUtil {
/**
* Delays the current thread execution.
* The thread loses ownership of any monitors.
* Quits immediately if the thread is interrupted
*
* @param durationInMillis the time duration in milliseconds
*/
public void delay(final long durationInMillis) {
delay(durationInMillis, TimeUnit.MILLISECONDS);
}
/**
* @param duration the time duration in the given {@code sourceUnit}
* @param unit
*/
public void delay(final long duration, final TimeUnit unit) {
long currentTime = System.currentTimeMillis();
long deadline = currentTime+unit.toMillis(duration);
ReentrantLock lock = new ReentrantLock();
Condition waitCondition = lock.newCondition();
while ((deadline-currentTime)>0) {
try {
lock.lockInterruptibly();
waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
currentTime = System.currentTimeMillis();
}
}
}
Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.
app.directive('stroman', function($compile) {
return {
link: function(scope, el, attrName) {
var newElem = angular.element('<div></div>');
// Copying all of the attributes
for (let prop in attrName.$attr) {
newElem.attr(prop, attrName[prop]);
}
el.replaceWith($compile(newElem)(scope)); // Replacing
}
};
});
Important: Register the directives that you want to use with restrict: 'C'
. Like this:
app.directive('my-directive', function() {
return {
restrict: 'C',
template: 'Hi there',
};
});
You can use like this:
<stroman class="my-directive other-class" randomProperty="8"></stroman>
To get this:
<div class="my-directive other-class" randomProperty="8">Hi there</div>
Protip. If you don't want to use directives based on classes then you can change '<div></div>'
to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class
.
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
I don't recommend storing passwords in a script, but this is a way to what you indicate:
use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );
say ( $user_table{ $name } eq $password ? 'You have gained access.'
: 'Access denied!'
);
Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.
You set the style per element and not by its content:
function init() {
document.getElementById("about").style.color = 'blue';
}
With innerHTML
you get/set the content of an element. So if you would want to modify your title, innerHTML
would be the way to go.
In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style
property of the element itself.
This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.
You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.
An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.
If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.
A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.
The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.
Apache CXF is an example the pattern in #2.
Giving the full access to all wp files to www-data
user (which is in this case the web server user) can be dangerous.
So rather do NOT do this:
chown www-data:www-data -R *
It can be useful however in the moment when you're installing or upgrading WordPress and its plug-ins. But when you finished it's no longer a good idea to keep wp files owned by the web server.
It basically allows the web server to put or overwrite any file in your website. This means that there is a possibility to take over your site if someone manage to use the web server (or a security hole in some .php script) to put some files in your website.
To protect your site against such an attack you should to the following:
All files should be owned by your user account, and should be writable by you. Any file that needs write access from WordPress should be writable by the web server, if your hosting set up requires it, that may mean those files need to be group-owned by the user account used by the web server process.
/
The root WordPress directory: all files should be writable only by your user account, except .htaccess if you want WordPress to automatically generate rewrite rules for you.
/wp-admin/
The WordPress administration area: all files should be writable only by your user account.
/wp-includes/
The bulk of WordPress application logic: all files should be writable only by your user account.
/wp-content/
User-supplied content: intended to be writable by your user account and the web server process.
Within
/wp-content/
you will find:
/wp-content/themes/
Theme files. If you want to use the built-in theme editor, all files need to be writable by the web server process. If you do not want to use the built-in theme editor, all files can be writable only by your user account.
/wp-content/plugins/
Plugin files: all files should be writable only by your user account.
Other directories that may be present with
/wp-content/
should be documented by whichever plugin or theme requires them. Permissions may vary.
Source and additional information: http://codex.wordpress.org/Hardening_WordPress
It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break
is up there with the while
), you could create a variable result = None
and loop while it is None
. You should also adjust the variables and you can replace continue
with the semantically perhaps correct pass
(you don't care if an error occurs, you just want to ignore it) and drop the break
- this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except:
clauses are evil for reasons given in the documentation.
Example incorporating all of the above:
result = None
while result is None:
try:
# connect
result = get_data(...)
except:
pass
# other code that uses result but is not involved in getting it
Note: Lynx has to have been compiled with the --enable-persistent-cookies flag for this to work
When you want to use wget to download some file from a site which requires login, you just need a cookie file. In order to generate the cookie file, I choose lynx. lynx is a text web browser. First you need a configure file for lynx to save cookie. Create a file lynx.cfg. Write these configuration into the file.
SET_COOKIES:TRUE
ACCEPT_ALL_COOKIES:TRUE
PERSISTENT_COOKIES:TRUE
COOKIE_FILE:cookie.file
Then start lynx with this command:
lynx -cfg=lynx.cfg http://the.site.com/login
After you input the username and password, and select 'preserve me on this pc' or something similar. If login successfully, you will see a beautiful text web page of the site. And you logout. The in the current directory, you will find a cookie file named as cookie.file. This is what we need for wget.
Then wget can download file from the site with this command.
wget --load-cookies ./cookie.file http://the.site.com/download/we-can-make-this-world-better.tar.gz
As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.
Don't make anonymous subclasses of Fragment :-)
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound) {
NSLog(@"string does not contain bla");
} else {
NSLog(@"string contains bla!");
}
The key is noticing that rangeOfString:
returns an NSRange
struct, and the documentation says that it returns the struct {NSNotFound, 0}
if the "haystack" does not contain the "needle".
And if you're on iOS 8 or OS X Yosemite, you can now do: (*NOTE: This WILL crash your app if this code is called on an iOS7 device).
NSString *string = @"hello bla blah";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
(This is also how it would work in Swift)
Just single if conditions
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
@foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**@if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
@endif**>
{{ ucfirst($categoryType->title) }}</option>
@endforeach
</select>
Your problem can be caused by different things. I will provide you three possible scenarios in Linux:
When you use scp name , you mean that your File name is in Home directory. When it is in Home but inside in another Folder, for example, my_folder, you should write:
scp /home/my-username/my_folder/name [email protected]:/Path....
You must know the File Permission your File has. If you have Read-only you should change it.
To change the Permission:
As Root ,sudo caja
( the default file manager for the MATE Desktop) or another file manager ,then with you Mouse , right-click to the File name , select Properties + Permissions
and change it on Group and Other to Read and write .
Or with chmod .
Maybe you remote machine or Server can only communicate with a Port Number, so you should write -P and the Port Number.
scp -P 22 /home/my-username/my_folder/name [email protected] /var/www/html
Try this
$('#D25,#E37,#E31,#F37,#E16,#E40,#F16,#F40,#E41,#F41').bind('DOMNodeInserted DOMNodeRemoved',function(){
// your code;
});
Do not use this. This may crash the page.
$('mydiv').bind("DOMSubtreeModified",function(){
alert('changed');
});
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
For version 3.0 (Community Edition):
File -> Settings -> Editor (under IDE Settings) -> Appearance -> check 'Show line numbers'
This should work for matches that might overlap:
public static void main(String[] args) {
String input = "aaaaaaaa";
String regex = "aa";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println(count);
}
Try setting the models to environment and static. That fix my issue.
You can have a table variable as a return type and then update or insert on a table based on that output. In other words, you can set the variable output as the original table, make the modifications and then do an insert to the original table from function output. It is a little hack but if you insert the @output_table from the original table and then say for example: Insert into my_table select * from my_function
then you can achieve the result.
The only half-way proper way to do this is
<p>
<span style="float: right">Text on the right</span>
<span style="float: left">Text on the left</span>
</p>
however, this will get you into trouble if the text overflows. If you can, use div
s (block level elements) and give them a fixed width
.
A table (or a number of div
s with the according display: table / table-row / table-cell
properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.
One possible workaround would be using a "frame-breaker" script as described here
You just need to alter the "if" statement to check for your allowed domains.
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
//your domain check goes here
if(top.location.host != "allowed.domain1.com" && top.location.host == "allowed.domain2.com")
top.location = self.location;
}
This workaround would be safe, I think. because with javascript not enabled you will have no security concern about a malicious website framing your page.
I think I know why you want to avoid that. But maybe try & catch !== try & catch. ;o) This came into my mind:
var json_verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};
So you may also dirty clip to the JSON object, like:
JSON.verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};
As this as encapsuled as possible, it may not break on error.
The solution above not working for the latest version on PostgreSQL. I found this way to convert epoch time being stored in number and int column type is on PostgreSQL 13:
SELECT TIMESTAMP 'epoch' + (<table>.field::int) * INTERVAL '1 second' as started_on from <table>;
For more detail explanation, you can see here https://www.yodiw.com/convert-epoch-time-to-timestamp-in-postgresql/#more-214
EXEC sp_helpuser
or
SELECT * FROM sysusers
Both of these select all the users of the current database (not the server).
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
Paste this code after setContentView or into onCreate
if you have a color code use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#408ed4")));
if you want a specific code from Color library use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
<body ng-app="app">
<button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'" class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
<div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
<div class="panel-heading">Take Quiz</div>
<div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">
<button type="button" class="btn btn-default">Start Quiz</button>
</div>
</div>
</body>
Button toggle and change header of button and show/hide div panel. See the Plunkr
editTextObject.setText(CharSequence)
http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)
I wrote this one:
public static String join(Collection<String> col, String delim) {
StringBuilder sb = new StringBuilder();
Iterator<String> iter = col.iterator();
if (iter.hasNext())
sb.append(iter.next());
while (iter.hasNext()) {
sb.append(delim);
sb.append(iter.next());
}
return sb.toString();
}
Collection
isn't supported by JSP, so for TLD I wrote:
public static String join(List<?> list, String delim) {
int len = list.size();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(list.get(0).toString());
for (int i = 1; i < len; i++) {
sb.append(delim);
sb.append(list.get(i).toString());
}
return sb.toString();
}
and put to .tld
file:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
<function>
<name>join</name>
<function-class>com.core.util.ReportUtil</function-class>
<function-signature>java.lang.String join(java.util.List, java.lang.String)</function-signature>
</function>
</taglib>
and use it in JSP files as:
<%@taglib prefix="funnyFmt" uri="tag:com.core.util,2013:funnyFmt"%>
${funnyFmt:join(books, ", ")}
The current(initial) directory of shell script is the directory from which you have called the script.
assuming you want the line height to be 20 px
.restart:before {
content: 'First Line';
padding-bottom:20px;
}
.restart:after {
content: 'Second-line';
position:absolute;
top:40px;
}
This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the log
-related stuff) add them.
So, there's a lot of Python code out there that does things like:
fw.write('\n'.join(line_list) + '\n')
or
fw.write(line + '\n' for line in line_list)
Either one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up…
But you should only do this if you can't avoid it.
It's better if you can create/keep the newlines in the first place—as in Greg Hewgill's suggestions:
line_list.append(new_line + "\n")
And it's even better if you can work at a higher level than raw lines of text, e.g., by using the csv module in the standard library, as esuaro suggests.
For example, right after defining fw
, you might do this:
cw = csv.writer(fw, delimiter='|')
Then, instead of this:
new_line = d[looking_for]+'|'+'|'.join(columns[1:])
line_list.append(new_line)
You do this:
row_list.append(d[looking_for] + columns[1:])
And at the end, instead of this:
fw.writelines(line_list)
You do this:
cw.writerows(row_list)
Finally, your design is "open a file, then build up a list of lines to add to the file, then write them all at once". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a csv.writer
, it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once—but once you've moved the open
all the way to the opposite end of the program from the write
, you've pretty much lost any benefits of all-at-once.)
If you want to return a File to be downloaded, specially if you want to integrate with some javascript libs of file upload/download, then the code bellow should do the job:
@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
@Context HttpServletResponse response) throws IOException {
try {
//Get your File or Object from wherever you want...
//you can use the key parameter to indentify your file
//otherwise it can be removed
//let's say your file is called "object"
response.setContentLength((int) object.getContentLength());
response.setHeader("Content-Disposition", "attachment; filename="
+ object.getName());
ServletOutputStream outStream = response.getOutputStream();
byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
DataInputStream in = new DataInputStream(
object.getDataInputStream());
int length = 0;
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
outStream.write(bbuf, 0, length);
}
in.close();
outStream.flush();
} catch (S3ServiceException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
return Response.ok().build();
}
int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];
This is one of many ways.
If you want a FAB looking circular button and you are using the official Material Component library you can easily do it like this:
<com.google.android.material.button.MaterialButton
style="@style/Widget.MaterialComponents.ExtendedFloatingActionButton"
app:cornerRadius="28dp"
android:layout_width="56dp"
android:layout_height="56dp"
android:text="1" />
Result:
If you change the size of the button, just be careful to use half of the button size as app:cornerRadius
.
Here is a full example with the date formatted in YYYY-MM-DD
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="//cdn.jsdelivr.net/webshim/1.14.5/polyfiller.js"></script>
<script>
webshims.setOptions('forms-ext', {types: 'date'});
webshims.polyfill('forms forms-ext');
$.webshims.formcfg = {
en: {
dFormat: '-',
dateSigns: '-',
patterns: {
d: "yy-mm-dd"
}
}
};
</script>
<input type="date" />
You can also use my custom HtmlHelpers in Griffin.MvcContrib. The following code:
@Html2.CheckBoxesFor(model => model.InputType) <br />
@Html2.RadioButtonsFor(model => model.InputType) <br />
@Html2.DropdownFor(model => model.InputType) <br />
Generates:
I really like cottsaks solution and think its very clearly explained. my only addition was to alter step 2 as follows
public abstract class MyController : Controller
{
#region Http404 handling
protected override void HandleUnknownAction(string actionName)
{
//if controller is ErrorController dont 'nest' exceptions
if(this.GetType() != typeof(ErrorController))
this.InvokeHttp404(HttpContext);
}
public ActionResult InvokeHttp404(HttpContextBase httpContext)
{
IController errorController = ObjectFactory.GetInstance<ErrorController>();
var errorRoute = new RouteData();
errorRoute.Values.Add("controller", "Error");
errorRoute.Values.Add("action", "Http404");
errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
errorController.Execute(new RequestContext(
httpContext, errorRoute));
return new EmptyResult();
}
#endregion
}
Basically this stops urls containing invalid actions AND controllers from triggering the exception routine twice. eg for urls such as asdfsdf/dfgdfgd
If you read the Keras documentation entry for Dense
, you will see that this call:
Dense(16, input_shape=(5,3))
would result in a Dense
network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x)
transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])]
with shape (5, 16)
. In order to have the behavior you specify you may first Flatten
your input to a 15-d vector and then apply Dense
:
model = Sequential()
model.add(Flatten(input_shape=(3, 2)))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(4))
model.compile(loss='mean_squared_error', optimizer='SGD')
EDIT: As some people struggled to understand - here you have an explaining image:
Do you need a type attribute at all? If you're using HTML5, no. Otherwise, yes. HTML 4.01 and XHTML 1.0 specifies the type
attribute as required while HTML5 has it as optional, defaulting to text/javascript
. HTML5 is now widely implemented, so if you use the HTML5 doctype, <script>...</script>
is valid and a good choice.
As to what should go in the type attribute, the MIME type application/javascript
registered in 2006 is intended to replace text/javascript
and is supported by current versions of all the major browsers (including Internet Explorer 9). A quote from the relevant RFC:
This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". Use of experimental and unregistered media types, as listed in part above, is discouraged. The media types,
* application/javascript * application/ecmascript
which are also defined in this document, are intended for common use and should be used instead.
However, IE up to and including version 8 doesn't execute script inside a <script>
element with a type
attribute of either application/javascript
or application/ecmascript
, so if you need to support old IE, you're stuck with text/javascript
.
Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.
I.e.
byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"
Which might not be what you intend to do.
If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.
The more_itertools
project extends itertools.islice
to handle negative indices.
Example
import more_itertools as mit
iterable = 'ABCDEFGH'
list(mit.islice_extended(iterable, 1, -1))
# Out: ['B', 'C', 'D', 'E', 'F', 'G']
Therefore, you can elegantly apply it slice elements between the first and last items of an iterable:
for car in mit.islice_extended(cars, 1, -1):
# do something
You need the permission of superuser levels to install React. In Linux/Unix the superuser account is generally named 'root'.
To get superuser privilege just run the following command on your terminal:
sudo -i
and then simply run the command to install React:
npm install -g create-react-app
However, the reactjs team encourages us to use the following command instead of installing a global package.
npx create-react-app app_name
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
It can't be stated enough that you can use console.debug(object) for this. This technique will save you literally hundreds of hours a year if you do this for a living :p
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.
Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.
If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.
However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.
You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials
only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie
header.
You can specify how many times you want the previous item to match by using {min,max}
.
{[0-9]{1,3}:[0-9]{1,3}}
Also, you can use \d
for digits instead of [0-9]
for most regex flavors:
{\d{1,3}:\d{1,3}}
You may also want to consider escaping the outer {
and }
, just to make it clear that they are not part of a repetition definition.
If you have already installed 2.2.5 and set as current ruby version, but still showing the same error even if the Ruby version 2.3.0 is not even installed, then just install the bundler.
gem install bundler
and then:
bundle install
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
container
class has 15px left & right padding, so if you want to remove this padding, use following, because row
class has -15px left & right margin.
<div class="container">
<div class="row">
<img class='img-responsive' src="#" alt="" />
</div>
</div>
First of all, I can only agree that Arrays.asList(T...)
is clearly the best solution for Wrapper types or arrays with non-primtive datatypes. This method calls a constructor of a simple private static AbstractList
implementation in the Arrays
class which basically saves the given array reference as field and simulates a list by overriding the needed methods.
If you can choose between a primtive type or a Wrapper type for your array, I would use the Wrapper type for such situations but of course, it's not always useful or required.
There would be only two possibilities you can do:
1) You can create a class with a static method for each primitive datatype array (boolean, byte, short, int, long, char, float, double
returning an Iterable<
WrapperType>
. These methods would use anonymous classes of Iterator
(besides Iterable
) which are allowed to contain the reference of the comprising method's argument (for example an int[]
) as field in order to implement the methods.
-> This approach is performant and saves you memory (except for the memory of the newly created methods, even though, using Arrays.asList()
would take memory in the same way)
2) Since arrays don't have methods (as to be read on the side you linked) they can't provide an Iterator
instance either. If you really are too lazy to write new classes, you must use an instance of an already existing class that implements Iterable
because there is no other way around than instantiating Iterable
or a subtype.
The ONLY way to create an existing Collection derivative implementing Iterable
is to use a loop (except you use anonymous classes as described above) or you instantiate an Iterable
implementing class whose constructor allows a primtive type array (because Object[]
doesn't allow arrays with primitive type elements) but as far as I know, the Java API doesn't feature a class like that.
The reason for the loop can be explained easily:
for each Collection you need Objects and primtive datatypes aren't objects. Objects are much bigger than primitive types so that they require additional data which must be generated for each element of the primitive type array. That means if two ways of three (using Arrays.asList(T...)
or using an existing Collection) require an aggregate of objects, you need to create for each primitive value of your int[]
array the wrapper object. The third way would use the array as is and use it in an anonymous class as I think it's preferable due to fast performance.
There is also a third strategy using an Object
as argument for the method where you want to use the array or Iterable
and it would require type checks to figure out which type the argument has, however I wouldn't recommend it at all as you usually need to consider that the Object hasn't always the required type and that you need seperate code for certain cases.
In conclusion, it's the fault of Java's problematic Generic Type system which doesn't allow to use primitive types as generic type which would save a lot of code by using simply Arrays.asList(T...)
. So you need to program for each primitive type array, you need, such a method (which basically makes no difference to the memory used by a C++ program which would create for each used type argument a seperate method.
You can also save a reference to module's global scope outside the (module.)exports.somemodule definition:
var _this = this;
exports.somefunction = function() {
console.log('hello');
}
exports.someotherfunction = function() {
_this.somefunction();
}
One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.
Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.
VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)
On Error Resume Next
is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.
import ConfigParser
import os
class Parser(object):
"""attributes may need additional manipulation"""
def __init__(self, section):
"""section to retun all options on, formatted as an object
transforms all comma-delimited options to lists
comma-delimited lists with colons are transformed to dicts
dicts will have values expressed as lists, no matter the length
"""
c = ConfigParser.RawConfigParser()
c.read(os.path.join(os.path.dirname(__file__), 'config.cfg'))
self.section_name = section
self.__dict__.update({k:v for k, v in c.items(section)})
#transform all ',' into lists, all ':' into dicts
for key, value in self.__dict__.items():
if value.find(':') > 0:
#dict
vals = value.split(',')
dicts = [{k:v} for k, v in [d.split(':') for d in vals]]
merged = {}
for d in dicts:
for k, v in d.items():
merged.setdefault(k, []).append(v)
self.__dict__[key] = merged
elif value.find(',') > 0:
#list
self.__dict__[key] = value.split(',')
So now my config.cfg
file, which could look like this:
[server]
credentials=username:admin,password:$3<r3t
loggingdirs=/tmp/logs,~/logs,/var/lib/www/logs
timeoutwait=15
Can be parsed into fine-grained-enough objects for my small project.
>>> import config
>>> my_server = config.Parser('server')
>>> my_server.credentials
{'username': ['admin'], 'password', ['$3<r3t']}
>>> my_server.loggingdirs:
['/tmp/logs', '~/logs', '/var/lib/www/logs']
>>> my_server.timeoutwait
'15'
This is for very quick parsing of simple configs, you lose all ability to fetch ints, bools, and other types of output without either transforming the object returned from Parser
, or re-doing the parsing job accomplished by the Parser class elsewhere.
there are packages that can simulate interfaces .
you can use es6-interface
Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".
And also it would require to run the docker in privileged mode, so the commands would be:
sudo chmod 757 /var/run/docker.sock
docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...
Calling the isHTML()
method after the instance Body
property (I mean $mail->Body
) has been set solved the problem for me:
$mail->Subject = $Subject;
$mail->Body = $Body;
$mail->IsHTML(true); // <=== call IsHTML() after $mail->Body has been set.
If your emulators were working and now they aren't due to Avast...
Avast no longer has the option for "Enable Hardware-assisted Virtualization" in Troubleshooting. (it's now March 2017)
Avast captures "emulator.exe", which disables emulators,and stows it in the Virus chest. Open the chest, "Restore and add to exclusions" and your emulator works again...
DECLARE @FDate DATETIME='05-05-2019' /*This is first date*/
GETDATE()/*This is Current date*/
SELECT (DATEDIFF(DAY,(@LastDate),GETDATE())) As DifferenceDays/*this query will return no of days between firstdate & Current date*/
implements
means a behaviour will be defined for abstract
methods (except for abstract classes obviously), you define the implementation.
extends
means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends
another interface instead of implementing it.
On a side note, remember that even if an abstract
class can define abstract
methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
you would need a parking lot, that holds a multi-dimensional array (specified in the constructor) of a type "space". The parking lot can keep track of how many spaces are taken via calls to functions that fill and empty spaces.Space can hold an enumerated type that tells what kind of space it is. Space also has a method taken(). for the valet parking, just find the first space thats open and put the car there. You will also need a Car object to put in the space, that holds whether it is a handicapped, compact, or regular vehicle.
class ParkingLot
{
Space[][] spaces;
ParkingLot(wide, long); // constructor
FindOpenSpace(TypeOfCar); // find first open space where type matches
}
enum TypeOfSpace = {compact, handicapped, regular };
enum TypeOfCar = {compact, handicapped, regular };
class Space
{
TypeOfSpace type;
bool empty;
// gets and sets here
// make sure car type
}
class car
{
TypeOfCar type;
}
I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.
You can find it on Github
Here are the simple steps to creating and using custom iterators:
typedef blRawIterator< Type > iterator;
typedef blRawIterator< const Type > const_iterator;
iterator begin(){return iterator(&m_data[0]);};
const_iterator cbegin()const{return const_iterator(&m_data[0]);};
Finally, onto defining our custom iterator classes:
NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.
In this example, I define a random access iterator and a reverse random access iterator:
//-------------------------------------------------------------------
// Raw iterator with random access
//-------------------------------------------------------------------
template<typename blDataType>
class blRawIterator
{
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = blDataType;
using difference_type = std::ptrdiff_t;
using pointer = blDataType*;
using reference = blDataType&;
public:
blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
~blRawIterator(){}
blRawIterator<blDataType>& operator=(const blRawIterator<blDataType>& rawIterator) = default;
blRawIterator<blDataType>& operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
operator bool()const
{
if(m_ptr)
return true;
else
return false;
}
bool operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
bool operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
blRawIterator<blDataType>& operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
blRawIterator<blDataType>& operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
blRawIterator<blDataType>& operator++(){++m_ptr;return (*this);}
blRawIterator<blDataType>& operator--(){--m_ptr;return (*this);}
blRawIterator<blDataType> operator++(int){auto temp(*this);++m_ptr;return temp;}
blRawIterator<blDataType> operator--(int){auto temp(*this);--m_ptr;return temp;}
blRawIterator<blDataType> operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
blRawIterator<blDataType> operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
difference_type operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
blDataType& operator*(){return *m_ptr;}
const blDataType& operator*()const{return *m_ptr;}
blDataType* operator->(){return m_ptr;}
blDataType* getPtr()const{return m_ptr;}
const blDataType* getConstPtr()const{return m_ptr;}
protected:
blDataType* m_ptr;
};
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Raw reverse iterator with random access
//-------------------------------------------------------------------
template<typename blDataType>
class blRawReverseIterator : public blRawIterator<blDataType>
{
public:
blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
~blRawReverseIterator(){}
blRawReverseIterator<blDataType>& operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
blRawReverseIterator<blDataType>& operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
blRawReverseIterator<blDataType>& operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
blRawReverseIterator<blDataType>& operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
blRawReverseIterator<blDataType>& operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
blRawReverseIterator<blDataType>& operator++(){--this->m_ptr;return (*this);}
blRawReverseIterator<blDataType>& operator--(){++this->m_ptr;return (*this);}
blRawReverseIterator<blDataType> operator++(int){auto temp(*this);--this->m_ptr;return temp;}
blRawReverseIterator<blDataType> operator--(int){auto temp(*this);++this->m_ptr;return temp;}
blRawReverseIterator<blDataType> operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
blRawReverseIterator<blDataType> operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
difference_type operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
blRawIterator<blDataType> base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
};
//-------------------------------------------------------------------
Now somewhere in your custom container class:
template<typename blDataType>
class blCustomContainer
{
public: // The typedefs
typedef blRawIterator<blDataType> iterator;
typedef blRawIterator<const blDataType> const_iterator;
typedef blRawReverseIterator<blDataType> reverse_iterator;
typedef blRawReverseIterator<const blDataType> const_reverse_iterator;
.
.
.
public: // The begin/end functions
iterator begin(){return iterator(&m_data[0]);}
iterator end(){return iterator(&m_data[m_size]);}
const_iterator cbegin(){return const_iterator(&m_data[0]);}
const_iterator cend(){return const_iterator(&m_data[m_size]);}
reverse_iterator rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
reverse_iterator rend(){return reverse_iterator(&m_data[-1]);}
const_reverse_iterator crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
const_reverse_iterator crend(){return const_reverse_iterator(&m_data[-1]);}
.
.
.
// This is the pointer to the
// beginning of the data
// This allows the container
// to either "view" data owned
// by other containers or to
// own its own data
// You would implement a "create"
// method for owning the data
// and a "wrap" method for viewing
// data owned by other containers
blDataType* m_data;
};
Another possible cause for this error message is if the HTTP Method is blocked by the server or load balancer.
It seems to be standard security practice to block unused HTTP Methods. We ran into this because HEAD was being blocked by the load balancer (but, oddly, not all of the load balanced servers, which caused it to fail only some of the time). I was able to test that the request itself worked fine by temporarily changing it to use the GET method.
The error code on iOS was: Error requesting App Code: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
This might be a megabit to late but you can use continue 2
.
Some php builds / configs will output this warning:
PHP Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?
For example:
$i = 1;
while ($i <= 10) {
$mod = $i % 4;
echo "\r\n out $i";
$i++;
switch($mod)
{
case 0:
break;
case 2:
continue;
break;
default:
continue 2;
break;
}
echo " is even";
}
This will output:
out 1
out 2 is even
out 3
out 4 is even
out 5
out 6 is even
out 7
out 8 is even
out 9
out 10 is even
Tested with PHP 5.5 and higher.
First install the: @babel/plugin-proposal-class-properties as dev dependency:
npm install @babel/plugin-proposal-class-properties --save-dev
Then edit your .babelrc so it will be exact like this:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
[
"@babel/plugin-proposal-class-properties"
]
]
}
.babelrc file located in the root directory, where package.json is.
Note that you should re-start your webpack dev server to changes take affect.
To delete by value :
modified_array = np.delete(original_array, np.where(original_array == value_to_delete))
Use "attr" method in jquery.
$('.test').click(function(){
var id = $(this).attr('id');
});
While you are switching, switch to PDO instead of mysqli, It helps you write database agnositc code and have better features for prepared statements.
Bindparam for PDO: http://se.php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->bindParam(':value1', 'foo');
$sth->bindParam(':value2', 'bar');
$sth->execute();
or:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = ? && field2 = ?");
$sth->bindParam(1, 'foo');
$sth->bindParam(2, 'bar');
$sth->execute();
or execute with the parameters as an array:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->execute(array(':value1' => 'foo' , ':value2' => 'bar'));
It will be easier for you if you would like your application to be able to run on different databases in the future.
I also think you should invest some time in using some of the classes from Zend Framwework whilst working with PDO. Check out their Zend_Db and more specifically [Zend_Db_Factory][2]. You do not have to use all of the framework or convert your application to the MVC pattern, but using the framework and reading up on it is time well spent.
Try to change directory to where the .box
is saved
Run vagrant box add my-box downloaded.box
, this may work as it avoids absolute path (on Windows?).
A simple and efficient way from http://akinas.com/pages/en/blog/mysql_random_row/
SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM 'SELECT * FROM table LIMIT ?, 1'; EXECUTE get_stmt USING @i;
I just had this problem, it turns it was just because I was using x64 version of the opencv file. Tried the x86 and it worked.
One more example for lists:
// constructs the elements in place.
emplace_back("element");
// creates a new object and then copies (or moves) that object.
push_back(ExplicitDataType{"element"});
I just solved this kind of a problem. What I've learned is:
my.cnf
and set the bind-address = your.mysql.server.address
under [mysqld]
check if it's running
mysql -u root -h your.mysql.server.address –p
create a user (usr or anything) with % as domain and grant her access to the database in question.
mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)
you should be able to now connect mysql server form your client server php script.
Note that the OpenSSL CLI uses a weak non-standard algorithm to convert the passphrase to a key, and installing GPG results in various files added to your home directory and a gpg-agent background process running. If you want maximum portability and control with existing tools, you can use PHP or Python to access the lower-level APIs and directly pass in a full AES Key and IV.
Example PHP invocation via Bash:
IV='c2FtcGxlLWFlcy1pdjEyMw=='
KEY='Twsn8eh2w2HbVCF5zKArlY+Mv5ZwVyaGlk5QkeoSlmc='
INPUT=123456789023456
ENCRYPTED=$(php -r "print(openssl_encrypt('$INPUT','aes-256-ctr',base64_decode('$KEY'),OPENSSL_ZERO_PADDING,base64_decode('$IV')));")
echo '$ENCRYPTED='$ENCRYPTED
DECRYPTED=$(php -r "print(openssl_decrypt('$ENCRYPTED','aes-256-ctr',base64_decode('$KEY'),OPENSSL_ZERO_PADDING,base64_decode('$IV')));")
echo '$DECRYPTED='$DECRYPTED
This outputs:
$ENCRYPTED=nzRi252dayEsGXZOTPXW
$DECRYPTED=123456789023456
You could also use PHP's openssl_pbkdf2
function to convert a passphrase to a key securely.
Use this code for read file with all type of extension file.
string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");
You need to generate a font first. You must use the MakeFont
utility included within the FPDF package. I used on Linux this a bit extended script from the demo:
<?php
// Generation of font definition file for tutorial 7
require('../makefont/makefont.php');
$dir = opendir('/usr/share/fonts/truetype/ttf-dejavu/');
while (($relativeName = readdir($dir)) !== false) {
if ($relativeName == '..' || $relativeName == '.')
continue;
MakeFont("/usr/share/fonts/truetype/ttf-dejavu/$relativeName",'ISO-8859-2');
}
?>
Then I copied generated files to the font
directory of my web and used this:
$pdf->Cell(80,70, iconv('UTF-8', 'ISO-8859-2', 'Bunka jedna'),1);
(I was working on a table.) That worked for my language (Bunka jedna is czech for Cell one). Czech language belongs to central european languages, also ISO-8859-2. Regrettably the user of FPDF is forced to lost advantages of UTF-8 encoding. You cannot get this in your PDF:
Mestecko Fruens Bøge
Danish letter ø
becomes r
in ISO-8859-2.
Suggestion of solution: You need to get a Greek font, generate the font using proper encoding (ISO-8859-7) and use iconv
with the same target encoding as the one the font has been generated with.
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Note that I prefer the code to be short.
List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.ToList();
or with a simple foreach
:
List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
if (item.Selected) selected.Add(item);
If you just want the ListItem.Value
:
List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
You are looking for dynamic_cast<B*>(pointer)
You should be able to use the variable name directly
ansible_ssh_host
Or you can go through hostvars without having to specify the host literally
by using the magic variable inventory_hostname
hostvars[inventory_hostname].ansible_ssh_host
The best possible solution that can be also used used inline:
end($arr) && false ?: key($arr)
This solution is only expression/statement and provides good is not the best possible performance.
Inlined example usage:
$obj->setValue(
end($arr) && false ?: key($arr) // last $arr key
);
UPDATE: In PHP 7.3+: use (of course) the newly added array_key_last()
method.
I finally found a way to use CardView in ADT/Eclipse. It's actually pretty easy:
android.support.v7.cardview
exploded-aar
folder in Android Studio and copy the following files to these locations:
Adding libraries with resources
here: https://developer.android.com/tools/support-library/setup.htmlAs an alternative to having to create a new Android Studio project in order to get the AAR's content, you could also simply find and unzip the AAR from the local maven repo. Just follow the steps provided by Andrew Chen below.
Please note the CardView library might not be available in source- and ADT-compatible-form because it's still only a preview and a WIP. As there might be bug fixes and improvements in following releases, it's important to keep the library up-to-date, which is easy using the Gradle dependency, but must be done manually when using the steps provided above.
In Eclipse Helios "Java EE Module Dependencies" in the project properties has been replaced with "Deployment Assembly".
So for solving this problem with Eclipse Helios, the way I did it is the following:
This solves the problem, but if you want to check what has happened in "Deployment Assembly", open the project properties again, select "Deployment Assembly" and you'll see that standard.jar and jstl.jar have been added to WEB-INF/lib folder.
You can use this command
$ git rev-list HEAD
You can also use the head
Unix command to show the latest n
HEAD
commits like
$ git rev-list HEAD | head - 2
The var_dump
function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.
The print_r()
displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Example:
$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj)
will display below output in the screen.
object(stdClass)#1 (3) {
[0]=> string(12) "qualitypoint"
[1]=> string(12) "technologies"
[2]=> string(5) "India"
}
And, print_r($obj)
will display below output in the screen.
stdClass Object (
[0] => qualitypoint
[1] => technologies
[2] => India
)
More Info
There is no way to set maxHeight. But you can set the Height.
To do that you will need to discovery the height of each item of you scrollView. After that just set your scrollView height to numberOfItens * heightOfItem.
To discovery the height of an item do that:
View item = adapter.getView(0, null, scrollView);
item.measure(0, 0);
int heightOfItem = item.getMeasuredHeight();
To set the height do that:
// if the scrollView already has a layoutParams:
scrollView.getLayoutParams().height = heightOfItem * numberOfItens;
// or
// if the layoutParams is null, then create a new one.
scrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, heightOfItem * numberOfItens));
I kept running into this problem every time I tried opening eclipse. I resolved it by unplugging my android device's USB from my laptop, and eclipse worked again.
I got this message when I tried to git clone
a repo that was not mine. The fix was to fork and then clone.
jQuery UI extends the jQuery native toggleClass
to take a second optional parameter: duration
toggleClass( class, [duration] )
I had the same problem, using sudo ng serve
seemed to "solve" the problem unsatisfactorily. Using sudo
is not satisfactory IMO.
I checked my INotify count versus my default limit (8192) using:
lsof | grep inotify | wc -l
The value returned by the above command was way less than the limit. So the INotify solution didn't seem to apply to my problem.
I also checked permissions and ownership, both seemed ok, comparable to another project that worked.
Out of frustration I restarted VS Code. Basically I closed all instances, I had two running and re-opened both following which the problem went away.
I am leaning towards a possible bug somewhere. This is something to consider before turning your system inside out. Fortunately/Unfortunately this problem hasn't occurred again, I'll dig deeper if it does.
you can achive it with group join
var result = (from c in Customers
join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
Select new { customer = c, orderItems = g});
c is Customer and g is the customers order items.
Replace the value in select statement itself...
(CASE WHEN Mobile LIKE '966%' THEN (select REPLACE(CAST(Mobile AS nvarchar(MAX)),'966','0')) ELSE Mobile END)
I tried many solutions for this, and this is the one that worked for me :
1.commit/save container to new image :
ps:"Our container CONTAINER_NAME has a mounted volume at '/var/home'" ( you have to inspect your container to specify its volume path : # docker inspect CONTAINER_NAME )
Now when you look at ${pwd}/backup , you will find our volume under tar format.
Until now, we have our conatainer's image 'IMAGE_NAME.tar' and its volume 'volume_backup.tar'.
Now you can , recreate the same old container on a new host.
Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true)
first if you're accessing it from a different class.
import java.lang.reflect.*;
class Other
{
private String str;
public void setStr(String value)
{
str = value;
}
}
class Test
{
public static void main(String[] args)
// Just for the ease of a throwaway test. Don't
// do this normally!
throws Exception
{
Other t = new Other();
t.setStr("hi");
Field field = Other.class.getDeclaredField("str");
field.setAccessible(true);
Object value = field.get(t);
System.out.println(value);
}
}
And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.
Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;
my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length
Or, you can iterate over this array by adding the following script:
for element in "${my_array[@]}"
do
echo "${element}"
done
Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).
If you'd like to use CSS3, you can do it pretty simply using background-size, like so:
background-size: 100%;
It is supported by all major browsers (including IE9+). If you'd like to get it working in IE8 and before, check out the answers to this question.
Call parent.remove(panel)
, where parent
is the container that you want the frame in and panel
is the panel you want to add.
[u'ABC']
would be a one-element list of unicode strings. Beautiful Soup always produces Unicode. So you need to convert the list to a single unicode string, and then convert that to ASCII.
I don't know exaxtly how you got the one-element lists; the contents member would be a list of strings and tags, which is apparently not what you have. Assuming that you really always get a list with a single element, and that your test is really only ASCII you would use this:
soup[0].encode("ascii")
However, please double-check that your data is really ASCII. This is pretty rare. Much more likely it's latin-1 or utf-8.
soup[0].encode("latin-1")
soup[0].encode("utf-8")
Or you ask Beautiful Soup what the original encoding was and get it back in this encoding:
soup[0].encode(soup.originalEncoding)
double *ptr = malloc(sizeof(double *) * TIME); /* ... */ for(tcount = 0; tcount <= TIME; tcount++) ^^
<=
to <
or alloc
SIZE + 1
elementsmalloc
is wrong, you'll want sizeof(double)
instead of
sizeof(double *)
ouah
comments, although not directly linked to your corruption problem, you're using *(ptr+tcount)
without initializing itptr[tcount]
instead of *(ptr + tcount)
malloc
+ free
since you already know SIZE
'async': false
says it's depreciated. I did notice if I run console.log('test1');
on ajax success, then console.log('test2');
in normal js after the ajax function, test2
prints before test1
so the issue is an ajax call has a small delay, but doesn't stop the rest of the function to get results. The variable simply, was not set "yet", so you need to delay the next function.
function runPHP(){
var input = document.getElementById("input1");
var result = 'failed to run php';
$.ajax({ url: '/test.php',
type: 'POST',
data: {action: 'test'},
success: function(data) {
result = data;
}
});
setTimeout(function(){
console.log(result);
}, 1000);
}
on test.php (incase you need to test this function)
function test(){
print 'ran php';
}
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = htmlentities($_POST['action']);
switch($action) {
case 'test' : test();break;
}
}
you must put object in your JSX, It`s easy way to do this just see my simple code here:
const link = [
{
name: "Cold Drink",
link: "/coldDrink"
},
{
name: "Hot Drink",
link: "/HotDrink"
},
{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :
const links = (this.props.link);
{links.map((item, i) => (
<li key={i}>
<Link to={item.link}>{item.name}</Link>
</li>
))}
I hope this answer will be helpful for you ...:)
The simplest way:
string input = null;
Color color = Color.White;
TextBoxText_Changed(object sender, EventsArgs e)
{
input = TextBox.Text;
}
Button_Click(object sender, EventsArgs e)
{
color = Color.FromName(input)
}
The answer, in a few words
In your example, itsProblem
is a local variable.
Your must use self
to set and get instance variables. You can set it in the __init__
method. Then your code would be:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
But if you want a true class variable, then use the class name directly:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)
But be careful with this one, as theExample.itsProblem
is automatically set to be equal to Example.itsProblem
, but is not the same variable at all and can be changed independently.
Some explanations
In Python, variables can be created dynamically. Therefore, you can do the following:
class Example(object):
pass
Example.itsProblem = "problem"
e = Example()
e.itsSecondProblem = "problem"
print Example.itsProblem == e.itsSecondProblem
prints
True
Therefore, that's exactly what you do with the previous examples.
Indeed, in Python we use self
as this
, but it's a bit more than that. self
is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self
or not.
Which means you can do:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
or:
class Example(object):
def __init__(my_super_self):
my_super_self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
It's exactly the same. The first argument of ANY object method is the current object, we only call it self
as a convention. And you add just a variable to this object, the same way you would do it from outside.
Now, about the class variables.
When you do:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?
Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.
As a conclusion, never use class variables to set default values to object variables. Use __init__
for that.
Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.
Wrap the text within the list item with a span (or some other element) and apply the bullet color to the list item and the text color to the span.
find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -I 'pigz -9' -cf target.tgz
for multicore or just for one core:
find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -czf target.tgz
I ran into a similar issue today - my ruby version didn't match my rvm installs.
> ruby -v
ruby 2.0.0p481
> rvm list
rvm rubies
ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.3 [ x86_64 ]
Also, rvm current
failed.
> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
The error message recommended this useful command, which resolved the issue for me:
> rvm get stable --auto-dotfiles
Swift 3.0
If you don't want to show user location in map, but just want to store it in firebase or some where else then follow this steps,
import MapKit
import CoreLocation
Now use CLLocationManagerDelegate on your VC and you must override the last three methods shown below. You can see how the requestLocation() method will get you the current user location using these methods.
class MyVc: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
isAuthorizedtoGetUserLocation()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
}
//if we have no permission to access user location, then ask user for permission.
func isAuthorizedtoGetUserLocation() {
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
}
//this method will be called each time when a user change his location access preference.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("User allowed us to access location")
//do whatever init activities here.
}
}
//this method is called by the framework on locationManager.requestLocation();
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did location updates is called")
//store the user location here to firebase or somewhere
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Did location updates is called but failed getting location \(error)")
}
}
Now you can code the below call once user sign in to your app. When requestLocation() is invoked it will further invoke didUpdateLocations above and you can store the location to Firebase or anywhere else.
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation();
}
if you are using GeoFire then in the didUpdateLocations method above you can store the location as below
geoFire?.setLocation(locations.first, forKey: uid) where uid is the user id who logged in to the app. I think you will know how to get UID based on your app sign in implementation.
Last but not least, go to your Info.plist and enable "Privacy -Location when in Use Usage Description."
When you use simulator to test it always give you one custom location that you configured in Simulator -> Debug -> Location.
Right-click on the column header and select Format Cells, the chose Date and select the desired date format. Those that are not recognized are ambiguous, and as such not interpreted as anything but that is resolved after applying formatting to the column. Note that for me, in Excel 2002 SP3, the dates given above are automatically and correctly interpreted as dates when pasting.
if all things were said didn't work, go back to basics and test if this is working:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$('body').click(function() {
// do something here like:
alert('hey! The body click is working!!!')
});
</script>
</body>
</html>
then tell me if its working or not.
Your data.json
should look like this:
{
"maps":[
{"id":"blabla","iscategorical":"0"},
{"id":"blabla","iscategorical":"0"}
],
"masks":
{"id":"valore"},
"om_points":"value",
"parameters":
{"id":"valore"}
}
Your code should be:
import json
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
pprint(data)
Note that this only works in Python 2.6 and up, as it depends upon the with
-statement. In Python 2.5 use from __future__ import with_statement
, in Python <= 2.4, see Justin Peel's answer, which this answer is based upon.
You can now also access single values like this:
data["maps"][0]["id"] # will return 'blabla'
data["masks"]["id"] # will return 'valore'
data["om_points"] # will return 'value'
As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful
bool cmp(string a, string b)
{
if(a.compare(b) > 0)
return true;
else
return false;
}
int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);
for(int i = 0; i < length; i++)
cout << words[i] << " ";
cout << endl;
// output will be: this test is a
}
If you want to reverse the order of sorting just modify the sign in the cmp function.
Hope this is helpful :)
Cheers!!!
You can access the namespace's dictionary with vars():
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
This is the right way to execute a .jar
, and whatever one class in that .jar
should have main()
and the following are the parameters to it :
java -DLB="uk" -DType="CLIENT_IND" -jar com.fbi.rrm.rrm-batchy-1.5.jar
Have you tried adding the absolute directory of go to your 'path'?
export PATH=$PATH:/directory/to/go/
Proper Swift 3.0 for iOS 10+ solution: Using ImageRenderer
and closure syntax:
func imageWith(newSize: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: newSize)
let image = renderer.image { _ in
self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
}
return image.withRenderingMode(self.renderingMode)
}
And here's the Objective-C version:
@implementation UIImage (ResizeCategory)
- (UIImage *)imageWithSize:(CGSize)newSize
{
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize];
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext*_Nonnull myContext) {
[self drawInRect:(CGRect) {.origin = CGPointZero, .size = newSize}];
}];
return [image imageWithRenderingMode:self.renderingMode];
}
@end
Update: for connecting to another sql server and executing sql statements, you have to use sqlcmd Utility. This is typically done in a batch file. You can combine this with xmp_cmdshell if you want to execute it within management studio.
one way is to configure a linked server. then you can append the linked server and the database name to the table name. (select * from linkedserver.database.dbo.TableName)
USE master
GO
EXEC sp_addlinkedserver
'SEATTLESales',
N'SQL Server'
GO
You can do it easily with regex:
string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"
The app is trying to create a COM Object and even if that COM DLL exists, it may depend on another DLL which isn't installed. You can use DependencyWalker to find out if this is the case.
For Eclipse, setting -Dspring.profiles.active
variable in the VM arguments would do the trick.
Go to
Right Click Project --> Run as --> Run Configurations --> Arguments
And add your -Dspring.profiles.active=dev
in the VM arguments
We do not need to use recursive method, it may be slow. My solution is using a user-defined function rint instesd of instrinsic function int or floor.
rint(x)=(x-int(x)>0.9999)?int(x)+1:int(x)
This function will give rint(0.0003/0.0001)=3
, while int(0.0003/0.0001)=floor(0.0003/0.0001)=2
.
Why? Please look at Perl int function and padding zeros
You can use .shape
In: a = np.array([[1,2,3],[4,5,6]])
In: a.shape
Out: (2, 3)
In: a.shape[0] # x axis
Out: 2
In: a.shape[1] # y axis
Out: 3
For prototyping, using curl from the shell with the -m
parameter allow to pass milliseconds, and will work in both cases, either the connection didn't initiate, error 404, 500, bad url, or the whole data wasn't retrieved in full in the allowed time range, the timeout is always effective. Php won't ever hang out.
Simply don't pass unsanitized user data in the shell call.
system("curl -m 50 -X GET 'https://api.kraken.com/0/public/OHLC?pair=LTCUSDT&interval=60' -H 'accept: application/json' > data.json");
// This data had been refreshed in less than 50ms
var_dump(json_decode(file_get_contents("data.json"),true));
(This answer took a while to write, and codeWizard's answer is correct in aim and essence, but not entirely complete, so I'll post this anyway.)
There is no such thing as a "remote Git tag". There are only "tags". I point all this out not to be pedantic,1 but because there is a great deal of confusion about this with casual Git users, and the Git documentation is not very helpful2 to beginners. (It's not clear if the confusion comes because of poor documentation, or the poor documentation comes because this is inherently somewhat confusing, or what.)
There are "remote branches", more properly called "remote-tracking branches", but it's worth noting that these are actually local entities. There are no remote tags, though (unless you (re)invent them). There are only local tags, so you need to get the tag locally in order to use it.
The general form for names for specific commits—which Git calls references—is any string starting with refs/
. A string that starts with refs/heads/
names a branch; a string starting with refs/remotes/
names a remote-tracking branch; and a string starting with refs/tags/
names a tag. The name refs/stash
is the stash reference (as used by git stash
; note the lack of a trailing slash).
There are some unusual special-case names that do not begin with refs/
: HEAD
, ORIG_HEAD
, MERGE_HEAD
, and CHERRY_PICK_HEAD
in particular are all also names that may refer to specific commits (though HEAD
normally contains the name of a branch, i.e., contains ref: refs/heads/branch
). But in general, references start with refs/
.
One thing Git does to make this confusing is that it allows you to omit the refs/
, and often the word after refs/
. For instance, you can omit refs/heads/
or refs/tags/
when referring to a local branch or tag—and in fact you must omit refs/heads/
when checking out a local branch! You can do this whenever the result is unambiguous, or—as we just noted—when you must do it (for git checkout branch
).
It's true that references exist not only in your own repository, but also in remote repositories. However, Git gives you access to a remote repository's references only at very specific times: namely, during fetch
and push
operations. You can also use git ls-remote
or git remote show
to see them, but fetch
and push
are the more interesting points of contact.
During fetch
and push
, Git uses strings it calls refspecs to transfer references between the local and remote repository. Thus, it is at these times, and via refspecs, that two Git repositories can get into sync with each other. Once your names are in sync, you can use the same name that someone with the remote uses. There is some special magic here on fetch
, though, and it affects both branch names and tag names.
You should think of git fetch
as directing your Git to call up (or perhaps text-message) another Git—the "remote"—and have a conversation with it. Early in this conversation, the remote lists all of its references: everything in refs/heads/
and everything in refs/tags/
, along with any other references it has. Your Git scans through these and (based on the usual fetch refspec) renames their branches.
Let's take a look at the normal refspec for the remote named origin
:
$ git config --get-all remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*
$
This refspec instructs your Git to take every name matching refs/heads/*
—i.e., every branch on the remote—and change its name to refs/remotes/origin/*
, i.e., keep the matched part the same, changing the branch name (refs/heads/
) to a remote-tracking branch name (refs/remotes/
, specifically, refs/remotes/origin/
).
It is through this refspec that origin
's branches become your remote-tracking branches for remote origin
. Branch name becomes remote-tracking branch name, with the name of the remote, in this case origin
, included. The plus sign +
at the front of the refspec sets the "force" flag, i.e., your remote-tracking branch will be updated to match the remote's branch name, regardless of what it takes to make it match. (Without the +
, branch updates are limited to "fast forward" changes, and tag updates are simply ignored since Git version 1.8.2 or so—before then the same fast-forward rules applied.)
But what about tags? There's no refspec for them—at least, not by default. You can set one, in which case the form of the refspec is up to you; or you can run git fetch --tags
. Using --tags
has the effect of adding refs/tags/*:refs/tags/*
to the refspec, i.e., it brings over all tags (but does not update your tag if you already have a tag with that name, regardless of what the remote's tag says Edit, Jan 2017: as of Git 2.10, testing shows that --tags
forcibly updates your tags from the remote's tags, as if the refspec read +refs/tags/*:refs/tags/*
; this may be a difference in behavior from an earlier version of Git).
Note that there is no renaming here: if remote origin
has tag xyzzy
, and you don't, and you git fetch origin "refs/tags/*:refs/tags/*"
, you get refs/tags/xyzzy
added to your repository (pointing to the same commit as on the remote). If you use +refs/tags/*:refs/tags/*
then your tag xyzzy
, if you have one, is replaced by the one from origin
. That is, the +
force flag on a refspec means "replace my reference's value with the one my Git gets from their Git".
For historical reasons,3 if you use neither the --tags
option nor the --no-tags
option, git fetch
takes special action. Remember that we said above that the remote starts by displaying to your local Git all of its references, whether your local Git wants to see them or not.4 Your Git takes note of all the tags it sees at this point. Then, as it begins downloading any commit objects it needs to handle whatever it's fetching, if one of those commits has the same ID as any of those tags, git will add that tag—or those tags, if multiple tags have that ID—to your repository.
Edit, Jan 2017: testing shows that the behavior in Git 2.10 is now: If their Git provides a tag named T, and you do not have a tag named T, and the commit ID associated with T is an ancestor of one of their branches that your git fetch
is examining, your Git adds T to your tags with or without --tags
. Adding --tags
causes your Git to obtain all their tags, and also force update.
You may have to use git fetch --tags
to get their tags. If their tag names conflict with your existing tag names, you may (depending on Git version) even have to delete (or rename) some of your tags, and then run git fetch --tags
, to get their tags. Since tags—unlike remote branches—do not have automatic renaming, your tag names must match their tag names, which is why you can have issues with conflicts.
In most normal cases, though, a simple git fetch
will do the job, bringing over their commits and their matching tags, and since they—whoever they are—will tag commits at the time they publish those commits, you will keep up with their tags. If you don't make your own tags, nor mix their repository and other repositories (via multiple remotes), you won't have any tag name collisions either, so you won't have to fuss with deleting or renaming tags in order to obtain their tags.
I mentioned above that you can omit refs/
almost always, and refs/heads/
and refs/tags/
and so on most of the time. But when can't you?
The complete (or near-complete anyway) answer is in the gitrevisions
documentation. Git will resolve a name to a commit ID using the six-step sequence given in the link. Curiously, tags override branches: if there is a tag xyzzy
and a branch xyzzy
, and they point to different commits, then:
git rev-parse xyzzy
will give you the ID to which the tag points. However—and this is what's missing from gitrevisions
—git checkout
prefers branch names, so git checkout xyzzy
will put you on the branch, disregarding the tag.
In case of ambiguity, you can almost always spell out the ref name using its full name, refs/heads/xyzzy
or refs/tags/xyzzy
. (Note that this does work with git checkout
, but in a perhaps unexpected manner: git checkout refs/heads/xyzzy
causes a detached-HEAD checkout rather than a branch checkout. This is why you just have to note that git checkout
will use the short name as a branch name first: that's how you check out the branch xyzzy
even if the tag xyzzy
exists. If you want to check out the tag, you can use refs/tags/xyzzy
.)
Because (as gitrevisions
notes) Git will try refs/name
, you can also simply write tags/xyzzy
to identify the commit tagged xyzzy
. (If someone has managed to write a valid reference named xyzzy
into $GIT_DIR
, however, this will resolve as $GIT_DIR/xyzzy
. But normally only the various *HEAD
names should be in $GIT_DIR
.)
1Okay, okay, "not just to be pedantic". :-)
2Some would say "very not-helpful", and I would tend to agree, actually.
3Basically, git fetch
, and the whole concept of remotes and refspecs, was a bit of a late addition to Git, happening around the time of Git 1.5. Before then there were just some ad-hoc special cases, and tag-fetching was one of them, so it got grandfathered in via special code.
4If it helps, think of the remote Git as a flasher, in the slang meaning.
This works for me. in place of customTheme you can put you theme in styles. in this code you can also change the font and text size.
<style name="MyTheme.NavMenu" parent="CustomTheme">
<item name="android:textSize">16sp</item>
<item name="android:fontFamily">@font/ssp_semi_bold</item>
<item name="android:textColorPrimary">@color/yourcolor</item>
</style>
here is my navigation view
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:theme="@style/MyTheme.NavMenu"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer">
<include layout="@layout/layout_update_available"/>
</android.support.design.widget.NavigationView>
10 * * * Sun
Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday.
This code will print each individual number:
for myList in [[10,13,17],[3,5,1],[13,11,12]]:
for item in myList:
print(item)
Or for your specific use case:
((50 - List1[0][0]) + List1[0][1]) - List1[0][2]
My issue was by putting wrong parameters in the header, the requested parameters was
Authorization: Token <string>
and is was trying
Authorization Token: <string>
String is an immutable object in Java. You can use the StringBuilder class to do the job you're trying to accomplish, as follows:
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("hello, world!");
System.out.println(sb);
foo(sb);
System.out.println(sb);
}
public static void foo(StringBuilder str)
{
str.delete(0, str.length());
str.append("String has been modified");
}
Another option is to create a class with a String as a scope variable (highly discouraged) as follows:
class MyString
{
public String value;
}
public static void main(String[] args)
{
MyString ms = new MyString();
ms.value = "Hello, World!";
}
public static void foo(MyString str)
{
str.value = "String has been modified";
}
This is a very old question, but I think I have a solution that is slightly easier to type than previous solutions and doesn't rely on external libraries:
function sortArguments() {
return Array.apply(null, arguments).sort();
}
It's described on the Angular tutorial: https://angular.io/tutorial/toh-pt1#the-missing-formsmodule
You have to import FormsModule
and add it to imports in your @NgModule
declaraction.
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
DynamicConfigComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})