public function testAction()
{
$filter_a = array('like'=>'a%');
$filter_b = array('like'=>'b%');
echo(
(string)
Mage::getModel('catalog/product')
->getCollection()
->addFieldToFilter('sku',array($filter_a,$filter_b))
->getSelect()
);
}
Result:
WHERE (((e.sku like 'a%') or (e.sku like 'b%')))
git pull origin master
this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.
You need to populate the empty indexes with nulls.
while (arraylist.size() < position)
{
arraylist.add(null);
}
arraylist.add(position, object);
swift 3
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelPressed(_:)))
cancelBarButton.setTitleTextAttributes( [NSFontAttributeName : UIFont.cancelBarButtonFont(),
NSForegroundColorAttributeName : UIColor.white], for: .normal)
self.navigationItem.leftBarButtonItem = cancelBarButton
func cancelPressed(_ sender: UIBarButtonItem ) {
self.dismiss(animated: true, completion: nil)
}
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
Another way of doing it:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year,
today.Month,
DateTime.DaysInMonth(today.Year,
today.Month));
If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.
So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.
Example with Digest Authentication:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace NUI
{
public class DigestAuthFixer
{
private static string _host;
private static string _user;
private static string _password;
private static string _realm;
private static string _nonce;
private static string _qop;
private static string _cnonce;
private static DateTime _cnonceDate;
private static int _nc;
public DigestAuthFixer(string host, string user, string password)
{
// TODO: Complete member initialization
_host = host;
_user = user;
_password = password;
}
private string CalculateMd5Hash(
string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
private string GrabHeaderVar(
string varName,
string header)
{
var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
return matchHeader.Groups[1].Value;
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(
string dir)
{
_nc = _nc + 1;
var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
var digestResponse =
CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
"algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
_user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}
public string GrabResponse(
string dir)
{
var url = _host + dir;
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(_cnonce) &&
DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(dir));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
_qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
_nc = 0;
_cnonce = new Random().Next(123400, 9999999).ToString();
_cnonceDate = DateTime.Now;
var request2 = (HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add("Authorization", GetDigestHeader(dir));
response = (HttpWebResponse)request2.GetResponse();
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Then you could call it:
DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);
if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)
you could also return it as stream and use XmlDocument Load() method.
Since the code sample is a bit outdated I thought I'd share a more recent approach, using Angular 4.3 and the new(er) HttpClient API, @angular/common/http
export class FileUpload {
@ViewChild('selectedFile') selectedFileEl;
uploadFile() {
let params = new HttpParams();
let formData = new FormData();
formData.append('upload', this.selectedFileEl.nativeElement.files[0])
const options = {
headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
params: params,
reportProgress: true,
withCredentials: true,
}
this.http.post('http://localhost:3000/api/FileUploads/fileupload', formData, options)
.subscribe(
data => {
console.log("Subscribe data", data);
},
(err: HttpErrorResponse) => {
console.log(err.message, JSON.parse(err.error).error.message);
}
)
.add(() => this.uploadBtn.nativeElement.disabled = false);//teardown
}
I just did the following (in V 3.5) and it worked like a charm:
<p:column headerText="name" width="20px"/>
I like to simplify the code without using conditional operators in such cases:
TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP
see http://api.jquery.com/prev/
var link = $("#me").parent("div").prev("h3").find("b");
alert(link.text());
I found a very simple method that works well:
<input type="text" onclick="this.focus();this.select()">
You don't really need a regex.
printf "%s\n" *[!\ -~]*
This will show file names with control characters in their names, too, but I consider that a feature.
If you don't have any matching files, the glob will expand to just itself, unless you have nullglob
set. (The expression does not match itself, so technically, this output is unambiguous.)
There is an open bug on Chromium: https://bugs.chromium.org/p/chromium/issues/detail?id=584905
Unfortunately they depend on Apple to open up an API in WKView for this to happen, after which maybe debugging will be available from Safari.
I had a similar issue with restoring using SQL Management Studio. I tried to restore a backup of the database to a new one with a different name. At first this failed and after fixing the new database's file names it was successfully performed - in any case the issue I'm describing re-occurred even if I got this right from the first time. So, after the restoration, the original database remained with a (Restoring...) next to its name. Considering the answers of the forum above (Bhusan's) I tried running in the query editor on the side the following:
RESTORE DATABASE "[NAME_OF_DATABASE_STUCK_IN_RESTORING_STATE]"
which fixed the issue. I was having trouble at first because of the database name which contained special characters. I resolved this by adding double quotes around - single quotes wouldn't work giving an "Incorrect syntax near ..." error.
This was the minimal solution I've tried to resolve this issue (stuck database in restoring state) and I hope it can be applied to more cases.
Instead of
return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);
try
return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);
This works on all current browsers on WinXP. Basically just checking what the current backgrond image is. If it's image1, show image2, otherwise show image1.
The jsapi stuff just loads jQuery from the Google CDN (easier for testing a misc file on the desktop).
The replace is for cross-browser compatibility (opera and ie add quotes to the url and firefox, chrome and safari remove quotes).
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
var original_image = 'url(http://stackoverflow.com/Content/img/wmd/link.png)';
var second_image = 'url(http://stackoverflow.com/Content/img/wmd/code.png)';
$('.mydiv').click(function() {
if ($(this).css('background-image').replace(/"/g, '') == original_image) {
$(this).css('background-image', second_image);
} else {
$(this).css('background-image', original_image);
}
return false;
});
});
</script>
<style>
.mydiv {
background-image: url('http://stackoverflow.com/Content/img/wmd/link.png');
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="mydiv"> </div>
</body>
</html>
The following works for me:
Query query = em.createNativeQuery("BEGIN VALIDACIONES_QPAI.RECALC_COMP_ASSEMBLY('X','X','X',0); END;");
query.executeUpdate();
You cannot in pure CSS. Having an image covering the whole page behind all other components is probably your best bet (looks like that's the solution given above). Anyway, chances are it will look awful anyway. I would try either an image big enough to cover most screen resolutions (say up to 1600x1200, above it is scarcer), to limit the width of the page, or just to use an image that tile.
I have an un-rooted Nexus 4 (which has only internal storage, no SD card) and was getting this error with larger apps updating. Smaller apps would update fine.
I discovered that it was because I have recently signed up to the Play Music All Access service and had pinned several albums.
These are downloaded to the hidden /data
partition and it was this that had run out of space (I assume)
I unpinned a couple of albums and now have no problems installing apps.
Use == operator instead of isEqual
Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.
String Equality
Two String values are considered equal if they contain exactly the same characters in the same order:
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.
For more read official documentation of Swift (search Comparing Strings).
The current PHP Nightrain (4.0.0) is written in Python and it uses the wxPython libraries. So far wxPython has been working well to get PHP Nightrain where it is today but in order to push PHP Nightrain to its next level, we are introducing a sibling of PHP Nightrain, the PHPWebkit!
It's an update to PHP Nightrain.
This is more a clarification than an answer! Yes, the clue is in the error message:
[hi: command not found
which shows you that your "hi" has been concatenated to the "[".
Unlike in more traditional programming languages, in Bash, "[" is a command just like the more obvious "ls", etc. - it's not treated specially just because it's a symbol, hence the "[" and the (substituted) "$s1" which are immediately next to each other in your question, are joined (as is correct for Bash), and it then tries to find a command in that position: [hi - which is unknown to Bash.
In C and some other languages, the "[" would be seen as a different "character class" and would be disjoint from the following "hi".
Hence you require a space after the opening "[".
This is derived from @fallino's answer, with some adjustments and simplifications by using the output format option for docker history. Since macOS and Gnu/Linux have different command-line utilities, a different version is necessary for Mac. If you only need one or the other, you can just use those lines.
#!/bin/bash
case "$OSTYPE" in
linux*)
docker history --no-trunc --format "{{.CreatedBy}}" $1 | # extract information from layers
tac | # reverse the file
sed 's,^\(|3.*\)\?/bin/\(ba\)\?sh -c,RUN,' | # change /bin/(ba)?sh calls to RUN
sed 's,^RUN #(nop) *,,' | # remove RUN #(nop) calls for ENV,LABEL...
sed 's, *&& *, \\\n \&\& ,g' # pretty print multi command lines following Docker best practices
;;
darwin*)
docker history --no-trunc --format "{{.CreatedBy}}" $1 | # extract information from layers
tail -r | # reverse the file
sed -E 's,^(\|3.*)?/bin/(ba)?sh -c,RUN,' | # change /bin/(ba)?sh calls to RUN
sed 's,^RUN #(nop) *,,' | # remove RUN #(nop) calls for ENV,LABEL...
sed $'s, *&& *, \\\ \\\n \&\& ,g' # pretty print multi command lines following Docker best practices
;;
*)
echo "unknown OSTYPE: $OSTYPE"
;;
esac
If you write an image gallery with ImageView
s and ViewPager
, that supports zoom and pan, see a simple solution described here: Implementing a zoomable ImageView by Extending the Default ViewPager in Phimpme Android (and Github sample - PhotoView). This solution doesn't work with ViewPager
alone.
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs)
{
super(context,attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
try {
return super.onInterceptTouchEvent(event);
} catch (IllegalArgumentException e) {
return false;
}
}
}
I'm not sure which version you had, but this question was asked for long time ago. Currently with Angular 1.5, I can use the ng-keypress
event and debounce
function from Lodash to emulate similar behavior like ng-change
, so I can capture the $event
<input type="text" ng-keypress="edit($event)" ng-model="myModel">
$scope.edit = _.debounce(function ($event) { console.log("$event", $event) }, 800)
http://php.net/session.gc-maxlifetime
session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)
OK, just change your code to something like this:
<script>
function submit() {
return confirm('Do you really want to submit the form?');
}
</script>
<form onsubmit="return submit(this);">
<input type="image" src="xxx" border="0" name="submit" onclick="show_alert();"
alt="PayPal - The safer, easier way to pay online!" value="Submit">
</form>
Also this is the code in run, just I make it easier to see how it works, just run the code below to see the result:
function submitForm() {_x000D_
return confirm('Do you really want to submit the form?');_x000D_
}
_x000D_
<form onsubmit="return submitForm(this);">_x000D_
<input type="text" border="0" name="submit" />_x000D_
<button value="submit">submit</button>_x000D_
</form>
_x000D_
You can do it in Python 2.7+ with python-dateutil
(which is insalled on Mac by default):
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'
Or you if you want to convert from an existed stored string:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT)
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)
SELECT SUBSTRING(subject, 1, 10) FROM tbl
There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.
To convert an object in string you use the str()
function. It works with any object that has a method called __str__()
defined. In fact
str(a)
is equivalent to
a.__str__()
The same if you want to convert something to int, float, etc.
Unlimited string readed:
String content = "";
char character;
while(Serial.available()) {
character = Serial.read();
content.concat(character);
}
if (content != "") {
Serial.println(content);
}
Try sgrep. It's not clear exactly what you are trying to do, but I surely would not attempt writing an XML parser in bash.
i came across this problem when i was trying to do pos tagging in nltk.
the way i got it correct is by making a new directory along with corpora directory named "taggers" and copying max_pos_tagger in directory taggers.
hope it works for you too. best of luck with it!!!.
This answer is counting that the second parameter is useless when calling removeAttr! (as it was when this answer was posted) Do not use this otherwise!
Can't beat RienNeVaPlus's clean answer, but it does the job as well, it's basically a more compressed way to do the ternary operation:
$('.list-sort')[$('.list-sort').hasAttr('colspan') ?
'removeAttr' : 'attr']('colspan', 6);
an extra variable can be used in these cases, when you need to use the reference more than once:
var $listSort = $('.list-sort');
$listSort[$listSort.hasAttr('colspan') ? 'removeAttr' : 'attr']('colspan', 6);
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
Normally, you add regular values to mySQL, from PHP like this:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
When your values are empty/null ($val1=="" or $val1==NULL), and you want NULL to be added to SQL and not 0 or empty string, to the following:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')?"NULL":("'".$val1."'")) . ", ".
(($val2=='')?"NULL":("'".$val2."'")) .
")";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
Note that null must be added as "NULL" and not as "'NULL'" . The non-null values must be added as "'".$val1."'", etc.
Hope this helps, I just had to use this for some hardware data loggers, some of them collecting temperature and radiation, others only radiation. For those without the temperature sensor I needed NULL and not 0, for obvious reasons ( 0 is an accepted temperature value also).
The other answers were incorrect, at least in my case. request.path
does not provide the full url, only the relative url, e.g. /paper/53
. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path
.
I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone! So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.
Actually, it is possible to create a branch in your fork from any commit of the upstream in the browser:
https://github.com/<repo>/commits/<hash>
, where repo is your fork, and hash is full hash of commit which you can find in the upstream web interface. For example, I can open https://github.com/max630/linux/commits/0aa0313f9d576affd7747cc3f179feb097d28990, which points to linux
master
as time of writing.You can then fetch that branch to your local clone, and you won't have to push all that data back to GitHub when you push edits on top of that commit. Or use the web interface to change something in that branch.
How it works (it is a guess, I don't know how exactly GitHub does it): forks share object storage and use namespaces to separate users' references. So you can access all commits through your fork, even if they did not exist by the time of forking.
For me, these two things helped on different occasions:
1) If you've just installed the MS Access runtime, reboot the server. Bouncing the database instance isn't enough.
2) As well as making sure the Excel file isn't open, check you haven't got Windows Explorer open with the preview pane switched on - that locks it too.
The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
// Add the whole configuration object here.
services.AddSingleton<IConfiguration>(Configuration);
}
In your controller add a field for the configuration and a parameter for it on a constructor
private readonly IConfiguration configuration;
public HomeController(IConfiguration config)
{
configuration = config;
}
Now later in your view code you can access it like:
connectionString = configuration.GetConnectionString("DefaultConnection");
I know this is an old thread but I just wanted to add a little as the marked solution didn't solve the problem for me (although I tried many times).
The only way I could actually stop git form tracking the folder was to do the following:
git rm -r --cached your_folder/
your_folder/
to .gitignoreYou should now see that the folder is no longer tracked.
Don't ask me why just clearing the cache didn't work for me, I am not a Git super wizard but this is how I solved the issue.
You may not pass str
to fit this kind of classifier.
For example, if you have a feature column named 'grade' which has 3 different grades:
A,B and C.
you have to transfer those str
"A","B","C" to matrix by encoder like the following:
A = [1,0,0]
B = [0,1,0]
C = [0,0,1]
because the str
does not have numerical meaning for the classifier.
In scikit-learn, OneHotEncoder
and LabelEncoder
are available in inpreprocessing
module.
However OneHotEncoder
does not support to fit_transform()
of string.
"ValueError: could not convert string to float" may happen during transform.
You may use LabelEncoder
to transfer from str
to continuous numerical values. Then you are able to transfer by OneHotEncoder
as you wish.
In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object
. The following code works for me and I hope this will help you.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for column_name in train_data.columns:
if train_data[column_name].dtype == object:
train_data[column_name] = le.fit_transform(train_data[column_name])
else:
pass
<script>
$(document).ready(function(){
$('#colorselector').on('change', function() {
if ( this.value == 'red')
{
$("#divid").show();
}
else
{
$("#divid").hide();
}
});
});
</script>
Do like this for every value
You may want to review through the Youtube JavaScript API Reference docs.
When you embed your video(s) on the page, you will need to pass this parameter:
http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1
If you want a stop all videos button, you can setup a javascript routine to loop through your videos and stop them:
player.stopVideo()
This does involve keeping track of all the page IDs for each video on the page. Even simpler might be to make a class and then use jQuery.each.
$('#myStopClickButton').click(function(){
$('.myVideoClass').each(function(){
$(this).stopVideo();
});
});
My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):
// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
// Replace 8000, below, with the correct size of the field
cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
cmd.ExecuteNonQuery();
}
Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with
Firstly you have to make it executable using: chmod +x name_of_your_file_script
.
After you made it executable, you can run it using ./same_name_of_your_file_script
git fetch origin master:master
pulls the latest version of master without needing to check it out.
So all you need is:
git fetch origin master:master && git rebase master
Notepad++
-> Replace window
Ensure that in Search mode you have selected the Regular expression radio button
Find what:
^(.*)(\r?\n\1)+$
Replace with:
$1
Before:
and we think there
and we think there
single line
Is it possible to
Is it possible to
After:
and we think there
single line
Is it possible to
Using getimagesize function, we can also get these properties of that specific image-
<?php
list($width, $height, $type, $attr) = getimagesize("image_name.jpg");
echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";
//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>
Result like this -
Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'
Type of image consider like -
1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM
You can use the Python implementation of the curses library: curses — Terminal handling for character-cell displays
Also, run this and you'll find your box:
for i in range(255):
print i, chr(i)
I know it a kind of obvious, but CharSequence is an interface whereas String is a concrete class :)
java.lang.String is an implementation of this interface...
In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):
select myintfield + 0.0 as myfloatfield from mytable
While @Heximal's answer works, I don't personally recommend it.
This is because it uses implicit casting. Although you didn't type CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
. But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.
I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.
If you want to be explicit, I would use the following.
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
If you are using an old version of FFMPEG and you cant upgrade you can do the following:
ffmpeg -i PATH/VIDEO_FILE_NAME.mp4 -i PATH/AUDIO_FILE_NAME.mp3 -vcodec copy -shortest DESTINATION_PATH/NEW_VIDEO_FILE_NAME.mp4
Notice that I used -vcodec
Object.prototype.toString.call(myVar)
will return:
"[object Object]"
if myVar is an object"[object Array]"
if myVar is an arrayFor more information on this and why it is a good alternative to typeof, check out this article.
In case of a large project, it's difficult to fix each of these exceptions. At the same time, using Silent
is not advised. I have written a script to remove all the unnecessary stubbings given a list of them.
https://gist.github.com/cueo/da1ca49e92679ac49f808c7ef594e75b
We just need to copy-paste the mvn
output and write the list of these exceptions using regex and let the script take care of the rest.
An <input>
's width is generated from its size
attribute. The default size
is what's driving the auto width.
You could try width:100%
as illustrated in my example below.
Doesn't fill width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:auto' />
</form>
Fills width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:100%' />
</form>
Smaller size, smaller width:
<form action='' method='post' style='width:200px;background:khaki'>
<input size='5' />
</form>
UPDATE
Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)
<div style='padding:30px;width:200px;background:red'>
<form action='' method='post' style='width:200px;background:blue;padding:3px'>
<input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
<br /><br />
<input size='' style='width:100%' />
</form>
</div>
Loki has both a Factory Method and an Abstract Factory. Both are documented (extensively) in Modern C++ Design, by Andei Alexandrescu. The factory method is probably closer to what you seem to be after, though it's still a bit different (at least if memory serves, it requires you to register a type before the factory can create objects of that type).
If you're using Google+ javascript button, then you have to use postmessage
instead of the actual URI. It took me almost the whole day to figure this out since Google's docs do not clearly state it for some reason.
On windows run "cmd " as administrator and execute command.
"C:\Program Files\Git\mingw64\etc>"
"git config --system core.longpaths true"
or you have to chmod for the folder whereever git is installed.
or manullay update your file manually by going to path "Git\mingw64\etc"
[http]
sslBackend = schannel
[diff "astextplain"]
textconv = astextplain
[filter "lfs"]
clean = git-lfs clean -- %f
smudge = git-lfs smudge -- %f
process = git-lfs filter-process
required = true
[credential]
helper = manager
**[core]
longpaths = true**
A simpler way, if you are using .NET 3.5, is to use XDocument
and XmlSchemaSet
validation.
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);
XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
See the MSDN documentation for more assistance.
As already mentioned that, break-statement works only with switches and loops. Here is another way to achieve what is being asked. I am reproducing https://stackoverflow.com/a/257421/1188057 as nobody else mentioned it. It's just a trick involving the do-while loop.
do {
// do something
if (error) {
break;
}
// do something else
if (error) {
break;
}
// etc..
} while (0);
Though I would prefer the use of goto-statement.
I'd use a decent HTML parser like Jsoup. It's then as easy as:
String html = Jsoup.connect("http://stackoverflow.com").get().html();
It handles GZIP and chunked responses and character encoding fully transparently. It offers more advantages as well, like HTML traversing and manipulation by CSS selectors like as jQuery can do. You only have to grab it as Document
, not as a String
.
Document document = Jsoup.connect("http://google.com").get();
You really don't want to run basic String methods or even regex on HTML to process it.
C# This is performing great:
static readonly Regex _base64RegexPattern = new Regex(BASE64_REGEX_STRING, RegexOptions.Compiled);
private const String BASE64_REGEX_STRING = @"^[a-zA-Z0-9\+/]*={0,3}$";
private static bool IsBase64(this String base64String)
{
var rs = (!string.IsNullOrEmpty(base64String) && !string.IsNullOrWhiteSpace(base64String) && base64String.Length != 0 && base64String.Length % 4 == 0 && !base64String.Contains(" ") && !base64String.Contains("\t") && !base64String.Contains("\r") && !base64String.Contains("\n")) && (base64String.Length % 4 == 0 && _base64RegexPattern.Match(base64String, 0).Success);
return rs;
}
When you decide between fixed width and fluid width you need to think in terms of your ENTIRE page. Generally, you want to pick one or the other, but not both. The examples you listed in your question are, in-fact, in the same fixed-width page. In other words, the Scaffolding page is using a fixed-width layout. The fixed grid and fluid grid on the Scaffolding page are not meant to be examples, but rather the documentation for implementing fixed and fluid width layouts.
The proper fixed width example is here. The proper fluid width example is here.
When observing the fixed width example, you should not see the content changing sizes when your browser is greater than 960px wide. This is the maximum (fixed) width of the page. Media queries in a fixed-width design will designate the minimum widths for particular styles. You will see this in action when you shrink your browser window and see the layout snap to a different size.
Conversely, the fluid-width layout will always stretch to fit your browser window, no matter how wide it gets. The media queries indicate when the styles change, but the width of containers are always a percentage of your browser window (rather than a fixed number of pixels).
The 'responsive' media queries are all ready to go. You just need to decide if you want to use a fixed width or fluid width layout for your page.
Previously, in bootstrap 2, you had to use row-fluid
inside a fluid container and row
inside a fixed container. With the introduction of bootstrap 3, row-fluid
was removed, do no longer use it.
EDIT: As per the comments, some jsFiddles for:
These fiddles are completely Bootstrap-free, based on pure CSS media queries, which makes them a good starting point, for anyone willing to craft similar solution without using Twitter Bootstrap.
Just in case you're wondering how you can set multiple different sizes in the same textview, but using an absolute size and not a relative one, you can achieve that using AbsoluteSizeSpan
instead of a RelativeSizeSpan
.
Just get the dimension in pixels of the desired text size
int textSize1 = getResources().getDimensionPixelSize(R.dimen.text_size_1);
int textSize2 = getResources().getDimensionPixelSize(R.dimen.text_size_2);
and then create a new AbsoluteSpan
based on the text
String text1 = "Hi";
String text2 = "there";
SpannableString span1 = new SpannableString(text1);
span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE);
SpannableString span2 = new SpannableString(text2);
span2.setSpan(new AbsoluteSizeSpan(textSize2), 0, text2.length(), SPAN_INCLUSIVE_INCLUSIVE);
// let's put both spans together with a separator and all
CharSequence finalText = TextUtils.concat(span1, " ", span2);
There are two ways to assign argument values to function parameters, both are used.
By Position. Positional arguments do not have keywords and are assigned first.
By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.
Note that you have the option to use positional arguments.
If you don't use positional arguments, then -- yes -- everything you wrote turns out to be a keyword argument.
When you call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want. Some of us do not make this choice and use positional arguments.
Use .toInt()
for int .toFloat()
for float and .toDouble()
for double
For those of you out there that are encountering this, use the time.RFC3339 versus the string constant of "2006-01-02T15:04:05.000Z"
. And here is the reason why:
regDate := "2007-10-09T22:50:01.23Z"
layout1 := "2006-01-02T15:04:05.000Z"
t1, err := time.Parse(layout1, regDate)
if err != nil {
fmt.Println("Static format doesn't work")
} else {
fmt.Println(t1)
}
layout2 := time.RFC3339
t2, err := time.Parse(layout2, regDate)
if err != nil {
fmt.Println("RFC format doesn't work") // You shouldn't see this at all
} else {
fmt.Println(t2)
}
This will produce the following result:
Static format doesn't work
2007-10-09 22:50:01.23 +0000 UTC
Here is the Playground Link
I do not use github plugin, but from the introduction page, it is more or less like gerrit-trigger plugin.
You can install git plugin, which can help you checkout your projects, if you want to include multi-projects in one jenkins job, just add Repository into your job.
I create the dialog using AlertDialog.Builder so I used Rodrigo's answer inside a OnShowListener.
dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
dialog.getWindow().setLayout((int)(312 * outMetrics.density), (int)(436 * outMetrics.density));
}
});
In Eclipse Ganymede (3.4.0):
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
Just wasted so much time to figure out you have to use getText(R.string.whatever) instead of getString(R.string.whatever)...
Anyways, here is how I got mine working. With multiple hyperlinks in the same text view too.
TextView termsTextView = (TextView) getActivity().findViewById(R.id.termsTextView);
termsTextView.append("By registering your account, you agree to our ");
termsTextView.append(getText(R.string.terms_of_service));
termsTextView.append(", ");
termsTextView.append(getText(R.string.fees));
termsTextView.append(", and the ");
termsTextView.append(getText(R.string.stripe_connected_account_agreement));
termsTextView.setMovementMethod(LinkMovementMethod.getInstance());
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/termsTextView"/>
string example
<string name="stripe_connected_account_agreement"><a href="https://stripe.com/connect/account-terms">Stripe Connected Account Agreement</a></string>
Here is a better way to loop over files as it handles spaces and newlines in file names:
#!/bin/bash
find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
echo "$line"
ls -l "$line"
done
You should use git pull --rebase
when
Indeed -- why not then? It's more clear, and doesn't impose a logical grouping on your commits.
Ok, I suppose it needs some clarification. In Git, as you probably know, you're encouraged to branch and merge. Your local branch, into which you pull changes, and remote branch are, actually, different branches, and git pull
is about merging them. It's reasonable, since you push not very often and usually accumulate a number of changes before they constitute a completed feature.
However, sometimes--by whatever reason--you think that it would actually be better if these two--remote and local--were one branch. Like in SVN. It is here where git pull --rebase
comes into play. You no longer merge--you actually commit on top of the remote branch. That's what it actually is about.
Whether it's dangerous or not is the question of whether you are treating local and remote branch as one inseparable thing. Sometimes it's reasonable (when your changes are small, or if you're at the beginning of a robust development, when important changes are brought in by small commits). Sometimes it's not (when you'd normally create another branch, but you were too lazy to do that). But that's a different question.
Here's a version that gets the most recent file from each subdirectory
List<string> reports = new List<string>();
DirectoryInfo directory = new DirectoryInfo(ReportsRoot);
directory.GetFiles("*.xlsx", SearchOption.AllDirectories).GroupBy(fl => fl.DirectoryName)
.ForEach(g => reports.Add(g.OrderByDescending(fi => fi.LastWriteTime).First().FullName));
The full paramiko distribution ships with a lot of good demos.
In the demos subdirectory, demo.py
and interactive.py
have full interactive TTY examples which would probably be overkill for your situation.
In your example above ssh_stdin
acts like a standard Python file object, so ssh_stdin.write
should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write
method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command
method is implemented for all the gory details.
I think this will work perfectly. I used the same:
For Android Studio:
As suggested you need to use ng-options and unfortunately I believe you need to reference the array element for a default (unless the array is an array of strings).
The JavaScript:
function AppCtrl($scope) {
$scope.operators = [
{value: 'eq', displayName: 'equals'},
{value: 'neq', displayName: 'not equal'}
]
$scope.filterCondition={
operator: $scope.operators[0]
}
}
The HTML:
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator.value}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.displayName for operator in operators">
</select>
</body>
LastLogon is the last time that the user logged into whichever domain controller you happen to have been load balanced to at the moment that you ran the GET-ADUser cmdlet, and is not replicated across the domain. You really should use LastLogonTimestamp if you want the time the last user logged in to any domain controller in your domain.
This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .
Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on
awk '{print $NF-1, $NF}' inputfile
Note: this works only if at least two columns exist. On records with one column you will get a spurious "-1 column1"
The problem is that the server process is 64 bit and the library is 32-bit and it tries to create the COM component in the same process (in-proc server). Either you recompile the server and make it 32-bit or you leave the server unchanged and make the COM component out-of-process. The easiest way to make a COM server out-of-process is to create a COM+ application - Control Panel -> Administrative Tools -> ComponentServices.
You can use the markup below, but note that if you set the textAllCaps
to true
the underline effect would be removed.
<resource>
<string name="my_string_value">I am <u>underlined</u>.</string>
</resources>
Note
Using textAllCaps with a string (login_change_settings) that contains markup; the markup will be dropped by the caps conversion
The textAllCaps text transform will end up calling toString on the CharSequence, which has the net effect of removing any markup such as . This check looks for usages of strings containing markup that also specify textAllCaps=true.
You are making sense, but you seem to misunderstand the concept of sending emails.
HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.
Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST
superglobal) and use the email sending function (mail()
).
Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.
A simple example code:
form.html:
<form method="post" action="email.php">
<input type="text" name="subject" /><br />
<textarea name="message"></textarea>
</form>
email.php:
<?php
mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>
Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).
You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.
you could probably use the gzip -t option to test the files integrity
http://linux.about.com/od/commands/l/blcmdl1_gzip.htm
To test the gzip file is not corrupt:
gunzip -t file.tar.gz
To test the tar file inside is not corrupt:
gunzip -c file.tar.gz | tar -t > /dev/null
As part of the backup you could probably just run the latter command and check the value of $? afterwards for a 0 (success) value. If either the tar or the gzip has an issue, $? will have a non zero value.
Since pandas v0.13 you can also use get_values
:
df.index.get_values()
For Swift 3, many Foundation
types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString
.
You can use the bootstrap grid system. as Yoann said
<div class="container">
<div class="row">
<form role="form">
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
</div>
<div class="clearfix"></div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Confirm Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
</div>
</form>
<div class="clearfix">
</div>
</div>
</div>
Raw arrays aren't resizable in C++.
You should be using something like a Vector class which does allow resizing..
std::vector
allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).
In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:
sc.exe config Service obj= user password= pass
Specyfying the .exe extension, PowerShell bypasses the alias lookup.
HTH
Above answer is correct but if you want to check you canOpenUrl
or not try like this.
let url = URL(string: "http://www.facebook.com")!
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
//If you want handle the completion block than
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
print("Open url : \(success)")
})
}
Note: If you do not want to handle completion you can also write like this.
UIApplication.shared.open(url, options: [:])
No need to write completionHandler
as it contains default value nil
, check apple documentation for more detail.
If your request is sent by HTTPS you will have an extra server variable named 'HTTPS'
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { //HTTPS }
Text:
This is my first android application and
I am trying to make a funny game,
It seems android is really very easy to play.
Suppose above is your text and if you are using ellipsize
's start
attribute it will seen like this
This is my first android application and
...t seems android is really very easy to play.
with end
attribute
This is my first android application and
I am trying to make a funny game,...
It is a good practice to .gitignore
at least your build products (programs, *.o, etc.).
Notice the repetition of Book
in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)
- it screams for a class type.
class Book {
int number;
String title;
String language;
int price;
}
Now you can simply have:
Book[] books = new Books[3];
If you want arrays, you can declare it as object array an insert Integer
and String
into it:
Object books[3][4]
Situation:
We have certificate.key
certificate.crt
inside /user/ssl/
We want to rename anything that starts with certificate
to certificate_OLD
We are now located inside /user
First, you do a dry run with -n
:
rename -n "s/certificate/certificate_old/" ./ssl/*
Which returns:
rename(./ssl/certificate.crt, ./ssl/certificate_OLD.crt)
rename(./ssl/certificate.key, ./ssl/certificate_OLD.key)
Your files will be unchanged this is just a test run.
Solution:
When your happy with the result of the test run it for real:
rename "s/certificate/certificate_OLD/" ./ssl/*
What it means:
`rename "s/ SOMETHING / SOMETING_ELSE " PATH/FILES
Tip:
If you are already on the path run it like this:
rename "s/certificate/certificate_OLD/" *
Or if you want to do this in any sub-directory starting with ss
do:
rename -n "s/certificat/certificate_old/" ./ss*/*
You can also do:
rename -n "s/certi*/certificate_old/" ./ss*/*
Which renames anything starting with certi
in any sub-directory starting with ss
.
The sky is the limit.
Play around with regex and ALWAYS test this BEFORE with -n
.
WATCH OUT THIS WILL EVEN RENAME FOLDER NAMES THAT MATCH.
Better cd
into the directory and do it there.
USE AT OWN RISK.
This code works for any given json file
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 20:35:35 2019
author: Ram
"""
import json
import csv
with open("file1.json") as file:
data = json.load(file)
# create the csv writer object
pt_data1 = open('pt_data1.csv', 'w')
csvwriter = csv.writer(pt_data1)
count = 0
for pt in data:
if count == 0:
header = pt.keys()
csvwriter.writerow(header)
count += 1
csvwriter.writerow(pt.values())
pt_data1.close()
You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:
echo preg_replace("/[^0-9]/","",'604-619-5135');
How about making the <div id="mainWrapperDivWithBGImage">
as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:
#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}
Then
HTML:
<div id="mainWrapperDivWithBGImage">
<div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
<div id="middle">
<div id="another_div"><img src="foo.gif" /></div>
<div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>
You may have to do position:relative; and such.
Try to use global.foo = bar
in index.android.js or index.ios.js, then you can call in other file js.
on sql 2008 this is valid
DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable
on sql server 2005, you need to do this
DECLARE @myVariable nvarchar(Max)
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.
The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.
You could try the following, however it will also load all the keys into memory
Object.keys(o).forEach(function(key) {
var val = o[key];
logic();
});
However since Object.keys
is a native method it may allow for better optimisation.
As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.
var async = {};
async.forEach = function(o, cb) {
var counter = 0,
keys = Object.keys(o),
len = keys.length;
var next = function() {
if (counter < len) cb(o[keys[counter++]], next);
};
next();
};
async.forEach(obj, function(val, next) {
// do things
setTimeout(next, 100);
});
I was having trouble with a parent service and its child using different instances. To force one instance to be used, you can alias the parent with reference to the child in your app module providers. The parent will not be able to access the child's properties, but the same instance will be used for both services. https://angular.io/guide/dependency-injection-providers#aliased-class-providers
app.module.ts
providers: [
ChildService,
// Alias ParentService w/ reference to ChildService
{ provide: ParentService, useExisting: ChildService}
]
When creating a library consisting of a component and a service, I ran into an issue where two instances would be created. One by my Angular project and one by the component inside of my library. The fix:
my-outside.component.ts
@Component({...})
export class MyOutsideComponent {
@Input() serviceInstance: MyOutsideService;
...
}
my-inside.component.ts
constructor(public myService: MyOutsideService) { }
my-inside.component.hmtl
<app-my-outside [serviceInstance]="myService"></app-my-outside>
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
Even if fileno(FILE *)
may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
If u want to set background of the list then place the image before the < Textview>
< ImageView
android:background="@drawable/image_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
and if u want to change color then put color code on above textbox like this
android:textColor="#ffffff"
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
Python3
import urllib.request
print('Beginning file download with urllib2...')
url = 'https://akm-img-a-in.tosshub.com/sites/btmt/images/stories/modi_instagram_660_020320092717.jpg'
urllib.request.urlretrieve(url, 'modiji.jpg')
Please try below stored procedure. I have already verified. I am getting proper result but without using groupby
.
CREATE DEFINER=`ks_root`@`%` PROCEDURE `first_five_record_per_id`()
BEGIN
DECLARE query_string text;
DECLARE datasource1 varchar(24);
DECLARE done INT DEFAULT 0;
DECLARE tenants varchar(50);
DECLARE cur1 CURSOR FOR SELECT rid FROM demo1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET @query_string='';
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO tenants ;
IF done THEN
LEAVE read_loop;
END IF;
SET @datasource1 = tenants;
SET @query_string = concat(@query_string,'(select * from demo where `id` = ''',@datasource1,''' order by rate desc LIMIT 5) UNION ALL ');
END LOOP;
close cur1;
SET @query_string = TRIM(TRAILING 'UNION ALL' FROM TRIM(@query_string));
select @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
The universal tool for string formatting, sprintf
:
$stamp = sprintf('%s%02s', $year, $month);
If you don't wan't to use ng-model there is ng-value
you can try.
Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/
The post is old but I found a perfect CSS for the purpose and I want to share it.
A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}
df_buy['BUY'] = df_buy['BUY'].astype('float')
df_buy['BUY'] = ['€ {:,.2f}'.format(i) for i in list(df_buy['BUY'])]
temp = open(filename,'r').read().splitlines()
Best to dump to a compressed file
mysqldump --no-create-info -u username -hhostname -p dbname | gzip > /backupsql.gz
and to restore using pv apt-get install pv
to monitor progress
pv backupsql.gz | gunzip | mysql -uusername -hhostip -p dbname
I ran into this using networkx
and bokeh
This works for me in Windows 7 (taken from here):
To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:
$ jupyter notebook --generate-config
Open the file and search for c.NotebookApp.iopub_data_rate_limit
Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000
and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000
This unforgiving default config is popping up in a lot of places. See git issues:
It looks like it might get resolved with the 5.1 release
Jupyter notebook is now on release 5.2.2
. This problem should have been resolved. Upgrade using conda or pip.
This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.
You can include dependent jars using plugin.
Add below snippet into your pom's plugins section
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
HTTPS using Jersey client has two different version if you are using java 6 ,7 and 8 then
SSLContext sc = SSLContext.getInstance("SSL");
If using java 8 then
SSLContext sc = SSLContext.getInstance("TLSv1");
System.setProperty("https.protocols", "TLSv1");
Please find working code
POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>WebserviceJersey2Spring</groupId>
<artifactId>WebserviceJersey2Spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<jersey.version>2.16</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Jersey -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<!-- Jersey + Spring -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-context</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-beans</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-web</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>jersey-server</artifactId>
<groupId>org.glassfish.jersey.core</groupId>
</exclusion>
<exclusion>
<artifactId>
jersey-container-servlet-core
</artifactId>
<groupId>org.glassfish.jersey.containers</groupId>
</exclusion>
<exclusion>
<artifactId>hk2</artifactId>
<groupId>org.glassfish.hk2</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
JAVA CLASS
package com.example.client;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.springframework.http.HttpStatus;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
public class JerseyClientGet {
public static void main(String[] args) {
String username = "username";
String password = "p@ssword";
String input = "{\"userId\":\"12345\",\"name \":\"Viquar\",\"surname\":\"Khan\",\"Email\":\"[email protected]\"}";
try {
//SSLContext sc = SSLContext.getInstance("SSL");//Java 6
SSLContext sc = SSLContext.getInstance("TLSv1");//Java 8
System.setProperty("https.protocols", "TLSv1");//Java 8
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
Client client = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder()
.credentialsForBasic(username, password).credentials(username, password).build();
client.register(feature);
//PUT request, if need uncomment it
//final Response response = client
//.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
//.request().put(Entity.entity(input, MediaType.APPLICATION_JSON), Response.class);
//GET Request
final Response response = client
.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
.request().get();
if (response.getStatus() != HttpStatus.OK.value()) { throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus()); }
String output = response.readEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
HELPER CLASS
package com.example.client;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class InsecureHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
Helper class
package com.example.client;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class InsecureTrustManager implements X509TrustManager {
/**
* {@inheritDoc}
*/
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
// Everyone is trusted!
}
/**
* {@inheritDoc}
*/
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
// Everyone is trusted!
}
/**
* {@inheritDoc}
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
Once you start running application will get Certificate error ,download certificate from browser and add into
C:\java-8\jdk1_8_0\jre\lib\security
Add into cacerts , you will get details in following links.
Few useful link to understand error
http://www.9threes.com/2015/01/restful-java-client-with-jersey-client.html
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html
I have tested following code for get and post method with SSL and basic Authentication here you can skip SSL Certificate , you can directly copy three class and add jar into java project and run.
package com.rest.client;
import java.io.IOException;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.filter.LoggingFilter;
import com.rest.dto.EarUnearmarkCollateralInput;
public class RestClientTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
//
sslRestClientGETReport();
//
sslRestClientPostEarmark();
//
sslRestClientGETRankColl();
//
} catch (KeyManagementException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//
private static WebTarget target = null;
private static String userName = "username";
private static String passWord = "password";
//
public static void sslRestClientGETReport() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/report";
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target.register(new LoggingFilter());
String responseMsg = target.request().get(String.class);
System.out.println("-------------------------------------------------------");
System.out.println(responseMsg);
System.out.println("-------------------------------------------------------");
//
}
public static void sslRestClientGET() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//Query param Search={JSON}
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb";
//
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target = target.path("employee/api/v1/informations/employee/data").queryParam("search","%7B\"name\":\"vaquar\",\"surname\":\"khan\",\"age\":\"30\",\"type\":\"admin\""%7D");
target.register(new LoggingFilter());
String responseMsg = target.request().get(String.class);
System.out.println("-------------------------------------------------------");
System.out.println(responseMsg);
System.out.println("-------------------------------------------------------");
//
}
//TOD need to fix
public static void sslRestClientPost() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//
//
Employee employee = new Employee("vaquar", "khan", "30", "E");
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/employee";
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target.register(new LoggingFilter());
//
Response response = target.request().put(Entity.json(employee));
String output = response.readEntity(String.class);
//
System.out.println("-------------------------------------------------------");
System.out.println(output);
System.out.println("-------------------------------------------------------");
}
}
Jars
repository/javax/ws/rs/javax.ws.rs-api/2.0/javax.ws.rs-api-2.0.jar"
repository/org/glassfish/jersey/core/jersey-client/2.6/jersey-client-2.6.jar"
repository/org/glassfish/jersey/core/jersey-common/2.6/jersey-common-2.6.jar"
repository/org/glassfish/hk2/hk2-api/2.2.0/hk2-api-2.2.0.jar"
repository/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.6/jersey-guava-2.6.jar"
repository/org/glassfish/hk2/hk2-locator/2.2.0/hk2-locator-2.2.0.jar"
repository/org/glassfish/hk2/hk2-utils/2.2.0/hk2-utils-2.2.0.jar"
repository/org/javassist/javassist/3.15.0-GA/javassist-3.15.0-GA.jar"
repository/org/glassfish/hk2/external/javax.inject/2.2.0/javax.inject-2.2.0.jar"
repository/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar"
genson-1.3.jar"
Here's the decoder I've been using for years...
static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const int BASE64_INPUT_SIZE = 57;
BOOL isbase64(char c)
{
return c && strchr(table, c) != NULL;
}
inline char value(char c)
{
const char *p = strchr(table, c);
if(p) {
return p-table;
} else {
return 0;
}
}
int UnBase64(unsigned char *dest, const unsigned char *src, int srclen)
{
*dest = 0;
if(*src == 0)
{
return 0;
}
unsigned char *p = dest;
do
{
char a = value(src[0]);
char b = value(src[1]);
char c = value(src[2]);
char d = value(src[3]);
*p++ = (a << 2) | (b >> 4);
*p++ = (b << 4) | (c >> 2);
*p++ = (c << 6) | d;
if(!isbase64(src[1]))
{
p -= 2;
break;
}
else if(!isbase64(src[2]))
{
p -= 2;
break;
}
else if(!isbase64(src[3]))
{
p--;
break;
}
src += 4;
while(*src && (*src == 13 || *src == 10)) src++;
}
while(srclen-= 4);
*p = 0;
return p-dest;
}
For the cut(1)
man page:
Use one, and only one of -b, -c or -f. Each LIST is made up of one range, or many ranges separated by commas. Selected input is written in the same order that it is read, and is written exactly once.
It reaches field 1 first, so that is printed, followed by field 2.
Use awk
instead:
awk '{ print $2 " " $1}' file.txt
The last day of the month you get like this, which returns 31:
DateTime.DaysInMonth(1980, 08);
You can use strcmp
:
break x:20 if strcmp(y, "hello") == 0
20
is line number, x
can be any filename and y
can be any variable.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
In my case when i tried
$ hive --service metastore
I got
MetaException(message:Version information not found in metastore. )
The necessary tables required for the metastore are missing in MySQL. Manually create the tables and restart hive metastore.
cd $HIVE_HOME/scripts/metastore/upgrade/mysql/
< Login into MySQL >
mysql> drop database IF EXISTS <metastore db name>;
mysql> create database <metastore db name>;
mysql> use <metastore db name>;
mysql> source hive-schema-2.x.x.mysql.sql;
metastore db name should match the database name mentioned in hive-site.xml files connection property tag.
hive-schema-2.x.x.mysql.sql file depends on the version available in the current directory. Try to go for the latest because it holds many old schema files also.
Now try to execute hive --service metastore
If everything goes cool, then simply start the hive from terminal.
>hive
I hope the above answer serves your need.
Simple solution for this problem is :
Click on the switch and then press CTL+1, It will change your switch to if-else block statement, and will resolve your problem
I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
ActiveRecord is clever enough to know that the parameter referred to by the ?
is a string, and so it encloses it in single quotes. You could as one post suggests use Ruby string interpolation to pad the string with the required %
symbols. However, this might expose you to SQL-injection (which is bad). I would suggest you use the SQL CONCAT()
function to prepare the string like so:
"name LIKE CONCAT('%',?,'%') OR postal_code LIKE CONCAT('%',?,'%')", search, search)
Hope to give some extra input in solving this question (or part of it).
This will work for opening an Excel
file from another. A line of code from Mr. Peter L., for the change, use the following:
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=3
This is in MSDS
. The effect is that it just updates everything (yes, everything) with no warning. This can also be checked if you record a macro.
In MSDS
, it refers this to MS EXCEL 2010
and 2013
. I'm thinking that MS EXCEL 2016
has this covered as well.
I have MS EXCEL 2013
, and have a situation pretty much the same as this topic. So I have a file (call it A
) with Workbook_Open
event code that always get's stuck on the update links prompt.
I have another file (call it B
) connected to this one, and Pivot Tables force me to open the file A
so that the data model can be loaded. Since I want to open the A
file silently in the background, I just use the line that I wrote above, with a Windows("A.xlsx").visible = false
, and, apart from a bigger loading time, I open the A
file from the B
file with no problems or warnings, and fully updated.
Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register
parameter, independently of the module used.
Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:
---
- hosts: localhost
tasks:
- shell: ls
register: shell_result
- debug:
var: shell_result.stdout_lines
Here register
tells ansible to save the response of the module into the shell_result
variable, and then we use the debug
module to print the variable out.
An example run would look like the this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"shell_result.stdout_lines": [
"play.yml"
]
}
Responses can contain multiple fields. stdout_lines
is one of the default fields you can expect from a module's response.
Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout
or stdout_lines
values, however the msg
field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.
Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v
, -vvv
and -vvvv
. For example when running the playbook with verbosity (-vvv
) you get this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
(...)
changed: [localhost] => {
"changed": true,
"cmd": "ls",
"delta": "0:00:00.007621",
"end": "2017-02-17 23:04:41.912570",
"invocation": {
"module_args": {
"_raw_params": "ls",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"rc": 0,
"start": "2017-02-17 23:04:41.904949",
"stderr": "",
"stdout": "play.retry\nplay.yml",
"stdout_lines": [
"play.retry",
"play.yml"
],
"warnings": []
}
As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines
is available, and its contents are what we expect.
To answer your main question about the jenkins_script
module, if you check its documentation, you can see that it returns the output in the output
field, so you might want to try the following:
tasks:
- jenkins_script:
script: (...)
register: jenkins_result
- debug:
var: jenkins_result.output
If you have just installed macports just run and it should work
source ~/.bash_profile
with connect(schema_name,table_name,index_name,index_column_id,column_name) as
( select s.name schema_name, t.name table_name, i.name index_name, index_column_id, cast(c.name as varchar(max)) column_name
from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
inner join sys.columns c on c.object_id = t.object_id and
ic.column_id = c.column_id
where index_column_id=1
union all
select s.name schema_name, t.name table_name, i.name index_name, ic.index_column_id, cast(connect.column_name + ',' + c.name as varchar(max)) column_name
from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
inner join sys.columns c on c.object_id = t.object_id and
ic.column_id = c.column_id join connect on
connect.index_column_id+1 = ic.index_column_id
and connect.schema_name = s.name
and connect.table_name = t.name
and connect.index_name = i.name)
select connect.schema_name,connect.table_name,connect.index_name,connect.column_name
from connect join (select schema_name,table_name,index_name,MAX(index_column_id) index_column_id
from connect group by schema_name,table_name,index_name) mx
on connect.schema_name = mx.schema_name
and connect.table_name = mx.table_name
and connect.index_name = mx.index_name
and connect.index_column_id = mx.index_column_id
order by 1,2,3
I created a function to handle this situation, thought I would share it.
getDirectDecendent(elem, selector, all){
const tempID = randomString(10) //use your randomString function here.
elem.dataset.tempid = tempID;
let returnObj;
if(all)
returnObj = elem.parentElement.querySelectorAll(`[data-tempid="${tempID}"] > ${selector}`);
else
returnObj = elem.parentElement.querySelector(`[data-tempid="${tempID}"] > ${selector}`);
elem.dataset.tempid = '';
return returnObj;
}
In essence what you are doing is generating a random-string (randomString function here is an imported npm module, but you can make your own.) then using that random string to guarantee that you get the element you are expecting in the selector. Then you are free to use the >
after that.
The reason I am not using the id attribute is that the id attribute may already be used and I don't want to override that.
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
There are a few answers already, but here is my solution:
I use opacity: 0
and visibility: hidden
. To make sure that visibility
is set before the animation, we have to set the right delays.
I use http://lesshat.com to simplify the demo, for use without this just add the browser prefixes.
(e.g. -webkit-transition-duration: 0, 200ms;
)
.fadeInOut {
.transition-duration(0, 200ms);
.transition-property(visibility, opacity);
.transition-delay(0);
&.hidden {
visibility: hidden;
.opacity(0);
.transition-duration(200ms, 0);
.transition-property(opacity, visibility);
.transition-delay(0, 200ms);
}
}
So as soon as you add the class hidden
to your element, it will fade out.
Here an approach to have count distinct over multiple columns. Let's have some data:
data = {'CLIENT_CODE':[1,1,2,1,2,2,3],
'YEAR_MONTH':[201301,201301,201301,201302,201302,201302,201302],
'PRODUCT_CODE': [100,150,220,400,50,80,100]
}
table = pd.DataFrame(data)
table
CLIENT_CODE YEAR_MONTH PRODUCT_CODE
0 1 201301 100
1 1 201301 150
2 2 201301 220
3 1 201302 400
4 2 201302 50
5 2 201302 80
6 3 201302 100
Now, list the columns of interest and use groupby in a slightly modified syntax:
columns = ['YEAR_MONTH', 'PRODUCT_CODE']
table[columns].groupby(table['CLIENT_CODE']).nunique()
We obtain:
YEAR_MONTH PRODUCT_CODE CLIENT_CODE
1 2 3
2 2 3
3 1 1
Use WSDL.EXE utility to generate a Web Service proxy from WSDL.
You'll get a long C# source file that contains a class that looks like this:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
...
}
In your client-side, Web-service-consuming code:
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
You probably want to read in more numbers, not only one. For this, you need a loop
int main()
{
int input = 0;
while(input != -1){
vector<int> V;
cout << "Enter your numbers to be evaluated: " << endl;
cin >> input;
V.push_back(input);
write_vector(V);
}
return 0;
}
Note, with this version, it is not possible to add the number -1 as it is the "end signal". Type numbers as long as you like, it will be aborted when you type -1.
You probably need to declare the code below for height:100%
to work for your divs
html, body {margin:0;padding:0;height:100%;}
fiddle: http://jsfiddle.net/5KYC3/
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
Note that you could as well plot directly from ce
(after the comma removing) using the column name :
hist(ce$Weight)
(As opposed to using hist(ce[1])
, which would lead to the same "must be numeric" error.)
This also works for a database query result.
Here is an update to the solution provided by @user235218 that allows you to specify number of milliseconds you require.
Note: The -n option is the number of retries and the -w is the timeout in milliseconds for ping. I chose the 127.255.255.254 address because it is in the loopback range and ms windows doesn’t respond to it.
I also doubt this will provide millisecond accuracy but on another note i tried it in an application using the ms script control and whilst the built in sleep function locked up the interface this method didn't.
If somebody can provide an explanation for why this method didn't lock up the interface we could make this answer more complete. Both sleep functions where run in the user thread.
Const WshHide = 0
Const WAIT_ON_RETURN = True
Sub Sleep(ByVal ms)
Dim shell 'As WScript.Shell
If Not IsNumeric(ms) Then _
Exit Sub
Set shell = CreateObject("WScript.Shell")
Call shell.Run("%COMSPEC% /c ping -n 1 -w " & ms & " 127.255.255.254 > nul", WshHide, WAIT_ON_RETURN)
End Sub
Just import Android.app,then you can use:
<br/>Application.getProcessName()<br/>
Get the current Application Process Name without context, view, or activity.
Use the in
keyword without is
.
if "x" in dog:
print "Yes!"
If you'd like to check for the non-existence of a character, use not in
:
if "x" not in dog:
print "No!"
Say, we have a column with values consisting of alphanumeric characters and underscore only. We need to trim this column off all spaces, tabs or whatever white characters.
The below example will solve the problem. The trimmed one and the original one both are being displayed for comparison.
select '/'||REGEXP_REPLACE(my_column,'[^A-Z,^0-9,^_]','')||'/' my_column,'/'||my_column||'/' from my_table;
It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.
<div id="placeholder"></div>
<script id="iframeTemplate" type="text/html">
<iframe src="...">
<!-- replace this line with alternate content -->
</iframe>
</script>
<script type="text/javascript">
var element,
html,
template;
element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;
element.innerHTML = html;
</script>
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
I was running some of the answers to see what is the fastest way for a large number. So, I found that we can convert the int to an array and it can give the correct results and it is faster.
arrayint=np.array(myInt)
newList = myList / arrayint
This a comparison of all answers above
import numpy as np
import time
import random
myList = random.sample(range(1, 100000), 10000)
myInt = 10
start_time = time.time()
arrayint=np.array(myInt)
newList = myList / arrayint
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.array(myList) / myInt
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
myList[:] = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = map(lambda x: x/myInt, myList)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [i/myInt for i in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
alert('this alert will popup twice');
}
}
);
Here's how you can avoid the double callback.
var completeCalled = false;
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
if(!completeCalled){
completeCalled = true;
alert('this alert will popup once');
}
}
}
);
I add a one-line solution if you need a datetime from both date and time parts:
select dateadd(month, (@Year -1900)*12 + @Month -1, @DayOfMonth -1) + dateadd(ss, @Hour*3600 + @Minute*60 + @Second, 0) + dateadd(ms, @Millisecond, 0)
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
Create a custom Http class by extending the Angular 2 Http
Provider and simply override the constructor
and request
method in you custom Http class. The example below adds Authorization
header in every http request.
import {Injectable} from '@angular/core';
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class HttpService extends Http {
constructor (backend: XHRBackend, options: RequestOptions) {
let token = localStorage.getItem('auth_token'); // your custom token getter function here
options.headers.set('Authorization', `Bearer ${token}`);
super(backend, options);
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('auth_token');
if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
if (!options) {
// let's make option object
options = {headers: new Headers()};
}
options.headers.set('Authorization', `Bearer ${token}`);
} else {
// we have to add the token to the url object
url.headers.set('Authorization', `Bearer ${token}`);
}
return super.request(url, options).catch(this.catchAuthError(this));
}
private catchAuthError (self: HttpService) {
// we have to pass HttpService's own instance here as `self`
return (res: Response) => {
console.log(res);
if (res.status === 401 || res.status === 403) {
// if not authenticated
console.log(res);
}
return Observable.throw(res);
};
}
}
Then configure your main app.module.ts
to provide the XHRBackend
as the ConnectionBackend
provider and the RequestOptions
to your custom Http class:
import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './services/http.service';
...
@NgModule({
imports: [..],
providers: [
{
provide: HttpService,
useFactory: (backend: XHRBackend, options: RequestOptions) => {
return new HttpService(backend, options);
},
deps: [XHRBackend, RequestOptions]
}
],
bootstrap: [ AppComponent ]
})
After that, you can now use your custom http provider in your services. For example:
import { Injectable } from '@angular/core';
import {HttpService} from './http.service';
@Injectable()
class UserService {
constructor (private http: HttpService) {}
// token will added automatically to get request header
getUser (id: number) {
return this.http.get(`/users/${id}`).map((res) => {
return res.json();
} );
}
}
Here's a comprehensive guide - http://adonespitogo.com/articles/angular-2-extending-http-provider/
You can pass arguments to a gnuplot script since version 5.0, with the flag -c
. These arguments are accessed through the variables ARG0
to ARG9
, ARG0
being the script, and ARG1
to ARG9
string variables. The number of arguments is given by ARGC
.
For example, the following script ("script.gp")
#!/usr/local/bin/gnuplot --persist
THIRD=ARG3
print "script name : ", ARG0
print "first argument : ", ARG1
print "third argument : ", THIRD
print "number of arguments: ", ARGC
can be called as:
$ gnuplot -c script.gp one two three four five
script name : script.gp
first argument : one
third argument : three
number of arguments: 5
or within gnuplot as
gnuplot> call 'script.gp' one two three four five
script name : script.gp
first argument : one
third argument : three
number of arguments: 5
In gnuplot 4.6.6 and earlier, there exists a call
mechanism with a different (now deprecated) syntax. The arguments are accessed through $#
, $0
,...,$9
. For example, the same script above looks like:
#!/usr/bin/gnuplot --persist
THIRD="$2"
print "first argument : ", "$0"
print "second argument : ", "$1"
print "third argument : ", THIRD
print "number of arguments: ", "$#"
and it is called within gnuplot as (remember, version <4.6.6)
gnuplot> call 'script4.gp' one two three four five
first argument : one
second argument : two
third argument : three
number of arguments: 5
Notice there is no variable for the script name, so $0
is the first argument, and the variables are called within quotes. There is no way to use this directly from the command line, only through tricks as the one suggested by @con-fu-se.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
I managed to get it working with that:
SSH_ASKPASS="echo \"my-pass-here\""
ssh -tt remotehost -l myusername
I have an answer that might be a bit less confusing for newbies like myself. You can just use map
within the components render method.
render () {
return (
<div>
{stations.map(station => <div key={station}> {station} </div>)}
</div>
);
}
You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.
<div id="container">
<img src="something.jpg" alt="" />
</div>
<script type="text/javascript">
(function() {
var img = document.getElementById('container').firstChild;
img.onload = function() {
if(img.height > img.width) {
img.height = '100%';
img.width = 'auto';
}
};
}());
</script>
#container {
width: 48px;
height: 48px;
}
#container img {
width: 100%;
}
If you use a JavaScript Library you might want to take advantage of it.
Try jQuery:
$("#banner-contenedor").width();
You need the actual package (the directory containing __init__.py
) stored somewhere that's in your system's PYTHONPATH. Normally, packages are distributed with a directory above the package directory, containing setup.py
(which you should use to install the package), documentation, etc. This directory is not a package. Additionally, your Python27
directory is probably not in PYTHONPATH; more likely one or more subdirectories of it are.
http://en.wikibooks.org/wiki/LaTeX/Tables#Resize_tables talks about two ways to do this.
I used:
\scalebox{0.7}{
\begin{tabular}
...
\end{tabular}
}
One of the aspects of .NET I like the most are generics. Even if you write procedural code in F#, you will still benefit from type inference. It makes writing generic code easy.
In C#, you write concrete code by default, and you have to put in some extra work to write generic code.
In F#, you write generic code by default. After spending over a year of programming in both F# and C#, I find that library code I write in F# is both more concise and more generic than the code I write in C#, and is therefore also more reusable. I miss many opportunities to write generic code in C#, probably because I'm blinded by the mandatory type annotations.
There are however situations where using C# is preferable, depending on one's taste and programming style.
In PHP, If your network under proxy. You should set the proxy URL and port
curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number
This is solves my problem
If you only want to change the font in the TEXTAREA then you only need to change the changeFont() function in the original code to:
function changeFont(_name) {
document.getElementById("mytextarea").style.fontFamily = _name;
}
Then selecting a font will change on the font only in the TEXTAREA.
git branch --merged master
lists branches merged into master
git branch --merged
lists branches merged into HEAD (i.e. tip of current branch)
git branch --no-merged
lists branches that have not been merged
By default this applies to only the local branches. The -a
flag will show both local and remote branches, and the -r
flag shows only the remote branches.
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
You should set jndi.properties. I've given below some piece of code that explain how the properties are set for activemq. Like that you can set for your application. Inside a J2EE container like JBoss no need to set these properties.
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL,"tcp://localhost:61616");
InitialContext ctx = new InitialContext(props);
// get the initial context
// InitialContext ctx = new InitialContext();
QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
// create a queue connection
QueueConnection queueConn = connFactory.createQueueConnection();
queueConn.start();
// lookup the queue object
Queue queue = (Queue) ctx.lookup("dynamicQueues/Payment_Check");
I know this is a late answer, but just giving for future reference.
If you want to ascertain whether the variable you are testing is actually explicitly an empty array, you could use something like this:
if ($variableToTest === array()) {
echo 'this is explicitly an empty array!';
}
Things have changed quite a bit since this question was asked. There are now options to let Google index your AngularJS site. The easiest option I found was to use http://prerender.io free service that will generate the crwalable pages for you and serve that to the search engines. It is supported on almost all server side web platforms. I have recently started using them and the support is excellent too.
I do not have any affiliation with them, this is coming from a happy user.
Yes its possible.
Return a RedirectToAction()
method like this:
return RedirectToAction("ActionOrViewName", "ControllerName");
use the below command to set the port number in node process while running node JS programme:
set PORT =3000 && node file_name.js
The set port can be accessed in the code as
process.env.PORT
To add to add to the previous answer, there is even a fourth way that can be used
import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)
The question is too broad to be answered definitively. Are you talking about removing all tags from a real-world HTML document, like a web page? If so, you would have to:
That's just off the top of my head--I'm sure there's more. Once you've done all that, you'll end up with words, sentences and paragraphs run together in some places, and big chunks of useless whitespace in others.
But, assuming you're working with just a fragment and you can get away with simply removing all tags, here's the regex I would use:
@"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>"
Matching single- and double-quoted strings in their own alternatives is sufficient to deal with the problem of angle brackets in attribute values. I don't see any need to explicitly match the attribute names and other stuff inside the tag, like the regex in Ryan's answer does; the first alternative handles all of that.
In case you're wondering about those (?>...)
constructs, they're atomic groups. They make the regex a little more efficient, but more importantly, they prevent runaway backtracking, which is something you should always watch out for when you mix alternation and nested quantifiers as I've done. I don't really think that would be a problem here, but I know if I don't mention it, someone else will. ;-)
This regex isn't perfect, of course, but it's probably as good as you'll ever need.
<script>
$(document).ready(function(){
$('button').attr('class','btn btn-primary');
}); </script>
After instaling the package you need to add the newtonsoft.json.dll into assemble path by runing the flowing command.
Before we can use our assembly, we have to add it to the global assembly cache (GAC). Open the Visual Studio 2008 Command Prompt again (for Vista/Windows7/etc. open it as Administrator). And execute the following command. gacutil /i d:\myMethodsForSSIS\myMethodsForSSIS\bin\Release\myMethodsForSSIS.dll
flow this link for more informATION http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html
The most efficient, but not the C++ way would be:
FILE* f = fopen(filename, "r");
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
delete[] where;
#
EDIT - 2Just tested the std::filebuf
variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.
std::ifstream file(filename, std::ios::binary);
std::streambuf* raw_buffer = file.rdbuf();
char* block = new char[size];
raw_buffer->sgetn(block, size);
delete[] block;
I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary
and rb
) modes.
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN ] IO.C_Kotti
[ OK ] IO.C_Kotti (78 ms)
[ RUN ] IO.CPP_Nikko
[ OK ] IO.CPP_Nikko (106 ms)
[ RUN ] IO.CPP_Beckmann
[ OK ] IO.CPP_Beckmann (1891 ms)
[ RUN ] IO.CPP_Neil
[ OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)
[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[ PASSED ] 4 tests.
I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.
The API includes a lot more, but start with the fetch()
method. It takes two arguments:
Simple GET:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Recreating the previous top answer, a POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Using regex:
var str = "my car is red";
var stringArray = str.split(/(\s+)/);
console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"]
\s
matches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next group starts when there is a character after the whitespace etc.
Simple example of how to use it
<?php
if(!isset($_POST) || empty($_POST)) {
?>
<form name="form1" method="post" action="">
<input type="text" name="textfield"><br />
<input type="submit" name="Submit" value="submit">
</form>
<?php
} else {
$example = file_get_contents("php://input");
echo $example; }
?>
You can use this function in your application to add keys to indexed array.
public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
$resArr = array();
foreach ($indexedArr as $item)
{
$tmpArr = array();
foreach ($item as $key=>$value)
{
$tmpArr[$keys[$key]] = $value;
}
$resArr[] = $tmpArr;
}
return $resArr;
}
Here is a simple example using Array.CopyTo. I think that it answers your question and gives an example of CopyTo usage - I am always puzzled when I need to use this function because the help is a bit unclear - the index is the position in the destination array where inserting occurs.
int[] xSrc1 = new int[3] { 0, 1, 2 };
int[] xSrc2 = new int[5] { 3, 4, 5, 6 , 7 };
int[] xAll = new int[xSrc1.Length + xSrc2.Length];
xSrc1.CopyTo(xAll, 0);
xSrc2.CopyTo(xAll, xSrc1.Length);
I guess you can't get it much simpler.
Calendar.getInstance().get(Calendar.MILLISECOND);
SELECT CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))
You need to supply the table name and column name of course.
This will be for the current session / connection http://www.postgresql.org/docs/8.3/static/functions-sequence.html
Weird, just had simmilar issue, went here http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679 downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.
The quick and less optimized way to do this is by using arrow function inside your onChangeText callback, by passing username
as your argument in your onChangeText callback.
<TextInput
ref= {(el) => { this.username = el; }}
onChangeText={(username) => this.setState({username})}
value={this.state.username}
/>
then in your _handlePress
method
_handlePress(event) {
let username=this.state.username;
}
But this has several drawback!!!
Best practice is to use a handler like handleInputChange
and bind ```this`` in the constructor.
...
constructor(props) {
super(props);
this.handleChange= this.handleChange.bind(this);
}
...
handleChange(event = {}) {
const name = event.target && event.target.name;
const value = event.target && event.target.value;
this.setState([name]: value);
}
...
render() {
...
<TextInput
name="username"
onChangeText={this.handleChange}
value={this.state.username}
/>
...
}
...
Or if you are using es6 class property shorthand which autobinds this
. But this has drawbacks, when it comes to testing and performance. Read More Here
...
handleChange= (event = {}) => {
const name = event.target && event.target.name;
const value = event.target && event.target.value;
this.setState([name]: value);
}
...
render() {
...
<TextInput
name="username"
onChangeText={this.handleChange}
value={this.state.username}
/>
...
}
...
It would be something like:
document.getElementById("username").value="Username";
document.forms[0].submit()
Or similar edit: you guys are too fast ;)
One solution is to use JavaScript to add the required CSS classes after the page is ready. For example, styling django form output with bootstrap classes (jQuery used for brevity):
<script type="text/javascript">
$(document).ready(function() {
$('#some_django_form_id').find("input[type='text'], select, textarea").each(function(index, element) {
$(element).addClass("form-control");
});
});
</script>
This avoids the ugliness of mixing styling specifics with your business logic.
See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.
On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key
With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true
//First define some delay function which is called from async function_x000D_
function __delay__(timer) {_x000D_
return new Promise(resolve => {_x000D_
timer = timer || 2000;_x000D_
setTimeout(function () {_x000D_
resolve();_x000D_
}, timer);_x000D_
});_x000D_
};_x000D_
_x000D_
//Then Declare Some Variable Global or In Scope_x000D_
//Depends on you_x000D_
var flag = false;_x000D_
_x000D_
//And define what ever you want with async fuction_x000D_
async function some() {_x000D_
while (!flag)_x000D_
await __delay__(1000);_x000D_
_x000D_
//...code here because when Variable = true this function will_x000D_
};
_x000D_
Just saying: numpy
has this too. So no need to import math
if you already did import numpy as np
:
>>> np.exp(1)
2.718281828459045
I know the accepted answer is quite old, but there is a way to control formatting with AutoGeneratColumns :
First create a function that will trigger when a column is generated :
<DataGrid x:Name="dataGrid" AutoGeneratedColumns="dataGrid_AutoGeneratedColumns" Margin="116,62,10,10"/>
Then check if the type of the column generated is a DateTime and just change its String format to "d" to remove the time part :
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if(YourColumn == typeof(DateTime))
{
e.Column.ClipboardContentBinding.StringFormat = "d";
}
}
Linq has a Max function.
If you have an IEnumerable<int>
you can call this directly, but if you require these in separate parameters you could create a function like this:
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
Then you could call it like this: max(1, 6, 2)
, it allows for an arbitrary number of parameters.