git config user.name
git config user.email
I believe these are the commands you are looking for.
Here is where I found them: http://alvinalexander.com/git/git-show-change-username-email-address
If you own the repository, you can find the exact size by opening your Account Settings ? Repositories (https://github.com/settings/repositories), and the repository size is displayed next to its designation.
If you do not own the repository, you can fork it and then check the in the same place.
Note: You might be the owner of the organization that hosts multiple repositories and yet not have a role in a specific repository inside the organization. By default, even if you create a repository in the organization you own, you are not added to the repo and hence not see that repo in settings/repositories
. So add yourself in the repository Setting(https://github.com/org-name/repo-name/settings
) to see it in https://github.com/settings/repositories
Somewhat hacky: use the download as a zip file
option, read the file size indicated and then cancel it.
I do not remember if downloading as a zip ever worked, but in any case, doing so now only downloads the currently selected branch with no history.
Use this:
$root = 'REST_SERVICE_URL'
$user = "user"
$pass= "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$result = Invoke-RestMethod $root -Credential $credential
If you want to force the factory function usage, name your struct (your class) with the first character in lowercase. Then, it won't be possible to instantiate directly the struct, the factory method will be required.
This visibility based on first character lower/upper case work also for struct field and for the function/method. If you don't want to allow external access, use lower case.
If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.
I have to create this extra file as link below was messing with my site styles too.
//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css
Instead to using it directly I created a css file bootstrap-glyphicons.css
@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}_x000D_
.glyphicon-asterisk:before{content:"\2a";}_x000D_
.glyphicon-plus:before{content:"\2b";}_x000D_
.glyphicon-euro:before{content:"\20ac";}_x000D_
.glyphicon-minus:before{content:"\2212";}_x000D_
.glyphicon-cloud:before{content:"\2601";}_x000D_
.glyphicon-envelope:before{content:"\2709";}_x000D_
.glyphicon-pencil:before{content:"\270f";}_x000D_
.glyphicon-glass:before{content:"\e001";}_x000D_
.glyphicon-music:before{content:"\e002";}_x000D_
.glyphicon-search:before{content:"\e003";}_x000D_
.glyphicon-heart:before{content:"\e005";}_x000D_
.glyphicon-star:before{content:"\e006";}_x000D_
.glyphicon-star-empty:before{content:"\e007";}_x000D_
.glyphicon-user:before{content:"\e008";}_x000D_
.glyphicon-film:before{content:"\e009";}_x000D_
.glyphicon-th-large:before{content:"\e010";}_x000D_
.glyphicon-th:before{content:"\e011";}_x000D_
.glyphicon-th-list:before{content:"\e012";}_x000D_
.glyphicon-ok:before{content:"\e013";}_x000D_
.glyphicon-remove:before{content:"\e014";}_x000D_
.glyphicon-zoom-in:before{content:"\e015";}_x000D_
.glyphicon-zoom-out:before{content:"\e016";}_x000D_
.glyphicon-off:before{content:"\e017";}_x000D_
.glyphicon-signal:before{content:"\e018";}_x000D_
.glyphicon-cog:before{content:"\e019";}_x000D_
.glyphicon-trash:before{content:"\e020";}_x000D_
.glyphicon-home:before{content:"\e021";}_x000D_
.glyphicon-file:before{content:"\e022";}_x000D_
.glyphicon-time:before{content:"\e023";}_x000D_
.glyphicon-road:before{content:"\e024";}_x000D_
.glyphicon-download-alt:before{content:"\e025";}_x000D_
.glyphicon-download:before{content:"\e026";}_x000D_
.glyphicon-upload:before{content:"\e027";}_x000D_
.glyphicon-inbox:before{content:"\e028";}_x000D_
.glyphicon-play-circle:before{content:"\e029";}_x000D_
.glyphicon-repeat:before{content:"\e030";}_x000D_
.glyphicon-refresh:before{content:"\e031";}_x000D_
.glyphicon-list-alt:before{content:"\e032";}_x000D_
.glyphicon-flag:before{content:"\e034";}_x000D_
.glyphicon-headphones:before{content:"\e035";}_x000D_
.glyphicon-volume-off:before{content:"\e036";}_x000D_
.glyphicon-volume-down:before{content:"\e037";}_x000D_
.glyphicon-volume-up:before{content:"\e038";}_x000D_
.glyphicon-qrcode:before{content:"\e039";}_x000D_
.glyphicon-barcode:before{content:"\e040";}_x000D_
.glyphicon-tag:before{content:"\e041";}_x000D_
.glyphicon-tags:before{content:"\e042";}_x000D_
.glyphicon-book:before{content:"\e043";}_x000D_
.glyphicon-print:before{content:"\e045";}_x000D_
.glyphicon-font:before{content:"\e047";}_x000D_
.glyphicon-bold:before{content:"\e048";}_x000D_
.glyphicon-italic:before{content:"\e049";}_x000D_
.glyphicon-text-height:before{content:"\e050";}_x000D_
.glyphicon-text-width:before{content:"\e051";}_x000D_
.glyphicon-align-left:before{content:"\e052";}_x000D_
.glyphicon-align-center:before{content:"\e053";}_x000D_
.glyphicon-align-right:before{content:"\e054";}_x000D_
.glyphicon-align-justify:before{content:"\e055";}_x000D_
.glyphicon-list:before{content:"\e056";}_x000D_
.glyphicon-indent-left:before{content:"\e057";}_x000D_
.glyphicon-indent-right:before{content:"\e058";}_x000D_
.glyphicon-facetime-video:before{content:"\e059";}_x000D_
.glyphicon-picture:before{content:"\e060";}_x000D_
.glyphicon-map-marker:before{content:"\e062";}_x000D_
.glyphicon-adjust:before{content:"\e063";}_x000D_
.glyphicon-tint:before{content:"\e064";}_x000D_
.glyphicon-edit:before{content:"\e065";}_x000D_
.glyphicon-share:before{content:"\e066";}_x000D_
.glyphicon-check:before{content:"\e067";}_x000D_
.glyphicon-move:before{content:"\e068";}_x000D_
.glyphicon-step-backward:before{content:"\e069";}_x000D_
.glyphicon-fast-backward:before{content:"\e070";}_x000D_
.glyphicon-backward:before{content:"\e071";}_x000D_
.glyphicon-play:before{content:"\e072";}_x000D_
.glyphicon-pause:before{content:"\e073";}_x000D_
.glyphicon-stop:before{content:"\e074";}_x000D_
.glyphicon-forward:before{content:"\e075";}_x000D_
.glyphicon-fast-forward:before{content:"\e076";}_x000D_
.glyphicon-step-forward:before{content:"\e077";}_x000D_
.glyphicon-eject:before{content:"\e078";}_x000D_
.glyphicon-chevron-left:before{content:"\e079";}_x000D_
.glyphicon-chevron-right:before{content:"\e080";}_x000D_
.glyphicon-plus-sign:before{content:"\e081";}_x000D_
.glyphicon-minus-sign:before{content:"\e082";}_x000D_
.glyphicon-remove-sign:before{content:"\e083";}_x000D_
.glyphicon-ok-sign:before{content:"\e084";}_x000D_
.glyphicon-question-sign:before{content:"\e085";}_x000D_
.glyphicon-info-sign:before{content:"\e086";}_x000D_
.glyphicon-screenshot:before{content:"\e087";}_x000D_
.glyphicon-remove-circle:before{content:"\e088";}_x000D_
.glyphicon-ok-circle:before{content:"\e089";}_x000D_
.glyphicon-ban-circle:before{content:"\e090";}_x000D_
.glyphicon-arrow-left:before{content:"\e091";}_x000D_
.glyphicon-arrow-right:before{content:"\e092";}_x000D_
.glyphicon-arrow-up:before{content:"\e093";}_x000D_
.glyphicon-arrow-down:before{content:"\e094";}_x000D_
.glyphicon-share-alt:before{content:"\e095";}_x000D_
.glyphicon-resize-full:before{content:"\e096";}_x000D_
.glyphicon-resize-small:before{content:"\e097";}_x000D_
.glyphicon-exclamation-sign:before{content:"\e101";}_x000D_
.glyphicon-gift:before{content:"\e102";}_x000D_
.glyphicon-leaf:before{content:"\e103";}_x000D_
.glyphicon-eye-open:before{content:"\e105";}_x000D_
.glyphicon-eye-close:before{content:"\e106";}_x000D_
.glyphicon-warning-sign:before{content:"\e107";}_x000D_
.glyphicon-plane:before{content:"\e108";}_x000D_
.glyphicon-random:before{content:"\e110";}_x000D_
.glyphicon-comment:before{content:"\e111";}_x000D_
.glyphicon-magnet:before{content:"\e112";}_x000D_
.glyphicon-chevron-up:before{content:"\e113";}_x000D_
.glyphicon-chevron-down:before{content:"\e114";}_x000D_
.glyphicon-retweet:before{content:"\e115";}_x000D_
.glyphicon-shopping-cart:before{content:"\e116";}_x000D_
.glyphicon-folder-close:before{content:"\e117";}_x000D_
.glyphicon-folder-open:before{content:"\e118";}_x000D_
.glyphicon-resize-vertical:before{content:"\e119";}_x000D_
.glyphicon-resize-horizontal:before{content:"\e120";}_x000D_
.glyphicon-hdd:before{content:"\e121";}_x000D_
.glyphicon-bullhorn:before{content:"\e122";}_x000D_
.glyphicon-certificate:before{content:"\e124";}_x000D_
.glyphicon-thumbs-up:before{content:"\e125";}_x000D_
.glyphicon-thumbs-down:before{content:"\e126";}_x000D_
.glyphicon-hand-right:before{content:"\e127";}_x000D_
.glyphicon-hand-left:before{content:"\e128";}_x000D_
.glyphicon-hand-up:before{content:"\e129";}_x000D_
.glyphicon-hand-down:before{content:"\e130";}_x000D_
.glyphicon-circle-arrow-right:before{content:"\e131";}_x000D_
.glyphicon-circle-arrow-left:before{content:"\e132";}_x000D_
.glyphicon-circle-arrow-up:before{content:"\e133";}_x000D_
.glyphicon-circle-arrow-down:before{content:"\e134";}_x000D_
.glyphicon-globe:before{content:"\e135";}_x000D_
.glyphicon-tasks:before{content:"\e137";}_x000D_
.glyphicon-filter:before{content:"\e138";}_x000D_
.glyphicon-fullscreen:before{content:"\e140";}_x000D_
.glyphicon-dashboard:before{content:"\e141";}_x000D_
.glyphicon-heart-empty:before{content:"\e143";}_x000D_
.glyphicon-link:before{content:"\e144";}_x000D_
.glyphicon-phone:before{content:"\e145";}_x000D_
.glyphicon-usd:before{content:"\e148";}_x000D_
.glyphicon-gbp:before{content:"\e149";}_x000D_
.glyphicon-sort:before{content:"\e150";}_x000D_
.glyphicon-sort-by-alphabet:before{content:"\e151";}_x000D_
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}_x000D_
.glyphicon-sort-by-order:before{content:"\e153";}_x000D_
.glyphicon-sort-by-order-alt:before{content:"\e154";}_x000D_
.glyphicon-sort-by-attributes:before{content:"\e155";}_x000D_
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}_x000D_
.glyphicon-unchecked:before{content:"\e157";}_x000D_
.glyphicon-expand:before{content:"\e158";}_x000D_
.glyphicon-collapse-down:before{content:"\e159";}_x000D_
.glyphicon-collapse-up:before{content:"\e160";}_x000D_
.glyphicon-log-in:before{content:"\e161";}_x000D_
.glyphicon-flash:before{content:"\e162";}_x000D_
.glyphicon-log-out:before{content:"\e163";}_x000D_
.glyphicon-new-window:before{content:"\e164";}_x000D_
.glyphicon-record:before{content:"\e165";}_x000D_
.glyphicon-save:before{content:"\e166";}_x000D_
.glyphicon-open:before{content:"\e167";}_x000D_
.glyphicon-saved:before{content:"\e168";}_x000D_
.glyphicon-import:before{content:"\e169";}_x000D_
.glyphicon-export:before{content:"\e170";}_x000D_
.glyphicon-send:before{content:"\e171";}_x000D_
.glyphicon-floppy-disk:before{content:"\e172";}_x000D_
.glyphicon-floppy-saved:before{content:"\e173";}_x000D_
.glyphicon-floppy-remove:before{content:"\e174";}_x000D_
.glyphicon-floppy-save:before{content:"\e175";}_x000D_
.glyphicon-floppy-open:before{content:"\e176";}_x000D_
.glyphicon-credit-card:before{content:"\e177";}_x000D_
.glyphicon-transfer:before{content:"\e178";}_x000D_
.glyphicon-cutlery:before{content:"\e179";}_x000D_
.glyphicon-header:before{content:"\e180";}_x000D_
.glyphicon-compressed:before{content:"\e181";}_x000D_
.glyphicon-earphone:before{content:"\e182";}_x000D_
.glyphicon-phone-alt:before{content:"\e183";}_x000D_
.glyphicon-tower:before{content:"\e184";}_x000D_
.glyphicon-stats:before{content:"\e185";}_x000D_
.glyphicon-sd-video:before{content:"\e186";}_x000D_
.glyphicon-hd-video:before{content:"\e187";}_x000D_
.glyphicon-subtitles:before{content:"\e188";}_x000D_
.glyphicon-sound-stereo:before{content:"\e189";}_x000D_
.glyphicon-sound-dolby:before{content:"\e190";}_x000D_
.glyphicon-sound-5-1:before{content:"\e191";}_x000D_
.glyphicon-sound-6-1:before{content:"\e192";}_x000D_
.glyphicon-sound-7-1:before{content:"\e193";}_x000D_
.glyphicon-copyright-mark:before{content:"\e194";}_x000D_
.glyphicon-registration-mark:before{content:"\e195";}_x000D_
.glyphicon-cloud-download:before{content:"\e197";}_x000D_
.glyphicon-cloud-upload:before{content:"\e198";}_x000D_
.glyphicon-tree-conifer:before{content:"\e199";}_x000D_
.glyphicon-tree-deciduous:before{content:"\e200";}_x000D_
.glyphicon-briefcase:before{content:"\1f4bc";}_x000D_
.glyphicon-calendar:before{content:"\1f4c5";}_x000D_
.glyphicon-pushpin:before{content:"\1f4cc";}_x000D_
.glyphicon-paperclip:before{content:"\1f4ce";}_x000D_
.glyphicon-camera:before{content:"\1f4f7";}_x000D_
.glyphicon-lock:before{content:"\1f512";}_x000D_
.glyphicon-bell:before{content:"\1f514";}_x000D_
.glyphicon-bookmark:before{content:"\1f516";}_x000D_
.glyphicon-fire:before{content:"\1f525";}_x000D_
.glyphicon-wrench:before{content:"\1f527";}
_x000D_
And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help
@import url("bootstrap-glyphicons.css");
Many people have already explained recursion here. I would like to cite a couple of thoughts about some advantages that recursion gives from the book “Concurrency in .NET, Modern patterns of concurrent and parallel programming” by Riccardo Terrell:
“Functional recursion is the natural way to iterate in FP because it avoids mutation of state. During each iteration, a new value is passed into the loop constructor instead to be updated (mutated). In addition, a recursive function can be composed, making your program more modular, as well as introducing opportunities to exploit parallelization."
Here also are some interesting notes from the same book about tail recursion:
Tail-call recursion is a technique that converts a regular recursive function into an optimized version that can handle large inputs without any risks and side effects.
NOTE The primary reason for a tail call as an optimization is to improve data locality, memory usage, and cache usage. By doing a tail call, the callee uses the same stack space as the caller. This reduces memory pressure. It marginally improves the cache because the same memory is reused for subsequent callers and can stay in the cache, rather than evicting an older cache line to make room for a new cache line.
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
In Pyspark you can simply specify each condition separately:
val Lead_all = Leads.join(Utm_Master,
(Leaddetails.LeadSource == Utm_Master.LeadSource) &
(Leaddetails.Utm_Source == Utm_Master.Utm_Source) &
(Leaddetails.Utm_Medium == Utm_Master.Utm_Medium) &
(Leaddetails.Utm_Campaign == Utm_Master.Utm_Campaign))
Just be sure to use operators and parenthesis correctly.
This will work for URL encoded strings too.
^(https?)(:\/\/|(\%3A%2F%2F))
Here is an example of how you do it with expect
tool:
sub copyover {
$scp = Expect->spawn("/usr/bin/scp ${srcpath}/$file $who:${destpath}/$file");
$scp->expect(30,"ssword: ") || die "Never got password prompt from $dest:$!\n";
print $scp 'password' . "\n";
$scp->expect(30,"-re",'$\s') || die "Never got prompt from parent system:$!\n";
$scp->soft_close();
return;
}
Having had an experience with both frameworks recently, I thought I can share my views on each frameworks.
I was asked to evaluate the logging frameworks for an existing web application, I narrowed down my choices to NLog (v2.0) and log4net (v1.2.11) after going through various online forums. Here are my findings:
Setting/starting up with NLog is dead easy. You go through the Getting started tutorial on their website and you are done. You get a fair idea, how thing might be with nlog. Config file is so intuitive that anyone can understand the config. For example: if you want to set the internal logging on, you set the flag in Nlog config file's header node, which is where you would expect it to be. In log4net, you set different flags in web.config's appSettings section.
In log4net, internal logging doesnt output timestamp which is annoying. In Nlog, you get a nice log with timestamps. I found it very useful in my evaluations.
Filters in log4net - You better check my this question - log4net filter - how to write AND filter to ignore log messages and if you find an answer/solution for this, please let me know. I understand, there is a workaround for this question, as you can write your own custom filter. But something which is not easily available in log4net.
Performance - I logged around 3000 log messages to database using a stored procedure. I used simple for loop (int i=0; i<3000; i++... to log the same message 3000 times. For the writes: log4net AdoAppender took almost double the time than NLog.
Log4net doesnt support asynchronous appender.
It was sufficient comparison for me to choose NLog as the logging framework. :)
It's not magic.
The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).
The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.
Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:
char array[100] = {};
As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization
Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.
const arrClass = document.querySelectorAll(".className");
for (let i of arrClass) {
i.addEventListener("click", (e) => {
if (e.target.classList.contains("className")) {
console.log("Perfrom Action")
}
})
}
I think you need str.contains
, if you need rows where values of column date
contains string 07311954
:
print df[df['date'].astype(str).str.contains('07311954')]
Or if type
of date
column is string
:
print df[df['date'].str.contains('07311954')]
If you want check last 4 digits for string
1954
in column date
:
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
Sample:
print df['date']
0 8152007
1 9262007
2 7311954
3 2252011
4 2012011
5 2012011
6 2222011
7 2282011
Name: date, dtype: int64
print df['date'].astype(str).str[-4:].str.contains('1954')
0 False
1 False
2 True
3 False
4 False
5 False
6 False
7 False
Name: date, dtype: bool
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
cmte_id trans_typ entity_typ state employer occupation date \
2 C00119040 24K CCM MD NaN NaN 7311954
amount fec_id cand_id
2 1000 C00140715 H2MD05155
I know the question states MVC 3, but it was 2012, so just in case:
As of MVC 5.1 you can now pass HTML attributes to EditorFor
like so:
@Html.EditorFor(x => x.Name, new { htmlAttributes = new { @readonly = "", disabled = "" } })
In UTC:
Instant.now().minus( 1 , ChronoUnit.HOURS )
Or, zoned:
Instant.now()
.atZone( ZoneId.of ( "America/Montreal" ) )
.minusHours( 1 )
Java 8 and later has the new java.time framework built-in.
Instant
If you only care about UTC (GMT), then use the Instant
class.
Instant instant = Instant.now ();
Instant instantHourEarlier = instant.minus ( 1 , ChronoUnit.HOURS );
Dump to console.
System.out.println ( "instant: " + instant + " | instantHourEarlier: " + instantHourEarlier );
instant: 2015-10-29T00:37:48.921Z | instantHourEarlier: 2015-10-28T23:37:48.921Z
Note how in this instant happened to skip back to yesterday’s date.
ZonedDateTime
If you care about a time zone, use the ZonedDateTime
class. You can start with an Instant and the assign a time zone, a ZoneId
object. This class handles the necessary adjustments for anomalies such as Daylight Saving Time (DST).
Instant instant = Instant.now ();
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
ZonedDateTime zdtHourEarlier = zdt.minus ( 1 , ChronoUnit.HOURS );
Dump to console.
System.out.println ( "instant: " + instant + "\nzdt: " + zdt + "\nzdtHourEarlier: " + zdtHourEarlier );
instant: 2015-10-29T00:50:30.778Z
zdt: 2015-10-28T20:50:30.778-04:00[America/Montreal]
zdtHourEarlier: 2015-10-28T19:50:30.778-04:00[America/Montreal]
The old java.util.Date/.Calendar classes are now outmoded. Avoid them. They are notoriously troublesome and confusing.
When you must use the old classes for operating with old code not yet updated for the java.time types, call the conversion methods. Here is example code going from an Instant or a ZonedDateTime to a java.util.Date.
java.util.Date date = java.util.Date.from( instant );
…or…
java.util.Date date = java.util.Date.from( zdt.toInstant() );
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
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.
Another notable (good) difference about PDO is that it's PDO::quote()
method automatically adds the enclosing quotes, whereas mysqli::real_escape_string()
(and similars) don't:
PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.
I prever to use this over the current accepted answer from Stephan as it makes it possible to configure the timestamp using named parameters after that:
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x
It will provide the following parameters:
You can then configure your format like so:
SET DATE=%Year%%Month%%Day%
If you're willing to use pandas
:
pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')
The headers are entirely encrypted. The only information going over the network 'in the clear' is related to the SSL setup and D/H key exchange. This exchange is carefully designed not to yield any useful information to eavesdroppers, and once it has taken place, all data is encrypted.
I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.
I used the following settings in the webpack:
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},
This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.
Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.
I updated my webpack with the following settings
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},
I then used the following command to import the images
import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">
<img style={{ width: 300, height: 150 }} src={img} />
</div>
The ceil and floor methods will help you determine if the number is a whole number.
However if you want to determine if the number can be represented by an int value.
if(value == (int) value)
or a long (64-bit integer)
if(value == (long) value)
or can be safely represented by a float without a loss of precision
if(value == (float) value)
BTW: don't use a 32-bit float unless you have to. In 99% of cases a 64-bit double is a better choice.
UPDATE
Consider avoiding createObjectURL()
method, while browsers are disabling support for it. Just attach MediaStream
object directly to the srcObject
property of HTMLMediaElement
e.g. <video>
element.
const mediaStream = new MediaStream();
const video = document.getElementById('video-player');
video.srcObject = mediaStream;
However, if you need to work with MediaSource
, Blob
or File
, you have to create a URL with URL.createObjectURL()
and assign it to HTMLMediaElement.src
.
Read more details here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
Older Answer
I experienced same error, when I passed to createObjectURL
raw data:
window.URL.createObjectURL(data)
It has to be Blob
, File
or MediaSource
object, not data itself. This worked for me:
var binaryData = [];
binaryData.push(data);
window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))
Check also the MDN for more info: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
You need the
fileItem.getOutputStream();
because it will throw NPE otherwise.
For a function type prop you can use the following code:
AddAddressComponent.defaultProps = {
callBackHandler: () => {}
};
AddAddressComponent.propTypes = {
callBackHandler: PropTypes.func,
};
Just use Apache Commons
First of all, read all the fine print. Note that NHibernate (thus, I assume, Hibernate as well) relational mapping has a funny correspondance with DB and object graph mapping. For example, one-to-one relationships are often implemented as a many-to-one relationship.
Second, before we can tell you how you should write your O/R map, we have to see your DB as well. In particular, can a single Skill be possesses by multiple people? If so, you have a many-to-many relationship; otherwise, it's many-to-one.
Third, I prefer not to implement many-to-many relationships directly, but instead model the "join table" in your domain model--i.e., treat it as an entity, like this:
class PersonSkill
{
Person person;
Skill skill;
}
Then do you see what you have? You have two one-to-many relationships. (In this case, Person may have a collection of PersonSkills, but would not have a collection of Skills.) However, some will prefer to use many-to-many relationship (between Person and Skill); this is controversial.
Fourth, if you do have bidirectional relationships (e.g., not only does Person have a collection of Skills, but also, Skill has a collection of Persons), NHibernate does not enforce bidirectionality in your BL for you; it only understands bidirectionality of the relationships for persistence purposes.
Fifth, many-to-one is much easier to use correctly in NHibernate (and I assume Hibernate) than one-to-many (collection mapping).
Good luck!
A While
/Wend
loop can only be exited prematurely with a GOTO
or by exiting from an outer block (Exit sub
/function
or another exitable loop)
Change to a Do
loop instead:
Do While True
count = count + 1
If count = 10 Then
Exit Do
End If
Loop
Or for looping a set number of times:
for count = 1 to 10
msgbox count
next
(Exit For
can be used above to exit prematurely)
here's one way you can do it with awk
curl -sL 'http://twitter.com/users/username.json' | awk -F"," -v k="text" '{
gsub(/{|}/,"")
for(i=1;i<=NF;i++){
if ( $i ~ k ){
print $i
}
}
}'
Try this, but I don't think it will work because you're not supposed to be able to change this
Put this line in an htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On
Note that this setting will only apply to PHP file's in the same directory as the htaccess file.
As an alternative to using url_fopen, try using curl.
You have to return a promise instead of a variable. So in your function just return:
return relationsManagerResource.GetParentId(nodeId)
And later resolve the returned promise.
Or you can make another deferred and resolve theParentId
with it.
Today, I mistakenly checked out on a commit and started working on it, making some commits on a detach HEAD state. Then I pushed to the remote branch using the following command:
git push origin HEAD: <My-remote-branch>
Then
git checkout <My-remote-branch>
Then
git pull
I finally got my all changes in my branch that I made in detach HEAD.
Change ownership and permissions folder
sudo chown -R username.www-data /var/www
sudo chmod -R +rwx /var/www
Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
Distinct the Note class by Author
var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());
foreach(var item in DistinctItems)
{
//Add to other List
}
Ok you use PHPMyAdmin but sometimes the best way is through terminal:
mysql -h localhost -u root -p
(switch root and localhost for user and database location)\. /path/to/your/file.sql
And that's it. Just remember if you are in a remote server, you must upload the .sql file to some folder.
File.foreach(filename).with_index do |line, line_num|
puts "#{line_num}: #{line}"
end
This will execute the given block for each line in the file without slurping the entire file into memory. See: IO::foreach.
I happened to encounter this similar SSL problem a few days ago. The problem is your npm does not set root certificate for the certificate used by https://registry.npmjs.org.
Solutions:
wget https://registry.npmjs.org/coffee-script --ca-certificate=./DigiCertHighAssuranceEVRootCA.crt
to fix wget problemnpm config set cafile /path/to/DigiCertHighAssuranceEVRootCA.crt
to set root certificate for your npm program.you can download root certificate from : https://www.digicert.com/CACerts/DigiCertHighAssuranceEVRootCA.crt
Notice: Different program may use different way of managing root certificate, so do not mix browser's with others.
let's fix your wget https://registry.npmjs.org/coffee-script
problem first. your snippet says:
ERROR: cannot verify registry.npmjs.org's certificate, issued by /C=US/ST=CA/L=Oakland/O=npm/OU=npm Certificate Authority/CN=npmCA/[email protected]: Unable to locally verify the issuer's authority.
This means that your wget program cannot verify https://registry.npmjs.org
's certificate. There are two reasons that may cause this problem:
So the solution is explicitly set root certificate for https://registry.npmjs.org
. We can use openssl to make sure that the reason bellow is the problem.
Try openssl s_client -host registry.npmjs.org -port 443
on the command line and we will get this message (first several lines):
CONNECTED(00000003) depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3 verify error:num=20:unable to get local issuer certificate verify return:0 --- Certificate chain 0 s:/C=US/ST=California/L=San Francisco/O=Fastly, Inc./CN=a.sni.fastly.net i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3 1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3 i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA ---
This line verify error:num=20:unable to get local issuer certificate
makes sure that https://registry.npmjs.org
does not pack root certificate. So we Google DigiCert High Assurance EV Root CA
root Certificate.
backItem.title = ""
to using topItem.title = ""
navigationItem.hidesBackButton = true
& navigationItem.leftBarButtonItem
will lose the back gestureMy solution will change the image & keep the back gesture:
navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back")
navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back")
navigationController?.navigationBar.topItem?.title = ""
Did you try format?
@font-face {
font-family: 'The name of the Font Family Here';
src: URL('font.ttf') format('truetype');
}
Read this article: http://css-tricks.com/snippets/css/using-font-face/
Also, might depend on browser as well.
Even though this is an old question, I had to do something similar today but I prefer JSTL:
<c:forEach var="par" items="${paramValues}">
<c:if test="${fn:startsWith(par.key, 'question')}">
${par.key} = ${par.value[0]}; //whatever
</c:if>
</c:forEach>
I also experienced an issue like this, my workspace was corrupted and didn't do all the important things anymore.
For some reason, I had a corrupt resource on one of my projects. It didn't show up in the package tree, but it did show in the error log in Eclipse as
Error while creating a link for external folder X:\somefolder
After checking every project (because the error didn't point to one), I indeed found this resource in one of the build paths (in Configure Build Path menu it did show an error icon!) and deleted it.
See Eclipse (Kepler) Workspace acting weird (type hierarchy, searching for references not working) for a wider description of my issue if you're experiencing something similar.
Posted this for future developers to reference.
Let's try this way:
select
a.ip,
a.os,
a.hostname,
a.port,
a.protocol,
b.state
from a
left join b
on a.ip = b.ip
and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/
So, in where
clause you can filter result set by column from right table only on this way:
...
where b.somecolumn <> (=) null
How are these mipmap images different from the other familiar drawable images?
Here is my two cents in trying to explain the difference. There are two cases you deal with when working with images in Android:
You want to load an image for your device density and you are going to use it "as is", without changing its actual size. In this case you should work with drawables and Android will give you the best fitting image.
You want to load an image for your device density, but this image is going to be scaled up or down. For instance this is needed when you want to show a bigger launcher icon, or you have an animation, which increases image's size. In such cases, to ensure best image quality, you should put your image into mipmap folder. What Android will do is, it will try to pick up the image from a higher density bucket instead of scaling it up. This will increase sharpness (quality) of the image.
Thus, the rule of thumb to decide where to put your image into would be:
Try changing the security mode from "Transport" to "None".
<!-- Transport security mode requires IIS to have a
certificate configured for SSL. See readme for
more information on how to set this up. -->
<security mode="None">
The Eclipse UI is a little bit confusing.
The Import -> "Existing projects into workspace" actually means import "Existing Eclipse projects into workspace". That's why you can't click on finish: the import option looks for a .project
file (the file used by Eclipse to store the project options) in the directory that you have chosen.
To import existing source code that doesn't have an Eclipse project file you have the following options (I suppose that you want to create a Java project):
New project inside the workspace dir: Create a new empty Java project into the workspace (File->New->Java Project). Then right click on the source folder and choose Import...->General->File system then choose your files, and it will make a copy of your files.
Tip: you can drag&drop your files from the Finder into the src folder.
Create an eclipse project in your existing dir: Create a new Java project, but in the "New Java Project" window:
You should check with SMTP.
That means you have to connect to that email's SMTP server.
After connecting to the SMTP server you should send these commands:
HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>
If you get "<[email protected]> Relay access denied" that means this email is Invalid.
There is a simple PHP class. You can use it:
http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html
This is an adaptation of the above answer, but should be more complete.
To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.
Windows Users
Go to C:\Program Files\Sublime Text 3\Packages
extract HTML.sublime-package
as if it is a zip file to a directory.
Open Miscellaneous.tmPreferences
and copy this contents into the file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Then re-zip the file as HTML.sublime-package
and replace the existing HTML.sublime-package
with the one you just created.
Close and open Sublime Text 3 and you're done!
Had this issue after installing Divio: it had changed my PATH or environment in some way, as it launches a terminal.
The solution in this case was just to do source ~/.bash_profile
which should already be setup to get you back to your original pyenv/pyenv-virtualenv state.
$.get
does not give you the opportunity to set an error handler. You will need to use the low-level $.ajax
function instead:
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
$(data).find('#reviews .card').appendTo('#reviews');
},
error: function(data) {
alert('woops!'); //or whatever
}
});
Edit March '10
Note that with the new jqXHR
object in jQuery 1.5, you can set an error handler after calling $.get
:
$.get('http://example.com/page/2/', function(data){
$(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
alert('woops'); // or whatever
});
The raw.githubusercontent.com
domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.
The URL in your question references the install
file in the master
branch of the Homebrew/install
repository. The rest of that command just retrieves the file and runs ruby
on its contents.
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function() {
//here you have the control over the body of the iframe document
var iBody = $("#iView").contents().find("body");
//here you have the control over any element (#myContent)
var myContent = iBody.find("#myContent");
});
</script>
</head>
<body>
<iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>
This is straightforward if you have control over the client that is sending the communications. All you need to do is set the HttpProxy on the client-side service class.
I did this, for example, to trace a web service client running on a smartphone. I set the proxy on that client-side connection to the IP/port of Fiddler, which was running on a PC on the network. The smartphone app then sent all of its outgoing communication to the web service, through Fiddler.
This worked perfectly.
If your client is a WCF client, then see this Q&A for how to set the proxy.
Even if you don't have the ability to modify the code of the client-side app, you may be able to set the proxy administratively, depending on the webservices stack your client uses.
I ran into this type error by updating the Xcode version to 8.0,
and under the Code signing is required for product type 'Application' in SDK 'iOS 10.0'
There is a warning:
isn't code signed but requires entitlements. It is not possible to add entitlements to a binary without signing it.
My solution is go to the TARGET ? General ? Signing -> click the Enable signing... button, and I solved the issue.
I wanted to use Realm for Android and that required Retrolambda. Problem is Retrolambda conflicts with Jack.
So I removed my Jack options config from my gradle shown in original answer below and made the following changes:
// ---------------------------------------------
// Project build.gradle file
// ---------------------------------------------
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'me.tatarka:gradle-retrolambda:3.6.1'
classpath "io.realm:realm-gradle-plugin:3.1.4"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
and
// ---------------------------------------------
// Module build.gradle file
// ---------------------------------------------
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'realm-android'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
...
If you made those changes above and you still get the following error:
Execution failed for task ':app:compileDebugJavaWithJavac'.
com.sun.tools.javac.util.Context.put(Ljava/lang/Class;Ljava/lang/Object;)V
Try removing the following file:
/Library/Java/Extensions/tools.jar
Then:
All the changes fixed it for me.
Note:
I am not sure what tools.jar does or whether it's important. Like other uses in this Stackoverflow question:
Can't build Java project on OSX yosemite
We were unfortunate enough to have to use AUSKey (some ancient dinosaur Java authentication key system used by Australian Government to authenticate our computer before we can log into Australian business portal website).
My speculation is tools.jar
might have been a JAR file for/by AUSKey.
If you're worried, instead of deleting this file, you can make a backup of the whole folder and save it somewhere just in case you can't login to Australian Business Portal again.
Hope that helps :D
I came across this problem today (27/06/2016).
I downloaded Android Studio 2.2 and updated JDK to 1.8.
In addition to the above answers of pointing to the correct JDK path, I had to additionally specify the JDK version in my build.gradle(Module: app)
file:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
The resulting file looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.mycompany.appname"
minSdkVersion 17
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
jackOptions {
enabled true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
}
Please also notice if you came across an error about Java 8 language features requires Jack enabled
, you need to add the following to your gradle file (as shown above):
jackOptions {
enabled true
}
After doing that, I finally got my new project app running on my phone.
This is definitely the cleanest answer to the question: https://stackoverflow.com/a/14025331/1008519.
In combination with table-layout: fixed
I often find <colgroup>
a great tool to make columns act as you want (see codepen here):
table {_x000D_
/* When set to 'fixed', all columns that do not have a width applied will get the remaining space divided between them equally */_x000D_
table-layout: fixed;_x000D_
}_x000D_
.fixed-width {_x000D_
width: 100px;_x000D_
}_x000D_
.col-12 {_x000D_
width: 100%;_x000D_
}_x000D_
.col-11 {_x000D_
width: 91.666666667%;_x000D_
}_x000D_
.col-10 {_x000D_
width: 83.333333333%;_x000D_
}_x000D_
.col-9 {_x000D_
width: 75%;_x000D_
}_x000D_
.col-8 {_x000D_
width: 66.666666667%;_x000D_
}_x000D_
.col-7 {_x000D_
width: 58.333333333%;_x000D_
}_x000D_
.col-6 {_x000D_
width: 50%;_x000D_
}_x000D_
.col-5 {_x000D_
width: 41.666666667%;_x000D_
}_x000D_
.col-4 {_x000D_
width: 33.333333333%;_x000D_
}_x000D_
.col-3 {_x000D_
width: 25%;_x000D_
}_x000D_
.col-2 {_x000D_
width: 16.666666667%;_x000D_
}_x000D_
.col-1 {_x000D_
width: 8.3333333333%;_x000D_
}_x000D_
_x000D_
/* Stylistic improvements from here */_x000D_
_x000D_
.align-left {_x000D_
text-align: left;_x000D_
}_x000D_
.align-right {_x000D_
text-align: right;_x000D_
}_x000D_
table {_x000D_
width: 100%;_x000D_
}_x000D_
table > tbody > tr > td,_x000D_
table > thead > tr > th {_x000D_
padding: 8px;_x000D_
border: 1px solid gray;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
<colgroup>_x000D_
<col /> <!-- take up rest of the space -->_x000D_
<col class="fixed-width" /> <!-- fixed width -->_x000D_
<col class="col-3" /> <!-- percentage width -->_x000D_
<col /> <!-- take up rest of the space -->_x000D_
</colgroup>_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="align-left">Title</th>_x000D_
<th class="align-right">Count</th>_x000D_
<th class="align-left">Name</th>_x000D_
<th class="align-left">Single</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
<td class="align-right">19</td>_x000D_
<td class="align-left">Lisa McArthur</td>_x000D_
<td class="align-left">No</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="align-left">This is a shorter title</td>_x000D_
<td class="align-right">2</td>_x000D_
<td class="align-left">John Oliver Nielson McAllister</td>_x000D_
<td class="align-left">Yes</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
<!-- define everything with percentage width -->_x000D_
<colgroup>_x000D_
<col class="col-6" />_x000D_
<col class="col-1" />_x000D_
<col class="col-4" />_x000D_
<col class="col-1" />_x000D_
</colgroup>_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="align-left">Title</th>_x000D_
<th class="align-right">Count</th>_x000D_
<th class="align-left">Name</th>_x000D_
<th class="align-left">Single</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
<td class="align-right">19</td>_x000D_
<td class="align-left">Lisa McArthur</td>_x000D_
<td class="align-left">No</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="align-left">This is a shorter title</td>_x000D_
<td class="align-right">2</td>_x000D_
<td class="align-left">John Oliver Nielson McAllister</td>_x000D_
<td class="align-left">Yes</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()
SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
Not yet mentioned here, another choice is environment aligned
, again from package amsmath
:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
\begin{aligned}
A & = B + C\\
& = D + E + F\\
& = G
\end{aligned}
\end{equation}
\end{document}
This outputs:
Not tested, but I think this will be close?
SELECT m1.id
FROM mytable m1
INNER JOIN mytable m2 ON m1.id < m2.id
GROUP BY m1.id
HAVING SUM(m1.cash) > 500
ORDER BY m1.id
LIMIT 1,2
The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one.
One liner:
System.IO.File.WriteAllText(@"D:\file.txt", content);
It creates the file if it doesn't exist and overwrites it if it exists. Make sure you have appropriate privileges to write to the location, otherwise you will get an exception.
https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Write string to text file and ensure it always overwrites the existing content.
Do you want your function to react to an array argument or variable arguments? If the latter, try:
var func = function(...rest) {
alert(rest.length);
// In JS, don't use for..in with arrays
// use for..of that consumes array's pre-defined iterator
// or a more functional approach
rest.forEach((v) => console.log(v));
};
But if you wish to handle an array argument
var fn = function(arr) {
alert(arr.length);
for(var i of arr) {
console.log(i);
}
};
Here I want my no to limit in 4 digit like if it is 1 it should show as 0001,if it 11 it should show as 0011..Below are the code.
reciptno=1;//Pass only integer.
string formatted = string.Format("{0:0000}", reciptno);
TxtRecNo.Text = formatted;//Output=0001..
I implemented this code to generate Money receipt no.
Here is generic equality checker function that receives array of elements as input and compare them to each other. Works with all types of elements.
const isEqual = function(inputs = []) {
// Checks an element if js object.
const isObject = function(data) {
return Object.prototype.toString.call(data) === '[object Object]';
};
// Sorts given object by its keys.
const sortObjectByKey = function(obj) {
const self = this;
if (!obj) return {};
return Object.keys(obj).sort().reduce((initialVal, item) => {
initialVal[item] = !Array.isArray(obj[item]) &&
typeof obj[item] === 'object'
? self.objectByKey(obj[item])
: obj[item];
return initialVal;
}, {});
};
// Checks equality of all elements in the input against each other. Returns true | false
return (
inputs
.map(
input =>
typeof input == 'undefined'
? ''
: isObject(input)
? JSON.stringify(sortObjectByKey(input))
: JSON.stringify(input)
)
.reduce(
(prevValue, input) =>
prevValue === '' || prevValue === input ? input : false,
''
) !== false
);
};
// Tests (Made with Jest test framework.)
test('String equality check', () => {
expect(isEqual(['murat'])).toEqual(true);
expect(isEqual(['murat', 'john', 'doe'])).toEqual(false);
expect(isEqual(['murat', 'murat', 'murat'])).toEqual(true);
});
test('Float equality check', () => {
expect(isEqual([7.89, 3.45])).toEqual(false);
expect(isEqual([7, 7.50])).toEqual(false);
expect(isEqual([7.50, 7.50])).toEqual(true);
expect(isEqual([7, 7])).toEqual(true);
expect(isEqual([0.34, 0.33])).toEqual(false);
expect(isEqual([0.33, 0.33])).toEqual(true);
});
test('Array equality check', () => {
expect(isEqual([[1, 2, 3], [1, 2, 3]])).toEqual(true);
expect(isEqual([[1, 3], [1, 2, 3]])).toEqual(false);
expect(isEqual([['murat', 18], ['murat', 18]])).toEqual(true);
});
test('Object equality check', () => {
let obj1 = {
name: 'murat',
age: 18
};
let obj2 = {
name: 'murat',
age: 18
};
let obj3 = {
age: 18,
name: 'murat'
};
let obj4 = {
name: 'murat',
age: 18,
occupation: 'nothing'
};
expect(isEqual([obj1, obj2])).toEqual(true);
expect(isEqual([obj1, obj2, obj3])).toEqual(true);
expect(isEqual([obj1, obj2, obj3, obj4])).toEqual(false);
});
test('Weird equality checks', () => {
expect(isEqual(['', {}])).toEqual(false);
expect(isEqual([0, '0'])).toEqual(false);
});
Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this
HttpServletRequest request;
request.setAttribute("param", "value")
now your parametrs will not be shown in your url header hope it works :)
You can do:
super.alphaMethod1();
Note, that super
is a reference to the parent, but super() is it's constructor.
I had the same problem and to solve this I follow this blog article: http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
special tks to @mkyong
If you try joining C on a field from B before joining B, i.e.:
SELECT A.x,
A.y,
A.z
FROM A
INNER JOIN C
on B.x = C.x
INNER JOIN B
on A.x = B.x
your query will fail, so in this case the order matters.
Change the return type of your GetResults to be List<Person>
.
Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically.
Using your definition for the Person class, this code works for me:
public List<Person> GetPlayers()
{
List<Person> players = new List<Person>();
players.Add(new Person { FirstName="Peyton", LastName="Manning", Age=35 } );
players.Add(new Person { FirstName="Drew", LastName="Brees", Age=31 } );
players.Add(new Person { FirstName="Brett", LastName="Favre", Age=58 } );
return players;
}
results:
[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},
{"Age":31,"FirstName":"Drew","LastName":"Brees"},
{"Age":58,"FirstName":"Brett","LastName":"Favre"}]
(All on one line)
I also used this attribute on the method:
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "players")]
WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.
The UriTemplate sets the URL at which the method is available. So I can do a GET on
http://myserver/myvdir/JsonService.svc/players
and it just works.
Also check out IIRF or another URL rewriter to get rid of the .svc in the URI.
The biggest PITA of Oracle is that is does not have a default date format!
In your installation of Oracle the combination of Locales and install options has picked (the very sensible!) YYYY-MM-DD as the format for outputting dates. Another installation could have picked "DD/MM/YYYY" or "YYYY/DD/MM".
If you want your SQL to be portable to another Oracle site I would recommend you always wrap a TO_CHAR(datecol,'YYYY-MM-DD')
or similar function around each date column your SQL or alternativly set the defualt format immediatly after you connect with
ALTER SESSION
SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
or similar.
(IN @brugernavn varchar(64)**)**,IN @password varchar(64))
The problem is the )
You might be using the enums incorrectly in the switch cases. In comparison with the above example by CoolBeans.. you might be doing the following:
switch(day) {
case Day.MONDAY:
// Something..
break;
case Day.FRIDAY:
// Something friday
break;
}
Make sure that you use the actual enum values instead of EnumType.EnumValue
Eclipse points out this mistake though..
<!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.io -->
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>
Add above dependency in pom.xml file
Post Value from
Intent ii = new Intent(this, GameStartPage.class);
// ii.putExtra("pkgName", B2MAppsPKGName);
ii.putExtra("pkgName", YourValue);
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(ii);
Get Value from
pkgn = getIntent().getExtras().getString("pkgName");
Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).
However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.
Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.
Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.
soooo late in the game i know, but thought i'd share this anyway. If you are solely working with the paths as strings, figuring this out is easy as pie:
private bool IsFolder(string ThePath)
{
string BS = Path.DirectorySeparatorChar.ToString();
return Path.GetDirectoryName(ThePath) == ThePath.TrimEnd(BS.ToCharArray());
}
for example:
ThePath == "C:\SomeFolder\File1.txt"
would end up being this:
return "C:\SomeFolder" == "C:\SomeFolder\File1.txt" (FALSE)
Another example:
ThePath == "C:\SomeFolder\"
would end up being this:
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
And this would also work without the trailing backslash:
ThePath == "C:\SomeFolder"
would end up being this:
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
Keep in mind here that this only works with the paths themselves, and not the relationship between the path and the "physical disk"... so it can't tell you if the path/file exists or anything like that, but it sure can tell you if the path is a folder or a file...
For me, using Anaconda Prompt instead of cmd or PowerShell is the key.
In Anaconda Prompt, all I need to do is activate XXX
Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty
. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty
. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.
Bear in mind that undefined
is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.
A more robust method is therefore the following:
if (typeof(x.attribute) !== 'undefined')
On the flip side, this method is much more verbose and also slower. :-/
A common alternative is to ensure that undefined
is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined
, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:
(function (undefined) {
… your code …
if (x.attribute !== undefined)
… mode code …
})();
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
Encoding and decoding can solve this in Python 3:
Client Side:
>>> host='127.0.0.1'
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.connect((host,port))
>>> st='connection done'
>>> byt=st.encode()
>>> s.send(byt)
15
>>>
Server Side:
>>> host=''
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.bind((host,port))
>>> s.listen(1)
>>> conn ,addr=s.accept()
>>> data=conn.recv(2000)
>>> data.decode()
'connection done'
>>>
press Alt to seee the Menubar and then go to view - appearance and remove the check from the fullscreen option
To install SOAP in PHP-7 run following in your Ubuntu terminal:
sudo apt-get install php7.0-soap
To install SOAP in PHP-7.1 run following in your Ubuntu terminal:
sudo apt-get install php7.1-soap
To install SOAP in PHP-7.2 run following in your Ubuntu terminal:
sudo apt-get install php7.2-soap
To install SOAP in PHP-7.3 run following in your Ubuntu terminal:
sudo apt-get install php7.3-soap
Populating a list is easier than an array. For arrays, you need to know the exact length of data, but for lists, data size can be any. And, you can convert a list into an array.
List<URLDTO> urls = new List<URLDTO>();
urls.Add(new URLDTO() {
key = "wiki",
url = "https://...",
});
urls.Add(new URLDTO()
{
key = "url",
url = "http://...",
});
urls.Add(new URLDTO()
{
key = "dir",
url = "https://...",
});
// convert a list into an array: URLDTO[]
return urls.ToArray();
I just posted an answer on a thread similiar to this here https://stackoverflow.com/a/43357241/3958617
The approach with:
<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>
and with
<a href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">whatsapp</a>
Only works if the person who clicked on your link have your number on their contact list.
Since not everybody will have it, the other solution is to use Whatsapp API like this:
<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>
More details on this API here: https://www.whatsapp.com/faq/en/general/26000030
And observations on how to use it here: https://stackoverflow.com/a/43357241/3958617
To Get The Data From the App.config
Keeping in mind you have to:
System.Configuration
using System.Configuration;
Just Simply do this
string value1 = ConfigurationManager.AppSettings["Value1"];
Alternatively, you can achieve this in one line, if you don't want to add using System.Configuration;
explicitly.
string value1 = System.Configuration.ConfigurationManager.AppSettings["Value1"]
You can Close your super view window
self.view.superview?.window?.close()
The If else statement needs to be wrapped in a .get or a .post to redirect. Such as
app.post('/login', function(req, res) {
});
or
app.get('/login', function(req, res) {
});
The importance of locales is that your environment/os can provide formatting functionality for all installed locales even if you don't know about them when you write your application. My Windows 7 system has 211 locales installed (listed below), so you wouldn't likely write any custom code or translation specific to this many locales.
The most important thing for various versions of English is in formatting numbers and dates. Other differences are significant to the extent that you want and able to cater to specific variations.
af-ZA
am-ET
ar-AE
ar-BH
ar-DZ
ar-EG
ar-IQ
ar-JO
ar-KW
ar-LB
ar-LY
ar-MA
arn-CL
ar-OM
ar-QA
ar-SA
ar-SY
ar-TN
ar-YE
as-IN
az-Cyrl-AZ
az-Latn-AZ
ba-RU
be-BY
bg-BG
bn-BD
bn-IN
bo-CN
br-FR
bs-Cyrl-BA
bs-Latn-BA
ca-ES
co-FR
cs-CZ
cy-GB
da-DK
de-AT
de-CH
de-DE
de-LI
de-LU
dsb-DE
dv-MV
el-GR
en-029
en-AU
en-BZ
en-CA
en-GB
en-IE
en-IN
en-JM
en-MY
en-NZ
en-PH
en-SG
en-TT
en-US
en-ZA
en-ZW
es-AR
es-BO
es-CL
es-CO
es-CR
es-DO
es-EC
es-ES
es-GT
es-HN
es-MX
es-NI
es-PA
es-PE
es-PR
es-PY
es-SV
es-US
es-UY
es-VE
et-EE
eu-ES
fa-IR
fi-FI
fil-PH
fo-FO
fr-BE
fr-CA
fr-CH
fr-FR
fr-LU
fr-MC
fy-NL
ga-IE
gd-GB
gl-ES
gsw-FR
gu-IN
ha-Latn-NG
he-IL
hi-IN
hr-BA
hr-HR
hsb-DE
hu-HU
hy-AM
id-ID
ig-NG
ii-CN
is-IS
it-CH
it-IT
iu-Cans-CA
iu-Latn-CA
ja-JP
ka-GE
kk-KZ
kl-GL
km-KH
kn-IN
kok-IN
ko-KR
ky-KG
lb-LU
lo-LA
lt-LT
lv-LV
mi-NZ
mk-MK
ml-IN
mn-MN
mn-Mong-CN
moh-CA
mr-IN
ms-BN
ms-MY
mt-MT
nb-NO
ne-NP
nl-BE
nl-NL
nn-NO
nso-ZA
oc-FR
or-IN
pa-IN
pl-PL
prs-AF
ps-AF
pt-BR
pt-PT
qut-GT
quz-BO
quz-EC
quz-PE
rm-CH
ro-RO
ru-RU
rw-RW
sah-RU
sa-IN
se-FI
se-NO
se-SE
si-LK
sk-SK
sl-SI
sma-NO
sma-SE
smj-NO
smj-SE
smn-FI
sms-FI
sq-AL
sr-Cyrl-BA
sr-Cyrl-CS
sr-Cyrl-ME
sr-Cyrl-RS
sr-Latn-BA
sr-Latn-CS
sr-Latn-ME
sr-Latn-RS
sv-FI
sv-SE
sw-KE
syr-SY
ta-IN
te-IN
tg-Cyrl-TJ
th-TH
tk-TM
tn-ZA
tr-TR
tt-RU
tzm-Latn-DZ
ug-CN
uk-UA
ur-PK
uz-Cyrl-UZ
uz-Latn-UZ
vi-VN
wo-SN
xh-ZA
yo-NG
zh-CN
zh-HK
zh-MO
zh-SG
zh-TW
zu-ZA
I had a similar situation where a download needed to stay active overnight and required a key press that refreshed my connection. I also found that the mouse move does not work. However, using notepad and a send key function appears to have done the trick. I send a space instead of a "." because if there is a [yes/no] popup, it will automatically click the default response using the spacebar. Here is the code used.
param($minutes = 120)
$myShell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 30
$myShell.sendkeys(" ")
}
This function will work for the designated 120 minutes (2 Hours), but can be modified for the timing desired by increasing or decreasing the seconds of the input, or increasing or decreasing the assigned value of the minutes parameter.
Just run the script in powershell ISE, or powershell, and open notepad. A space will be input at the specified interval for the desired length of time ($minutes).
Good Luck!
Lower the Deployment Target version. For example you have set the target as iOS 13.4 but your Xcode version is lower and there is no iOS 13.4 installed simulator.
Although I don't know about asp.net mvc, but this is what we should do in a normal .net website. It should work for asp.net mvc also.
YourSessionClass obj=Session["key"] as YourSessionClass;
if(obj==null){
obj=new YourSessionClass();
Session["key"]=obj;
}
You would put this inside a method for easy access. HTH
You didn't specify a GradientType
:
background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */
Copy-paste the following into your current terminal:
gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"
This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.
You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:
sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
open new terminal and validate environment is clean from old RVM settings (should be no output):
env | grep rvm
if there was output, try to open new terminal, if it does not help then restart your computer.
\curl -L https://get.rvm.io |
bash -s stable --ruby --autolibs=enable --auto-dotfiles
If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.
Sometimes file names are numbered, where the index may be at the beginning or the end. So I wanted to shorten from the center of the string:
function stringTruncateFromCenter(str, maxLength) {
const midChar = "…"; // character to insert into the center of the result
var left, right;
if (str.length <= maxLength) return str;
// length of beginning part
left = Math.ceil(maxLength / 2);
// start index of ending part
right = str.length - Math.floor(maxLength / 2) + 1;
return str.substr(0, left) + midChar + str.substring(right);
}
Be aware that I used a fill character here with more than 1 byte in UTF-8.
I had this issue under Windows 10 when using Visual Studio 2015 Professional, while Visual Studio 2015 Express worked! Under Windows 7, both Visual Studio versions used to work.
New projects created from the Visual Studio 2015 Professional IDE successfully compile, but CMake would fail to find the compiler reporting:
The C compiler identification is unknown
The CXX compiler identification is unknown
I upgraded CMake from 3.4.1 to 3.11.4, and now the problem is gone.
Here is an alternative way to do that.
const conditionsArray = [
condition1,
condition2,
condition3,
]
if (conditionsArray.indexOf(false) === -1) {
"do somthing"
}
Or ES6
if (!conditionsArray.includes(false)) {
"do somthing"
}
To get individual colour values you can use Color like following for pixel(x,y).
import java.awt.Color;
import java.awt.image.BufferedImage;
Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
The above will give you the integer values of Red, Green and Blue in range of 0 to 255.
To set the values from RGB you can do so by:
Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();
//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);
Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.
The update statement in all versions of SQL looks like:
update table
set col1 = expr1,
col2 = expr2,
. . .
coln = exprn
where some condition
So, the answer is that you separate the assignments using commas and don't repeat the set
statement.
Probably something like this if it's the text part you want...
from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)
The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.
<name>
blabla
<somestuff>asdf</somestuff>
znylpx
</name>
You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.
This is documented on ?logical
. The pertinent section of which is:
Details:
‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
in the R language, whereas ‘T’ and ‘F’ are global variables whose
initial values set to these. All four are ‘logical(1)’ vectors.
Logical vectors are coerced to integer vectors in contexts where a
numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details:
....
‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
true if and only if ‘x’ is a length-one logical vector whose only
element is ‘TRUE’ and which has no attributes (not even names).
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
From HandlerIntercepter
's javadoc:
HandlerInterceptor
is basically similar to a ServletFilter
, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured inweb.xml
, aHandlerInterceptor
in the application context.As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for
HandlerInterceptor
implementations, especially factored-out common handler code and authorization checks. On the other hand, aFilter
is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
With that being said:
So where is the difference between
Interceptor#postHandle()
andFilter#doFilter()
?
postHandle
will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse
since it's already committed.
doFilter
is much more versatile than the postHandle
. You can change the request or response and pass it to the chain or even block the request processing.
Also, in preHandle
and postHandle
methods, you have access to the HandlerMethod
that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.
What is the best practise in which use cases it should be used?
As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor
implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter
is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
Yes, you just need to add a parenthesis :
SELECT col1 as a, (CASE WHEN a = 'test' THEN 'yes' END) as value FROM table;
in additional to your way
you could call system ps command and get memory usage from it output.
or read info from /proc/pid ( see PIOCPSINFO struct )
I have implemented the method from Varun Vohra's answer here for both lists and dicts.
import math
import numbers
import operator
import itertools
def round_list_percentages(number_list):
"""
Takes a list where all values are numbers that add up to 100,
and rounds them off to integers while still retaining a sum of 100.
A total value sum that rounds to 100.00 with two decimals is acceptable.
This ensures that all input where the values are calculated with [fraction]/[total]
and the sum of all fractions equal the total, should pass.
"""
# Check input
if not all(isinstance(i, numbers.Number) for i in number_list):
raise ValueError('All values of the list must be a number')
# Generate a key for each value
key_generator = itertools.count()
value_dict = {next(key_generator): value for value in number_list}
return round_dictionary_percentages(value_dict).values()
def round_dictionary_percentages(dictionary):
"""
Takes a dictionary where all values are numbers that add up to 100,
and rounds them off to integers while still retaining a sum of 100.
A total value sum that rounds to 100.00 with two decimals is acceptable.
This ensures that all input where the values are calculated with [fraction]/[total]
and the sum of all fractions equal the total, should pass.
"""
# Check input
# Only allow numbers
if not all(isinstance(i, numbers.Number) for i in dictionary.values()):
raise ValueError('All values of the dictionary must be a number')
# Make sure the sum is close enough to 100
# Round value_sum to 2 decimals to avoid floating point representation errors
value_sum = round(sum(dictionary.values()), 2)
if not value_sum == 100:
raise ValueError('The sum of the values must be 100')
# Initial floored results
# Does not add up to 100, so we need to add something
result = {key: int(math.floor(value)) for key, value in dictionary.items()}
# Remainders for each key
result_remainders = {key: value % 1 for key, value in dictionary.items()}
# Keys sorted by remainder (biggest first)
sorted_keys = [key for key, value in sorted(result_remainders.items(), key=operator.itemgetter(1), reverse=True)]
# Otherwise add missing values up to 100
# One cycle is enough, since flooring removes a max value of < 1 per item,
# i.e. this loop should always break before going through the whole list
for key in sorted_keys:
if sum(result.values()) == 100:
break
result[key] += 1
# Return
return result
I can carry out some cleanups before exiting. What is the best way of doing this Thats is the real goal: trap exit, to make your own stuff. And neigther answers above not makeing it right. Because, Ctrl+C is just one of many ways to exiting app.
What in dotnet c# is needed for it - so called cancellation token passed to Host.RunAsync(ct)
and then, in exit signals traps, for Windows it would be
private static readonly CancellationTokenSource cts = new CancellationTokenSource();
public static int Main(string[] args)
{
// For gracefull shutdown, trap unload event
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
cts.Cancel();
exitEvent.Wait();
};
Console.CancelKeyPress += (sender, e) =>
{
cts.Cancel();
exitEvent.Wait();
};
host.RunAsync(cts);
Console.WriteLine("Shutting down");
exitEvent.Set();
return 0;
}
...
StringUtils.isBlank(CharSequence)
Ah, that would be because RegExp is not jQuery. :)
Try this page. jQuery.attr
doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text()
to return the String representation.
Something like:
$("li").val("title").search(/sometext/i));
For commenting line use REM or :: though ::
might fail inside brackets
within delayed expansion lines starting with !<delimiter>
will be ignored so this can be used for comments:
@echo off
setlocal enableDelayedExpansion
echo delayed expansion activated
!;delayed expansion commented line
echo end of the demonstration
For comments at the end of line you can again use rem
and ::
combined with &
:
echo --- &:: comment (should not be the last line in the script)
echo --- &rem comment
As noting will be parsed after the exit
command you can use it to put comments at the end of the file:
@echo off
echo commands
exit /b
-------------------
commnts at the end
of the file
------------------
Expansion of not existing variables is replaced with nothing ,and as setting a variable with =
rather hard you can use this for inline comments:
@echo off
echo long command %= this is a comment =% with an inline comment
For multiline comments GOTO
(for outside brackets) and REM
with conditional execution (for inside brackets) can be used. More details here:
@echo off
echo starting script
goto :end_comments
comented line
one more commented line
:end_comments
echo continue with the script
(
echo demonstration off
rem/||(
lines with
comments
)
echo multiline comment inside
echo brackets
)
And the same technique beautified with macros:
@echo off
::GOTO comment macro
set "[:=goto :]%%"
::brackets comment macros
set "[=rem/||(" & set "]=)"
::testing
echo not commented 1
%[:%
multi
line
comment outside of brackets
%:]%
echo not commented 2
%[:%
second multi
line
comment outside of brackets
%:]%
::GOTO macro cannot be used inside for
for %%a in (first second) do (
echo first not commented line of the %%a execution
%[%
multi line
comment
%]%
echo second not commented line of the %%a execution
)
There's a better way of storing JSON in the HTML:
HTML
<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>
JavaScript
JSON.parse(document.getElementById('some-data').textContent);
I would encourage you to see this youtube video which demonstrates the difference between C# bin and obj folders and also explains how we get the benefit of incremental/conditional compilation.
C# compilation is a two-step process, see the below diagram for more details:
If you compare both bin and obj directory you will find greater number of files in the "obj" directory as it has individual compiled code files while "bin" has a single unit.
In a similar situation I got away with this:
someUtils.validateURL = function(url) {
var parser = document.createElement('a');
try {
parser.href = url;
return !!parser.hostname;
} catch (e) {
return false;
}
};
i.e. why invent the wheel if browsers can do it for you? But, of course, this will only work in the browser.
there are various parts of parsed URL exactly how browser would interpret it:
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "8080"
parser.pathname; // => "/path/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
Using these you can improve your validating function depending on the requirements. The only drawback is that it will accept relative URLs and use current page server's host and port. But you can use it for your advantage, by re-assembling the URL from parts and always passing it in full to your AJAX service.
What validateURL
won't accept is invalid URL, e.g. http:\:8883
will return false, but :1234
is valid and is interpreted as http://pagehost.example.com/:1234
i.e. as a relative path.
UPDATE
This approach is no longer working with Chrome and other WebKit browsers. Even when URL is invalid, hostname is filled with some value, e.g. taken from base
. It still helps to parse parts of URL, but will not allow to validate one.
Possible better no-own-parser approach is to use var parsedURL = new URL(url)
and catch exceptions. See e.g. URL API. Supported by all major browsers and NodeJS, although still marked experimental.
>>> x='$120'
>>> import string
>>> a=string.maketrans('','')
>>> ch=a.translate(a, string.digits)
>>> int(x.translate(a, ch))
120
Try to install your application by using yum
command
yum install application_name
var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;
function changeIframe() {
$('#frame')[0].src = sites[index++];
index = index >= sites.length ? 0 : index;
}
This method worked in my case.
video=getElementsByTagName('video');
function removeControls(video){
video.removeAttribute('controls');
}
window.onload=removeControls(video);
Adding to the answer of Fatal Error, There is one more way to pass the variables to another shell script.
The above suggested solution have some drawbacks:
using Export
: It will cause the variable to be present out of their scope which is not a good design practice.using Source
: It may cause name collisions or accidental overwriting of a predefined variable in some other shell script file which have sourced another file.There is another simple solution avaiable for us to use. Considering the example posted by you,
test.sh
#!/bin/bash
TESTVARIABLE=hellohelloheloo
./test2.sh "$TESTVARIABLE"
test2.sh
#!/bin/bash
echo $1
output
hellohelloheloo
Also it is important to note that ""
are necessary if we pass multiword strings.
Taking one more example
master.sh
#!/bin/bash
echo in master.sh
var1="hello world"
sh slave1.sh $var1
sh slave2.sh "$var1"
echo back to master
slave1.sh
#!/bin/bash
echo in slave1.sh
echo value :$1
slave2.sh
#!/bin/bash
echo in slave2.sh
echo value : $1
output
in master.sh
in slave1.sh
value :"hello
in slave2.sh
value :"hello world"
It happens because of the reasons aptly described in this link
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
Brody's solution worked perfect for me. I have had to add side views on a textfield and add additional padding. So by implementing the custom UIEdgeInsets property to a UITextField subclass I have managed to achieve the task. I'm going to use this new subclass in all of my projects.
From WWDC 2015 there is a session on Implementing UI Designs in Interface Builder. Around the 32min mark he says that you always want to make your @IBOutlet
strong.
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
With PostgreSQL there are a number of date/time functions available, see here.
In your example, you could use:
SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
If you are running this query regularly, it is possible to create an index using the date_trunc
function as well:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
One advantage of this is there is some more flexibility with timezones if required, for example:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
You ask for quickest, but perhaps you mean "best" or "correct" or "typical"?
You also ask for commas to indicate thousands, but perhaps you mean "in normal human readable form according to the local custom of your user"?
You do it as so:
int i = 35634646;
String s = NumberFormat.getIntegerInstance().format(i);
Americans will get "35,634,646"
Germans will get "35.634.646"
Swiss Germans will get "35'634'646"
Use the --single-branch
switch (available as of Git 1.7.10). The syntax is:
git clone -b <tag_name> --single-branch <repo_url> [<dest_dir>]
For example:
git clone -b 'v1.9.5' --single-branch https://github.com/git/git.git git-1.9.5
The benefit: Git will receive objects and (need to) resolve deltas for the specified branch/tag only - while checking out the exact same amount of files! Depending on the source repository, this will save you a lot of disk space. (Plus, it'll be much quicker.)
By default, Log4j
logs to standard output and that means you should be able to see log messages on your Eclipse's console view. To log to a file you need to use a FileAppender
explicitly by defining it in a log4j.properties
file in your classpath.
Create the following log4j.properties
file in your classpath. This allows you to log your message to both a file as well as your console.
log4j.rootLogger=debug, stdout, file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=example.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%p %t %c - %m%n
Note: The above creates an example.log in your current working directory (i.e. Eclipse's project directory) so that the same log4j.properties could work with different projects without overwriting each other's logs.
References:
Apache log4j 1.2 - Short introduction to log4j
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
In C, static
means the function or variable you define can be only used in this file(i.e. the compile unit)
So, static inline
means the inline function which can be used in this file only.
EDIT:
The compile unit should be The Translation Unit
Since, nothing really work for me. I create a little windows BATCH script based on other answers combined together. Hope it help somebody. Simply usage: backupDatabase < PackageName > < ApplicationName > [TargetDirectory]. It use Sergei's backup method and Android Backup Extractor.
@echo off
if [%1]==[] goto usage
if [%2]==[] goto usage
if NOT [%4]==[] goto usage
@echo Processing: preparations
set PACKAGE=%1
set APPLICATION_NAME=%2
set TARGET_DIR=%cd%
IF NOT "%~3"=="" set TARGET_DIR=%3
set PATH_ADB="c:\Program Files (x86)\Android\android-studio\sdk\platform-tools"
set PATH_ABE="c:\Programs\android-backup-extractor-20140630-bin"
set PATH_7Z="c:\Program Files\7-Zip"
@echo Processing: backup
%PATH_ADB%\adb.exe backup -f %TARGET_DIR%\%APPLICATION_NAME%\%APPLICATION_NAME%.ab -noapk %PACKAGE%
@echo Processing: unpack
java -jar %PATH_ABE%\abe.jar unpack %TARGET_DIR%\%APPLICATION_NAME%\%APPLICATION_NAME%.ab %TARGET_DIR%\%APPLICATION_NAME%\%APPLICATION_NAME%.ab.tar
@echo Processing: extract
cd %TARGET_DIR%\%APPLICATION_NAME%
%PATH_7Z%\7z.exe e %APPLICATION_NAME%.ab.tar "apps\%PACKAGE%\db\%APPLICATION_NAME%"
@echo Processing: cleaning
del %APPLICATION_NAME%.ab
del %APPLICATION_NAME%.ab.tar
goto :eof
:usage
@echo.Pull out SQLite database file from your android device.
@echo.Needs: - connected device
@echo. - device enable backup.
@echo. - application enable backup
@echo. - application in debug mode
@echo. - installed Android Backup Extractor
@echo. - installed command line TAR extractor (7z, ...)
@echo.Does NOT need: root device
@echo.
@echo.Uses: - ADB backup (set PATH_ADB)
@echo. - Android Backup Extractor (http://sourceforge.net/projects/adbextractor/) (set PATH_ABE)
@echo. - Extract TAR container, uses 7z (set PATH_7Z)
@echo.
@echo.Usage: backupDatabase ^<PackageName^> ^<ApplicationName^> [TargetDirectory]
@echo.Example: backupDatabase com.foo.example ExampleApp
@echo Example: backupDatabase com.foo.example ExampleApp workspace\AndroidProjects\Example
exit /B 1
Use whatever navigation key you want to get inside the parentheses, then you can use either yi(
or yi)
to copy everything within the matching parens. This also works with square brackets (e.g. yi]
) and curly braces. In addition to y
, you can also delete or change text (e.g. ci)
, di]
).
I tried this with double and single-quotes and it appears to work there as well. For your data, I do:
write (*, '(a)') 'Computed solution coefficients:'
Move cursor to the C
, then type yi'
. Move the cursor to a blank line, hit p
, and get
Computed solution coefficients:
As CMS noted, this works for visual mode selection as well - just use vi)
, vi}
, vi'
, etc.
I think use this is better:
os.path.realpath(__file__).rsplit('/', X)[0]
In [1]: __file__ = "/aParent/templates/blog1/page.html"
In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'
In [4]: __file__ = "/aParent/templates/blog1/page.html"
In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'
In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'
In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'
I'm going to add to the answer given before.
It's not a bug in your code or the browser's code. It's the JavaScript code inside the YouTube iframe polls for the extensions it could interoperate with in case they were installed (likely to determine if the extension is installed).
Look at the source of www-embed-player.js
(loaded from s.ytimg.com
, it's YouTube static files CDN).
You'll find the following:
function Wj(a){return"chrome-extension://"+a+"/cast_sender.js"}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
}
}
);
Can this not be done simply by adding a additional "container" div and adding the removed alert div back into it each time. Seems to work for me?
HTML
<div id="alert_container"></div>
JS
$("#alert_container").html('<div id="alert"></div>');
$("#alert").addClass("alert alert-info alert-dismissible");
$("#alert").html('<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a><strong>Info!</strong>message');
To create an environment named py37
with python 3.7, using the channel conda-forge and a list of packages:
conda create -y --name py37 python=3.7
conda install --force-reinstall -y -q --name py37 -c conda-forge --file requirements.txt
conda activate py37
...
conda deactivate
Flags explained:
-y
: Do not ask for confirmation.--force-reinstall
: Install the package even if it already exists.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderThe ansible-role dockpack.base_miniconda can manage conda environments and can be used to create a docker base image.
Alternatively you can create an environment.yml file instead of requirements.txt:
name: py37
channels:
- conda-forge
dependencies:
- python=3.7
- numpy=1.9.*
- pandas
Use this command to list the environments you have:
conda info --envs
Use this command to remove the environment:
conda env remove -n py37
Try this. You can just use built-in ThresholdFilter
and LevelFilter
. No need to create your own filters programmically. In this example WARN and ERROR levels are logged to System.err and rest to System.out:
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny ERROR level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
</filter>
<!-- deny WARN level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>DENY</onMatch>
</filter>
<target>System.out</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<appender name="stderr" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny all events with a level below WARN, that is INFO, DEBUG and TRACE -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<target>System.err</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="stderr"/>
</root>
<root level="TRACE">
<appender-ref ref="stdout"/>
</root>
A 32-bit process is still limited to the same constraints in a 64-bit OS. The issue is that memory pointers are only 32-bits wide, so the program can't assign/resolve any memory address larger than 32 bits.
In my case I had to do this, because none of the suggested solutions were available:
List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();
From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm
:
--force
Same as using --replacepkgs, --replacefiles, and --oldpackage.
--oldpackage
Allow an upgrade to replace a newer package with an older one.
So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force
to solve your issue.
You can do these in unix shell:
java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
You can do these in windows powershell:
java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main
Use onChange={this.handleChange.bind(this, "name")
method and value={this.state.fields["name"]}
on input text field and below that create span element to show error, see the below example.
export default class Form extends Component {
constructor(){
super()
this.state ={
fields: {
name:'',
email: '',
message: ''
},
errors: {},
disabled : false
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
if(!fields["name"]){
formIsValid = false;
errors["name"] = "Name field cannot be empty";
}
if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
if(!fields["name"].match(/^[a-zA-Z]+$/)){
formIsValid = false;
errors["name"] = "Only letters";
}
}
if(!fields["email"]){
formIsValid = false;
errors["email"] = "Email field cannot be empty";
}
if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
if(!fields["message"]){
formIsValid = false;
errors["message"] = " Message field cannot be empty";
}
this.setState({errors: errors});
return formIsValid;
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
handleSubmit(e){
e.preventDefault();
if(this.handleValidation()){
console.log('validation successful')
}else{
console.log('validation failed')
}
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)} method="POST">
<div className="row">
<div className="col-25">
<label htmlFor="name">Name</label>
</div>
<div className="col-75">
<input type="text" placeholder="Enter Name" refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="exampleInputEmail1">Email address</label>
</div>
<div className="col-75">
<input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
<span style={{color: "red"}}>{this.state.errors["email"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="message">Message</label>
</div>
<div className="col-75">
<textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
<span style={{color: "red"}}>{this.state.errors["message"]}</span>
</div>
</div>
<div className="row">
<button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
</div>
</form>
)
}
}
Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input.
Per definition, NULL cannot be part of a successful comparison. Even a comparison to itself (NULL = NULL
) will fail. This means a key containing NULL would not work.
Additonally, NULL is allowed in a foreign key, to mark an optional relationship.(*) Allowing it in the PK as well would break this.
(*)A word of caution: Having nullable foreign keys is not clean relational database design.
If there are two entities A
and B
where A
can optionally be related to B
, the clean solution is to create a resolution table (let's say AB
). That table would link A
with B
: If there is a relationship then it would contain a record, if there isn't then it would not.
You can iterate over the length of the string and push the character at each position:
const str = 'Hello World';_x000D_
_x000D_
const stringToArray = (text) => {_x000D_
var chars = [];_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
chars.push(text[i]);_x000D_
}_x000D_
return chars_x000D_
}_x000D_
_x000D_
console.log(stringToArray(str))
_x000D_
Solution for Android Studio 3.6:
yourSwitch.setTextColor(getResources().getColor(R.color.yourColor));
Changes the text color of a in the color XML file defined value (yourColor).
Of course Pawel has given the right answer. But I found in this post that since EF 6+ it is possible to save private properties. So I would prefer this code, because you are not able to save the Strings in a wrong way.
public class Test
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column]
[Required]
private String StringsAsStrings { get; set; }
public List<String> Strings
{
get { return StringsAsStrings.Split(',').ToList(); }
set
{
StringsAsStrings = String.Join(",", value);
}
}
public Test()
{
Strings = new List<string>
{
"test",
"test2",
"test3",
"test4"
};
}
}
Just saying, this is also the value (kind of...) that is returned from php upon:
<?php var_dump(urlencode(PHP_EOL)); ?>
// Prints: string '%0D%0A' (length=6)-- used in 5.4.24 at least
Unlike in some laguages, empty
is not a keyword in Python. Python lists are constructed form the ground up, so if element i
has a value, then element i-1
has a value, for all i > 0
.
To do an equality check, you usually use either the ==
comparison operator.
>>> my_list = ["asdf", 0, 42, '', None, True, "LOLOL"]
>>> my_list[0] == "asdf"
True
>>> my_list[4] is None
True
>>> my_list[2] == "the universe"
False
>>> my_list[3]
""
>>> my_list[3] == ""
True
Here's a link to the strip
method: your comment indicates to me that you may have some strange file parsing error going on, so make sure you're stripping off newlines and extraneous whitespace before you expect an empty line.
Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.
Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.
The answer to my question is at Ansible: best practice for maintaining list of sudoers.
The Ansible playbook code fragment looks like this from my problem:
- name: Make sure we have a 'wheel' group
group:
name: wheel
state: present
- name: Allow 'wheel' group to have passwordless sudo
lineinfile:
dest: /etc/sudoers
state: present
regexp: '^%wheel'
line: '%wheel ALL=(ALL) NOPASSWD: ALL'
validate: 'visudo -cf %s'
- name: Add sudoers users to wheel group
user:
name=deployer
groups=wheel
append=yes
state=present
createhome=yes
- name: Set up authorized keys for the deployer user
authorized_key: user=deployer key="{{item}}"
with_file:
- /home/railsdev/.ssh/id_rsa.pub
And the best part is that the solution is idempotent. It doesn't add the line
%wheel ALL=(ALL) NOPASSWD: ALL
to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.
This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
You need to join
the two tables and then filter the result in where
clause:
SELECT country.name as country, country.headofstate
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
The global Git configuration file is stored at $HOME/.gitconfig
on all platforms.
However, you can simply open a terminal and execute git config
, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig
, unless you particularly want to.
@cope360 's excellent answer, converted to use join syntax.
select t.relname as table_name
, i.relname as index_name
, array_to_string(array_agg(a.attname), ', ') as column_names
from pg_class t
join pg_index ix
on t.oid = ix.indrelid
join pg_class i
on i.oid = ix.indexrelid
join pg_attribute a
on a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
where t.relkind = 'r'
and t.relname like 'test%'
group by t.relname
, i.relname
order by t.relname
, i.relname
;
I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/
For Windows vista and Windows 7 ,to open the command prompt 1) go to folder you want to work
2)In address bar type- cmd
press enter
it will open the command prompt for that location
all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
//THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = @img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.Parameters.Add("@img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
da.UpdateCommand.Parameters["@img"].Value = photo;
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.
In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.
I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.
Here is my version
#include <vector>
inline std::vector<std::string> Split(const std::string &str, const std::string &delim = " ")
{
std::vector<std::string> tokens;
if (str.size() > 0)
{
if (delim.size() > 0)
{
std::string::size_type currPos = 0, prevPos = 0;
while ((currPos = str.find(delim, prevPos)) != std::string::npos)
{
std::string item = str.substr(prevPos, currPos - prevPos);
if (item.size() > 0)
{
tokens.push_back(item);
}
prevPos = currPos + 1;
}
tokens.push_back(str.substr(prevPos));
}
else
{
tokens.push_back(str);
}
}
return tokens;
}
It works with multi-character delimiters. It prevents empty tokens to get in your results. It uses a single header. It returns the string as one single token when you provide no delimiter. It also returns an empty result if the string is empty. It is unfortunately inefficient because of the huge std::vector
copy UNLESS you are compiling using C++11, which should be using the move schematic. In C++11, this code should be fast.
Best way is to use the Carbon dependency.
With Carbon\Carbon::now();
you get the current Datetime.
With Carbon you can do like enything with the DateTime. Event things like this:
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).
x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.
x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.
A variation of the expression by @Gumbo that makes use of \K
for resetting match positions to prevent the inclusion of number blocks in the match. Usable in PCRE regex flavours.
123-\K(?:(?:apple|banana)(?=-456)|456\K)
Matches:
Match 1 apple
Match 2 banana
Match 3
Use parentheses:
data(2)
But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector
(immutable) or ArrayBuffer
(mutable) or possibly Array
(which is just a Java array, except again you index into it with (i)
instead of [i]
).
If you are looking for a simple way, here it is.
Create a utility class like this,
public class ApplicationUtils {
/**
* Sets the boolean preference value
*
* @param context the current context
* @param key the preference key
* @param value the value to be set
*/
public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(key, value).apply();
}
/**
* Get the boolean preference value from the SharedPreference
*
* @param context the current context
* @param key the preference key
* @return the the preference value
*/
public static boolean getBooleanPreferenceValue(Context context, String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(key, false);
}
}
At your Main Activity, onCreate()
if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
Log.d(TAG, "First time Execution");
ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
// do your first time execution stuff here,
}
if u also want ur UI (ie. ur flatList) to be up to date, use PrevState: in the example below if user clicks on the button , it is going to add a new object to the list( both in the model and UI)
data: ['shopping','reading'] // declared in constructor
onPress={() => {this.setState((prevState, props) => {
return {data: [new obj].concat(prevState.data) };
})}}.
You are trying to run your program with a Java version that does not support the version in which the code was compiled. So basically you must have compiled your code with a higher version and trying to run it using a lower version.
As you are getting
Unsupported major.minor version 51.0
and version 51.0 corresponds to J2SE 7 you have most probably compiled your code in Java 7 and trying to run it using a lower version. Check what java -version
displays. It should be the Java 7 version. If not make appropriate changes in the PATH/JAVA_HOME. Or you can compile with the same version you are trying to run the code. If the configurations are confusing you can always give absolute path /home/user/jdk1.7.0_11/bin/javac
and /home/user/jdk1.7.0_11/bin/java
.
Signed integers in C represent numbers. If a
and b
are variables of signed integer types, the standard will never require that a compiler make the expression a+=b
store into a
anything other than the arithmetic sum of their respective values. To be sure, if the arithmetic sum would not fit into a
, the processor might not be able to put it there, but the standard would not require the compiler to truncate or wrap the value, or do anything else for that matter if values that exceed the limits for their types. Note that while the standard does not require it, C implementations are allowed to trap arithmetic overflows with signed values.
Unsigned integers in C behave as abstract algebraic rings of integers which are congruent modulo some power of two, except in scenarios involving conversions to, or operations with, larger types. Converting an integer of any size to a 32-bit unsigned type will yield the member corresponding to things which are congruent to that integer mod 4,294,967,296. The reason subtracting 3 from 2 yields 4,294,967,295 is that adding something congruent to 3 to something congruent to 4,294,967,295 will yield something congruent to 2.
Abstract algebraic rings types are often handy things to have; unfortunately, C uses signedness as the deciding factor for whether a type should behave as a ring. Worse, unsigned values are treated as numbers rather than ring members when converted to larger types, and unsigned values smaller than int
get converted to numbers when any arithmetic is performed upon them. If v
is a uint32_t
which equals 4,294,967,294
, then v*=v;
should make v=4
. Unfortunately, if int
is 64 bits, then there's no telling what v*=v;
could do.
Given the standard as it is, I would suggest using unsigned types in situations where one wants the behavior associated with algebraic rings, and signed types when one wants to represent numbers. It's unfortunate that C drew the distinctions the way it did, but they are what they are.
You can also use LocalDate.parse()
or LocalDateTime.parse()
on a String
without providing it with a pattern, if the String
is in ISO-8601 format.
for example,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
Output,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
and use DateTimeFormatter
only if you have to deal with other date patterns.
For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);
Output
04 Aug 2015 parses to 2015-08-04
also remember that the DateTimeFormatter
object is bidirectional; it can both parse input and format output.
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));
Output
2015-08-04 formats as 04 Aug 2015
(see complete list of Patterns for Formatting and Parsing DateFormatter)
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
Your problem may be that you are dealing with DATETIME data, not just dates. If a row has a mydate that is '2008-11-25 09:30 AM', then your WHERE mydate<='2008-11-25'; is not going to return that row. '2008-11-25' has an implied time of 00:00 (midnight), so even though the date part is the same, they are not equal, and mydate is larger.
If you use < '2008-11-26' instead of <= '2008-11-25', that would work. The Datediff method works because it compares just the date portion, and ignores the times.
There can be a problem with "\00a0" in pseudo-elements because it takes the text-decoration of its defining element, so that, for example, if the defining element is underlined, then the white space of the pseudo-element is also underlined.
The easiest way to deal with this is to define the opacity of the pseudo-element to be zero, eg:
element:before{
content: "_";
opacity: 0;
}
Here is a code snip to do exactly that.
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
1f, 1f, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(1000);
v.startAnimation(anim);
}
The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...)
.
The other 4 args are for the Y-scaling we do care about.
startScale, endScale
- In your case, you'd use 0f, 0.6f
.
Animation.RELATIVE_TO_SELF, 1f
- This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f
because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f
.
Finally, and equally important, is the call to anim.setFillAfter(true)
. If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.
So in your case, you can do something like this:
View v = findViewById(R.id.viewContainer);
scaleView(v, 0f, .6f);
There's actually a pretty easy way to do this. The code should be something like:
<script type="test/javascript">
function showcontent(x){
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 1) {
document.getElementById('content').innerHTML = "<img src='loading.gif' />";
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('content').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', x+'.html', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(null);
}
And in the HTML:
<body onload="showcontent(main)"> <!-- onload optional -->
<div id="content"><img src="loading.gif"></div> <!-- leave img out if not onload -->
</body>
I did something like that on my page and it works great.
This answer contains 2 generators for random-based and name-based UUIDs, compliant with RFC-4122. Feel free to use and share.
RANDOM-BASED (v4)
This utility class that generates random-based UUIDs:
package your.package.name;
import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;
/**
* Utility class that creates random-based UUIDs.
*
*/
public abstract class RandomUuidCreator {
private static final int RANDOM_VERSION = 4;
/**
* Returns a random-based UUID.
*
* It uses a thread local {@link SecureRandom}.
*
* @return a random-based UUID
*/
public static UUID getRandomUuid() {
return getRandomUuid(SecureRandomLazyHolder.THREAD_LOCAL_RANDOM.get());
}
/**
* Returns a random-based UUID.
*
* It uses any instance of {@link Random}.
*
* @return a random-based UUID
*/
public static UUID getRandomUuid(Random random) {
long msb = 0;
long lsb = 0;
// (3) set all bit randomly
if (random instanceof SecureRandom) {
// Faster for instances of SecureRandom
final byte[] bytes = new byte[16];
random.nextBytes(bytes);
msb = toNumber(bytes, 0, 8); // first 8 bytes for MSB
lsb = toNumber(bytes, 8, 16); // last 8 bytes for LSB
} else {
msb = random.nextLong(); // first 8 bytes for MSB
lsb = random.nextLong(); // last 8 bytes for LSB
}
// Apply version and variant bits (required for RFC-4122 compliance)
msb = (msb & 0xffffffffffff0fffL) | (RANDOM_VERSION & 0x0f) << 12; // apply version bits
lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits
// Return the UUID
return new UUID(msb, lsb);
}
private static long toNumber(final byte[] bytes, final int start, final int length) {
long result = 0;
for (int i = start; i < length; i++) {
result = (result << 8) | (bytes[i] & 0xff);
}
return result;
}
// Holds thread local secure random
private static class SecureRandomLazyHolder {
static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = ThreadLocal.withInitial(SecureRandom::new);
}
/**
* For tests!
*/
public static void main(String[] args) {
System.out.println("// Using thread local `java.security.SecureRandom` (DEFAULT)");
System.out.println("RandomUuidCreator.getRandomUuid()");
System.out.println();
for (int i = 0; i < 5; i++) {
System.out.println(RandomUuidCreator.getRandomUuid());
}
System.out.println();
System.out.println("// Using `java.util.Random` (FASTER)");
System.out.println("RandomUuidCreator.getRandomUuid(new Random())");
System.out.println();
Random random = new Random();
for (int i = 0; i < 5; i++) {
System.out.println(RandomUuidCreator.getRandomUuid(random));
}
}
}
This is the output:
// Using thread local `java.security.SecureRandom` (DEFAULT)
RandomUuidCreator.getRandomUuid()
'ef4f5ad2-8147-46cb-8389-c2b8c3ef6b10'
'adc0305a-df29-4f08-9d73-800fde2048f0'
'4b794b59-bff8-4013-b656-5d34c33f4ce3'
'22517093-ee24-4120-96a5-ecee943992d1'
'899fb1fb-3e3d-4026-85a8-8a2d274a10cb'
// Using `java.util.Random` (FASTER)
RandomUuidCreator.getRandomUuid(new Random())
'4dabbbc2-fcb2-4074-a91c-5e2977a5bbf8'
'078ec231-88bc-4d74-9774-96c0b820ceda'
'726638fa-69a6-4a18-b09f-5fd2a708059b'
'15616ebe-1dfd-4f5c-b2ed-cea0ac1ad823'
'affa31ad-5e55-4cde-8232-cddd4931923a'
NAME-BASED (v3 and v5)
This utility class that generates name-based UUIDs (MD5 and SHA1):
package your.package.name;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
/**
* Utility class that creates UUIDv3 (MD5) and UUIDv5 (SHA1).
*
*/
public class HashUuidCreator {
// Domain Name System
public static final UUID NAMESPACE_DNS = new UUID(0x6ba7b8109dad11d1L, 0x80b400c04fd430c8L);
// Uniform Resource Locator
public static final UUID NAMESPACE_URL = new UUID(0x6ba7b8119dad11d1L, 0x80b400c04fd430c8L);
// ISO Object ID
public static final UUID NAMESPACE_ISO_OID = new UUID(0x6ba7b8129dad11d1L, 0x80b400c04fd430c8L);
// X.500 Distinguished Name
public static final UUID NAMESPACE_X500_DN = new UUID(0x6ba7b8149dad11d1L, 0x80b400c04fd430c8L);
private static final int VERSION_3 = 3; // UUIDv3 MD5
private static final int VERSION_5 = 5; // UUIDv5 SHA1
private static final String MESSAGE_DIGEST_MD5 = "MD5"; // UUIDv3
private static final String MESSAGE_DIGEST_SHA1 = "SHA-1"; // UUIDv5
private static UUID getHashUuid(UUID namespace, String name, String algorithm, int version) {
final byte[] hash;
final MessageDigest hasher;
try {
// Instantiate a message digest for the chosen algorithm
hasher = MessageDigest.getInstance(algorithm);
// Insert name space if NOT NULL
if (namespace != null) {
hasher.update(toBytes(namespace.getMostSignificantBits()));
hasher.update(toBytes(namespace.getLeastSignificantBits()));
}
// Generate the hash
hash = hasher.digest(name.getBytes(StandardCharsets.UTF_8));
// Split the hash into two parts: MSB and LSB
long msb = toNumber(hash, 0, 8); // first 8 bytes for MSB
long lsb = toNumber(hash, 8, 16); // last 8 bytes for LSB
// Apply version and variant bits (required for RFC-4122 compliance)
msb = (msb & 0xffffffffffff0fffL) | (version & 0x0f) << 12; // apply version bits
lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits
// Return the UUID
return new UUID(msb, lsb);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Message digest algorithm not supported.");
}
}
public static UUID getMd5Uuid(String string) {
return getHashUuid(null, string, MESSAGE_DIGEST_MD5, VERSION_3);
}
public static UUID getSha1Uuid(String string) {
return getHashUuid(null, string, MESSAGE_DIGEST_SHA1, VERSION_5);
}
public static UUID getMd5Uuid(UUID namespace, String string) {
return getHashUuid(namespace, string, MESSAGE_DIGEST_MD5, VERSION_3);
}
public static UUID getSha1Uuid(UUID namespace, String string) {
return getHashUuid(namespace, string, MESSAGE_DIGEST_SHA1, VERSION_5);
}
private static byte[] toBytes(final long number) {
return new byte[] { (byte) (number >>> 56), (byte) (number >>> 48), (byte) (number >>> 40),
(byte) (number >>> 32), (byte) (number >>> 24), (byte) (number >>> 16), (byte) (number >>> 8),
(byte) (number) };
}
private static long toNumber(final byte[] bytes, final int start, final int length) {
long result = 0;
for (int i = start; i < length; i++) {
result = (result << 8) | (bytes[i] & 0xff);
}
return result;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "JUST_A_TEST_STRING";
UUID namespace = UUID.randomUUID(); // A custom name space
System.out.println("Java's generator");
System.out.println("UUID.nameUUIDFromBytes(): '" + UUID.nameUUIDFromBytes(string.getBytes()) + "'");
System.out.println();
System.out.println("This generator");
System.out.println("HashUuidCreator.getMd5Uuid(): '" + HashUuidCreator.getMd5Uuid(string) + "'");
System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(string) + "'");
System.out.println();
System.out.println("This generator WITH name space");
System.out.println("HashUuidCreator.getMd5Uuid(): '" + HashUuidCreator.getMd5Uuid(namespace, string) + "'");
System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(namespace, string) + "'");
}
}
This is the output:
// Java's generator
UUID.nameUUIDFromBytes(): '9e120341-627f-32be-8393-58b5d655b751'
// This generator
HashUuidCreator.getMd5Uuid(): '9e120341-627f-32be-8393-58b5d655b751'
HashUuidCreator.getSha1Uuid(): 'e4586bed-032a-5ae6-9883-331cd94c4ffa'
// This generator WITH name space
HashUuidCreator.getMd5Uuid(): '2b098683-03c9-3ed8-9426-cf5c81ab1f9f'
HashUuidCreator.getSha1Uuid(): '1ef568c7-726b-58cc-a72a-7df173463bbb'
ALTERNATE GENERATOR
You can also use the uuid-creator
library. See these examples:
// Create a random-based UUID
UUID uuid = UuidCreator.getRandomBased();
// Create a name based UUID (SHA1)
String name = "JUST_A_TEST_STRING";
UUID uuid = UuidCreator.getNameBasedSha1(name);
Project page: https://github.com/f4b6a3/uuid-creator
Keeping it simple, if you want the request to use the same browsing context as the page you are already looking at then in the Chrome console just do:
window.location="https://www.example.com";
I was to dumb to find the Solution...
For me (VB):
Dim string= Datagrid.SelectedCells(0).Item(0).ToString
select * from Reference where reference_dt = DateAdd(month,1,another_date_reference)
To truncate a string provided by the maximum limit without breaking a word use this:
/**
* truncate a string provided by the maximum limit without breaking a word
* @param string $str
* @param integer $maxlen
* @return string
*/
public static function truncateStringWords($str, $maxlen): string
{
if (strlen($str) <= $maxlen) return $str;
$newstr = substr($str, 0, $maxlen);
if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr;
}
From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:
dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059
And here's the code I used (Python 3.6)
from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit
def is_date_parsing(date_str):
try:
return bool(date_parser.parse(date_str))
except ValueError:
return False
def is_date_matching(date_str):
try:
return bool(datetime.strptime(date_str, '%Y-%m-%d'))
except ValueError:
return False
if __name__ == '__main__':
print("dateutil.parser (valid date):", end=' ')
print(timeit("is_date_parsing('2021-01-26')",
setup="from __main__ import is_date_parsing",
number=100000))
print("dateutil.parser (invalid date):", end=' ')
print(timeit("is_date_parsing('meh')",
setup="from __main__ import is_date_parsing",
number=100000))
print("datetime.strptime (valid date):", end=' ')
print(timeit("is_date_matching('2021-01-26')",
setup="from __main__ import is_date_matching",
number=100000))
print("datetime.strptime (invalid date):", end=' ')
print(timeit("is_date_matching('meh')",
setup="from __main__ import is_date_matching",
number=100000))
When you create an initialization of the ResourceBundle, you can do this way also.
For testing and development I have created a properties file under \src with the name prp.properties.
Use this way:
ResourceBundle rb = ResourceBundle.getBundle("prp");
Naming convention and stuff:
http://192.9.162.55/developer/technicalArticles/Intl/ResourceBundles/
Add the linked server first with
exec sp_addlinkedserver
@server = 'SNRJDI\SLAMANAGEMENT',
@srvproduct=N'',
@provider=N'SQLNCLI'
Make a HTML Table from a JSON array of Objects by extending $ as shown below
$.makeTable = function (mydata) {
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
tblHeader += "</tr>";
$(tblHeader).appendTo(table);
$.each(mydata, function (index, value) {
var TableRow = "<tr>";
$.each(value, function (key, val) {
TableRow += "<td>" + val + "</td>";
});
TableRow += "</tr>";
$(table).append(TableRow);
});
return ($(table));
};
and use as follows:
var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");
where TableCont is some div
If you have a pd.Series
object x
with index named 'Gene', you can use reset_index
and supply the name
argument:
df = x.reset_index(name='count')
Here's a demo:
x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'
df = x.reset_index(name='count')
print(df)
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
Echoing justanotherdev's comment:
Mind-blowing and useful:
CTRL
+ SHIFT
+ p
(Mac: CMD
+ SHIFT
+ p
)>transform
pick upper/lower case and press enterIf you are editing your Makefile in eclipse:
Windows-> Preferences->General->Editor->Text Editors->Show Whitespace Characters -> Apply
Or use the shortcut shown below.
Tab will be represented by gray ">>" and Space will be represented by gray "." as in figure below.
It looks like the object file was compiled on a 64-bit toolchain, and you're using a 32-bit toolchain. Have you tried recompiling the object file in 32-bit mode?
I think that you should use rather the following:
data => {
this.results = this.results.concat(data.results);
this._next = data.next;
},
From the concat
doc:
The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.
On top of everything that's been said (
https://stackoverflow.com/a/4416666/172109
),
which is correct, TFS isn't just a VCS. One major feature that TFS provides is natively integrated bug tracking functionality. Changesets are linked to issues and could be tracked. Various policies for check-ins are supported, as well as integration with Windows domain, which is what people who run TFS have. Tightly integrated GUI with Visual Studio is another selling point, which appeals to less than average mouse and click developer and his manager.
Hence comparing Git to TFS isn't a proper question to ask. Correct, though impractical, question is to compare Git with just VCS functionality of TFS. At that, Git blows TFS out of the water. However, any serious team needs other tools and this is where TFS provides one stop destination.
If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &
-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:
void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference
You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)
), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.
Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.
I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:
void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foo1(arr);
foo2(arr);
foo3(arr);
foo4(arr);
}
// TypeScript
const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );
If you want this environment variable available to all users and on system start then you can add the following to /etc/profile.d/java.sh (create it if necessary):
export JDK_HOME=/usr/lib/jvm/java-7-oracle
export JAVA_HOME=/usr/lib/jvm/java-7-oracle
Then in a terminal run:
sudo chmod +x /etc/profile.d/java.sh
source /etc/profile.d/java.sh
My second question is - should it point to java-6-sun or java-6-sun-1.6.0.24 ?
It should always point to java-7-oracle
as that symlinks to the latest installed one (assuming you installed Java from the Ubuntu repositories and now from the download available at oracle.com).
For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.
<html>
<head>
<script>
var div, container = document.getElementById("container")
for(var i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
https://codepen.io/pcwanderer/pen/MMEREr
Looking at the error in the console for the above code.
Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.
<html>
<head>
<style>
#container{
height: 200px;
width: 700px;
background-color: red;
margin: 10px;
}
div{
height: 100px;
width: 100px;
background-color: purple;
margin: 20px;
display: inline-block;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var div, container = document.getElementById("container")
for(let i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</body>
</html>
https://codepen.io/pcwanderer/pen/pXWBQL
I hope this helps. :)
Wrap your image with a span
element with a black background.
.img-wrapper {
display: inline-block;
background: #000;
}
.item-fade {
vertical-align: top;
transition: opacity 0.3s;
-webkit-transition: opacity 0.3s;
opacity: 1;
}
.item-fade:hover {
opacity: 0.2;
}
_x000D_
<span class="img-wrapper">
<img class="item-fade" src="http://placehold.it/100x100/cf5" />
</span>
_x000D_
See the docs: https://getbootstrap.com/docs/4.0/utilities/display/
In order to hide the content on mobile and display on the bigger devices you have to use the following classes:
d-none d-sm-block
The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.
I suggest to read about that before migration:
https://getbootstrap.com/docs/4.0/migration/#responsive-utilities
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
if you want to reload your entire page, like it seems, just inject $window into your controller and then call
$window.location.href = '/';
but if you only want to reload your current view, inject $scope, $state and $stateParams (the latter just in case you need to have some parameters change in this upcoming reload, something like your page number), then call this within any controller method:
$stateParams.page = 1;
$state.reload();
AngularJS v1.3.15 angular-ui-router v0.2.15
Here is the explanation:
https://www.w3.org/TR/css-flexbox-1/#flex-common
flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.
Therefore flex:1
is equivalent to flex: 1 1 0
Here's a slightly different approach (I don't think the other answers do this). I'm not sure whether I love it or hate it, but it works!
export function addDaySuffix(day: number) {
const suffixes =
' stndrdthththththththththththththththththstndrdthththththththst';
const startIndex = day * 2;
return `${day}${suffixes.substring(startIndex, startIndex + 2)}`;
}