Solved similar issue by doing this:
export interface IItem extends Record<string, any> {
itemId: string;
price: number;
}
const item: IItem = { itemId: 'someId', price: 200 };
const fieldId = 'someid';
// gives you no errors and proper typing
item[fieldId]
Very sort cut and effective solution is below:-
Add the below rule in your tsconfig.json file:-
"noImplicitAny": false
Then restart your project.
Please try:
select count(*) as count,dept.DNAME
from emp
inner join dept on emp.DEPTNO = dept.DEPTNO
group by dept.DNAME
public static <T> T defaultWhenNull(@Nullable T object, @NonNull T def) {
return (object == null) ? def : object;
}
Example:
defaultWhenNull(getNullableString(), "");
Always evaluates the default value
(as oposed to cond ? nonNull() : notEvaluated()
)
This could be circumvented by passing a Callable instead of a default value, but making it somewhat more complicated and less dynamic (e.g. if performance is an issue).
By the way, you encounter the same disadvantage when using Optional.orElse()
;-)
Assuming timestamp is the index of the data frame, you can just do the following:
hours = sales.index.hour
If you want to add that to your sales data frame, just do:
import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)
Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:
hours = sales['date'].hour
Edit2:
If you want to adjust a column in your data frame you have to include dt
:
sales['datehour'] = sales['date'].dt.hour
Swift 4
Add a view outlet
@IBOutlet weak var gradientView: UIView!
Add gradient to the view
func setGradient() {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.frame = gradientView.layer.frame
gradientView.layer.insertSublayer(gradient, at: 0)
}
Well, the "-a" mail and mailx in Centos7 is "attach file" not "append header." My shortest path to a solution on Centos7 from here: stackexchange.com
Basically:
yum install mutt
mutt -e 'set content_type=text/html' -s 'My subject' [email protected] < msg.html
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
I had changed the document root for my wamp-server-installed apache web server. so using the relative url i.e. (images/img.png) didn't work. I had to use the absolute url in order for it to work i.e.
background-image:url("http://localhost/project_x/images/img.png");
Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))
If you then try predict(m)
, you get the same error as in this question.
Let's say that I want to create the following URL:
https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name
To build this with the Uri.Builder
I would do the following.
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("www.myawesomesite.com")
.appendPath("turtles")
.appendPath("types")
.appendQueryParameter("type", "1")
.appendQueryParameter("sort", "relevance")
.fragment("section-name");
String myUrl = builder.build().toString();
The answer was very funny for me and my team, and worked like a charm
REASON:
We observed that this happens only for the First View in the View Hierarchy, if this first view is a UITableView. So, all other similar UITableViews do not have this annoying section, except the first. We Tried moving the UITableView out of the first place in the view hierarchy, and everything was working as expected.
I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:
angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()
I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.
Refer django docs on static files.
In settings.py:
import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
)
Then place your js and css files static folder in your project. Not in media folder.
In views.py:
from django.shortcuts import render_to_response, RequestContext
def view_name(request):
#your stuff goes here
return render_to_response('template.html', locals(), context_instance = RequestContext(request))
In template.html:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>
In urls.py:
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
Project file structure can be found here in imgbin.
I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True
. See here: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions
In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'
. I fixed that by locally running python manage.py collectstatic
.
For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again. Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)
$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
$ch = curl_init();
curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, urlencode($url));
$response = curl_exec($ch);
curl_close($ch);
You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!
I know this answer is not directly related to this questions' issue but in some cases the "Uncaught ReferenceError: google is not defined" issue will occur if your js file is being called prior to the google maps api you're using...so DON'T DO this:
<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
Here's a neat trick:
// E.g pad("sss","00000000"); should deliver "00000sss".
public static String pad(String string, String pad) {
/*
* Add the pad to the left of string then take as many characters from the right
* that is the same length as the pad.
* This would normally mean starting my substring at
* pad.length() + string.length() - pad.length() but obviously the pad.length()'s
* cancel.
*
* 00000000sss
* ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
*/
return (pad + string).substring(string.length());
}
public static void main(String[] args) throws InterruptedException {
try {
System.out.println("Pad 'Hello' with ' ' produces: '"+pad("Hello"," ")+"'");
// Prints: Pad 'Hello' with ' ' produces: ' Hello'
} catch (Exception e) {
e.printStackTrace();
}
}
The question is already answered (BTW, really good and comprehensive answer provided by Ben), but I would like to add another element for completeness, which may be also very handy.
In the example suggested by Ben:
<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>
the following ngOptions form has been used: select as label for value in array
.
Label is an expression, which result will be the label for <option>
element. In that case you can perform certain string concatenations, in order to have more complex option labels.
Examples:
ng-options="item.ID as item.Title + ' - ' + item.ID for item in items"
gives you labels like Title - ID
ng-options="item.ID as item.Title + ' (' + item.Title.length + ')' for item in items"
gives you labels like Title (X)
, where X
is length of Title string.You can also use filters, for example,
ng-options="item.ID as item.Title + ' (' + (item.Title | uppercase) + ')' for item in items"
gives you labels like Title (TITLE)
, where Title value of Title property and TITLE is the same value but converted to uppercase characters.ng-options="item.ID as item.Title + ' (' + (item.SomeDate | date) + ')' for item in items"
gives you labels like Title (27 Sep 2015)
, if your model has a property SomeDate
Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS
Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
convertDataURIToBinary: function(dataURI) {_x000D_
var BASE64_MARKER = ';base64,',_x000D_
base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
base64 = dataURI.substring(base64Index),_x000D_
raw = window.atob(base64),_x000D_
rawLength = raw.length,_x000D_
array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
for (var i = 0; i < rawLength; i++) {_x000D_
array[i] = raw.charCodeAt(i);_x000D_
}_x000D_
return array;_x000D_
},
_x000D_
try this:
var c=document.getElementById("alpha");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='"+d+"' alt='from canvas'/>");
This shows image from canvas on new page, but if you have open popup in new tab
setting it shows about:blank
in address bar.
EDIT:- though window.open("<img src='"+ c.toDataURL('image/png') +"'/>")
does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:
window.open(c.toDataURL('image/png'));
I guess an img tag is needed as a child of an a tag, the following way:
<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
<img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>
or
<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
<img src="/path/to/OtherFile.jpg"></img>
</a>
Only using the a tag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.href and img.src tags worked for me.
From JavaScript it could be generated like this:
var data = canvas.toDataURL("image/jpeg");
var img = document.createElement('img');
img.src = data;
var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);
var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);
A Scala version based on Zaz's answer.
case class DocumentEx(document: Document) {
def toXmlString(pretty: Boolean = false):Try[String] = {
getStringFromDocument(document, pretty)
}
}
implicit def documentToDocumentEx(document: Document):DocumentEx = {
DocumentEx(document)
}
def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
try
{
val domSource= new DOMSource(doc)
val writer = new StringWriter()
val result = new StreamResult(writer)
val tf = TransformerFactory.newInstance()
val transformer = tf.newTransformer()
if (pretty)
transformer.setOutputProperty(OutputKeys.INDENT, "yes")
transformer.transform(domSource, result)
Success(writer.toString);
}
catch {
case ex: TransformerException =>
Failure(ex)
}
}
With that, you can do either doc.toXmlString()
or call the getStringFromDocument(doc)
function.
HTML:
<div class="foo">
/* whatever is required */
</div>
CSS:
.foo {
top: 0;
transition: top ease 0.5s;
}
.foo:hover{
top: -10px;
}
This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.
The requests
Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
So there is no use of having to use some separate module for decoding JSON.
You can use CSS:
p.capitalize {text-transform:capitalize;}
Based on Kamal Reddy's comment:
document.getElementById("myP").style.textTransform = "capitalize";
If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues
I like this code because it's pretty handy:
data[] <- lapply(data, function(x) type.convert(as.character(x), as.is = TRUE)) #change all vars to their best fitting data type
It is not exactly what was asked for (convert to numeric), but in many cases even more appropriate.
Emacs 28 adds a redo command (called undo-redo
).
If you want to have more typical undo/redo, the following commands can be used.
(global-set-key (kbd "C-z") 'undo-only)
(global-set-key (kbd "C-S-z") 'undo-redo)
It's valid, but rather nasty. I would suggest it's generally bad to allow fall-throughs as it can lead to some very messy spaghetti code.
It's almost certainly better to break these cases up into several switch statements or smaller functions.
[edit] @Tristopia: Your example:
Example from UCS-2 to UTF-8 conversion
r is the destination array,
wc is the input wchar_t
switch(utf8_length)
{
/* Note: code falls through cases! */
case 3: r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800;
case 2: r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0;
case 1: r[0] = wc;
}
would be clearer as to it's intention (I think) if it were written like this:
if( utf8_length >= 1 )
{
r[0] = wc;
if( utf8_length >= 2 )
{
r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0;
if( utf8_length == 3 )
{
r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800;
}
}
}
[edit2] @Tristopia: Your second example is probably the cleanest example of a good use for follow-through:
for(i=0; s[i]; i++)
{
switch(s[i])
{
case '"':
case '\'':
case '\\':
d[dlen++] = '\\';
/* fall through */
default:
d[dlen++] = s[i];
}
}
..but personally I would split the comment recognition into it's own function:
bool isComment(char charInQuestion)
{
bool charIsComment = false;
switch(charInQuestion)
{
case '"':
case '\'':
case '\\':
charIsComment = true;
default:
charIsComment = false;
}
return charIsComment;
}
for(i=0; s[i]; i++)
{
if( isComment(s[i]) )
{
d[dlen++] = '\\';
}
d[dlen++] = s[i];
}
Did you try to set timezone by func: http://pl.php.net/manual/en/function.date-default-timezone-set.php
This PHP function do the Job for you an give back an array:
function time_zonelist(){
$return = array();
$timezone_identifiers_list = timezone_identifiers_list();
foreach($timezone_identifiers_list as $timezone_identifier){
$date_time_zone = new DateTimeZone($timezone_identifier);
$date_time = new DateTime('now', $date_time_zone);
$hours = floor($date_time_zone->getOffset($date_time) / 3600);
$mins = floor(($date_time_zone->getOffset($date_time) - ($hours*3600)) / 60);
$hours = 'GMT' . ($hours < 0 ? $hours : '+'.$hours);
$mins = ($mins > 0 ? $mins : '0'.$mins);
$text = str_replace("_"," ",$timezone_identifier);
$return[$timezone_identifier] = $text.' ('.$hours.':'.$mins.')';
}
return $return;
}
This PHP function give back an array of all existing Timezones including Offset:
Use it e.g. like this:
print_r(time_zonelist());
Try
//book[title/@lang = 'it']
This reads:
book
elements
title
lang
"it"
You may find this helpful — it's an article entitled "XPath in Five Paragraphs" by Ronald Bourret.
But in all honesty, //book[title[@lang='it']]
and the above should be equivalent, unless your XPath engine has "issues." So it could be something in the code or sample XML that you're not showing us -- for example, your sample is an XML fragment. Could it be that the root element has a namespace, and you aren't counting for that in your query? And you only told us that it didn't work, but you didn't tell us what results you did get.
if mystring = USCAGoleta9311734.5021-120.1287855805
print substr(mystring,0,2)
would print US
where 0 is the start position and 2 is how meny chars to read
I've found the easiest way to centre and left-align text inside a container is the following:
HTML:
<div>
<p>Some interesting text.</p>
</div>
CSS:
P {
width: 50%; //or whatever looks best
margin: auto; //top and bottom margin can be added for aesthetic effect
}
Hope this is what you were looking for as it took me quite a bit of searching just to figure out this pretty basic solution.
If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.
Use a CSS method to force wrap a string that has no white-spaces. Three methods:
1) Use the CSS white-space property. To cover browser inconsistencies, you have to declare it several ways. So just put your looooong string into some block level element (e.g., div, pre, p) and give that element the following css:
some_block_level_tag {
white-space: pre; /* CSS 2.0 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3.0 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP Printers */
word-wrap: break-word; /* IE 5+ */
}
2) use the force-wrap mixin from Compass.
3) I was just looking into this as well and I think might also work (but I need to test browser support more completely):
.break-me {
word-wrap: break-word;
overflow-wrap: break-word;
}
Reference: wrapping content
I had the same problem as the original poster but the quoted answer did not solve the problem for me. The query still ran really slow from a stored procedure.
I found another answer here "Parameter Sniffing", Thanks Omnibuzz. Boils down to using "local Variables" in your stored procedure queries, but read the original for more understanding, it's a great write up. e.g.
Slow way:
CREATE PROCEDURE GetOrderForCustomers(@CustID varchar(20))
AS
BEGIN
SELECT *
FROM orders
WHERE customerid = @CustID
END
Fast way:
CREATE PROCEDURE GetOrderForCustomersWithoutPS(@CustID varchar(20))
AS
BEGIN
DECLARE @LocCustID varchar(20)
SET @LocCustID = @CustID
SELECT *
FROM orders
WHERE customerid = @LocCustID
END
Hope this helps somebody else, doing this reduced my execution time from 5+ minutes to about 6-7 seconds.
The MDN Show for General Macintosh business topics.
cocoaFusion and coreInt for in-depth Cocoa topics.
Then all you have to do is subtract that from total document height
jQuery(function () {
var documentHeight = jQuery(document).height();
var element = jQuery('#you-element');
var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
alert(distanceFromBottom)
});
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?
Intl.PluralRules
, the standard method.I would just like to drop the canonical way of doing this in here, as nobody seems to know it.
If you want your code to be
- this is the way to go.
const english_ordinal_rules = new Intl.PluralRules("en", {type: "ordinal"});
const suffixes = {
one: "st",
two: "nd",
few: "rd",
other: "th"
};
function ordinal(number) {
const suffix = suffixes[english_ordinal_rules.select(number)];
return (number + suffix);
}
const test = Array(201)
.fill()
.map((_, index) => index - 100)
.map(ordinal)
.join(" ");
console.log(test);
_x000D_
I advocate use of the "rel" attribute. The XHTML validates, the attribute itself is rarely used, and the data is efficiently retrieved.
You can configure a proxy with conda by adding it to the .condarc
, like
proxy_servers:
http: http://user:[email protected]:8080
https: https://user:[email protected]:8080
or set the HTTP_PROXY
and HTTPS_PROXY
environment variables. Note that in your case you need to add the scheme to the proxy url, like https://proxy-us.bla.com:123.
See http://conda.pydata.org/docs/config.html#configure-conda-for-use-behind-a-proxy-server.
You could simply pass an array of values for the value in a regular HashMap, thus simulating duplicate keys, and it would be up to you to decide what data to use.
You may also just use a MultiMap, although I do not like the idea of duplicate keys myself.
I just had this idea, so maybe it's shortsighted, but it seems to work well and might be the most consistent between your CSS and JS.
In your CSS you set the max-width value for html based on the @media screen value:
@media screen and (max-width: 480px) and (orientation: portrait){
html {
max-width: 480px;
}
... more styles for max-width 480px screens go here
}
Then, using JS (probably via a framework like JQuery), you would just check the max-width value of the html tag:
maxwidth = $('html').css('max-width');
Now you can use this value to make conditional changes:
If (maxwidth == '480px') { do something }
If putting the max-width value on the html tag seems scary, then maybe you can put on a different tag, one that is only used for this purpose. For my purpose the html tag works fine and doesn't affect my markup.
Useful if you are using Sass, etc: To return a more abstract value, such as breakpoint name, instead of px value you can do something like:
<div id="breakpoint-indicator" />
$('#breakpoint-indicator').css('content');
), which returns "large", or "mobile", etc depending on what the content property is set to by the media query.Now you can act on same breakpoint names as you do in sass, e.g. sass: @include respond-to(xs)
, and js if ($breakpoint = "xs) {}
.
What I especially like about this is that I can define my breakpoint names all in css and in one place (likely a variables scss document) and my js can act on them independently.
Just set minDate: 0
Here is my script:
$("#valid_from")
.datepicker({
minDate: 0,
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
Path changes appear to be persistent if you set the SHELL variable in your makefile first:
SHELL := /bin/bash
PATH := bin:$(PATH)
test all:
x
I don't know if this is desired behavior or not.
Like this?
ALTER TABLE `tablename` ADD `new_col_name` INT NOT NULL DEFAULT 0;
The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.
The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.
Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.
All answers I've encountered here only check if the element is positioned inside the current viewport. But that doesn't mean that it is visible.
What if the given element is inside a div with overflowing content, and it is scrolled out of view?
To solve that, you'd have to check if the element is contained by all parents.
My solution does exactly that:
It also allows you to specify how much of the element has to be visible.
Element.prototype.isVisible = function(percentX, percentY){
var tolerance = 0.01; //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals
if(percentX == null){
percentX = 100;
}
if(percentY == null){
percentY = 100;
}
var elementRect = this.getBoundingClientRect();
var parentRects = [];
var element = this;
while(element.parentElement != null){
parentRects.push(element.parentElement.getBoundingClientRect());
element = element.parentElement;
}
var visibleInAllParents = parentRects.every(function(parentRect){
var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);
var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);
var visiblePercentageX = visiblePixelX / elementRect.width * 100;
var visiblePercentageY = visiblePixelY / elementRect.height * 100;
return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;
});
return visibleInAllParents;
};
This solution ignored the fact that elements may not be visible due to other facts, like opacity: 0
.
I have tested this solution in Chrome and Internet Explorer 11.
It's not a bug in ARel, it's a bug in your logic.
What you want here is:
Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))
Heres is another option using CSS variables . This requires a css hover definition ahead of time so I guess its not pure inline, but is very little code and flexible.
css (setup a hover state) :
.p:hover:{
color:var(--hover-color) !important,
opacity:var(--hover-opacity)
}
react:
<p style={{'color':'red','--hover-color':'blue','--hover-opacity':0.5}}>
To check all versions of Internet Explorer you can go to codecpack.nl and install all versions of Internet Explorer, that is, IE collection.
Or you can use www.multibrowserviewer.com. It can check in 45 browsers and 3 OSes.
I came across this fairly recent (compared to the age of the question) TechNet article that includes some of the best techniques I could find on the topic:
WPF: Programmatically Selecting and Focusing a Row or Cell in a DataGrid
It includes details that should cover most requirements. It is important to remember that if you specify custom templates for the DataGridRow for some rows that these won't have DataGridCells inside and then the normal selection mechanisms of the grid doesn't work.
You'll need to be more specific on what datasource you've given the grid to answer the first part of your question, as the others have stated.
There is a library on Github for tab support in your textareas by wjbryant: Tab Override
This is how it works:
// get all the textarea elements on the page
var textareas = document.getElementsByTagName('textarea');
// enable Tab Override for all textareas
tabOverride.set(textareas);
If I have one thing that I love to share with respect to CSS, it's MY FAVE WAY OF CENTERING THINGS ALONG BOTH AXES!!!
Advantages of this method:
I always do this by using 2 classes: One to specify the parent element, whose content will be centered (.centered-wrapper
), and the 2nd one to specify which child of the parent is centered (.centered-content
). This 2nd class is useful in the case where the parent has multiple children, but only 1 needs to be centered).
In this case, body
will be the .centered-wrapper
, and an inner div
will be .centered-content
.
<html>
<head>...</head>
<body class="centered-wrapper">
<div class="centered-content">...</div>
</body>
</html>
The idea for centering will now be to make .centered-content
an inline-block
. This will easily facilitate horizontal centering, through text-align: center;
, and also allows for vertical centering as you shall see.
.centered-wrapper {
position: relative;
text-align: center;
}
.centered-wrapper:before {
content: "";
position: relative;
display: inline-block;
width: 0; height: 100%;
vertical-align: middle;
}
.centered-content {
display: inline-block;
vertical-align: middle;
}
This gives you 2 really reusable classes for centering any child inside of any parent! Just add the .centered-wrapper
and .centered-content
classes.
So, what's up with that :before
element? It facilitates vertical-align: middle;
and is necessary because vertical alignment isn't relative to the height of the parent - vertical alignment is relative to the height of the tallest sibling!!!. Therefore, by ensuring that there is a sibling whose height is the parent's height (100% height, 0 width to make it invisible), we know that vertical alignment will be with respect to the parent's height.
One last thing: You need to ensure that your html
and body
tags are the size of the window so that centering to them is the same as centering to the browser!
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
Find the below-mentioned code, it might be helpful for you.
val stringDate = spark.sparkContext.parallelize(Seq("12/16/2019")).toDF("StringDate")
val dateCoversion = stringDate.withColumn("dateColumn", to_date(unix_timestamp($"StringDate", "dd/mm/yyyy").cast("Timestamp")))
dateCoversion.show(false)
+----------+----------+
|StringDate|dateColumn|
+----------+----------+
|12/16/2019|2019-01-12|
+----------+----------+
Using these magic methods (__enter__
, __exit__
) allows you to implement objects which can be used easily with the with
statement.
The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a try-finally
block). Some more explanation here.
A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
As explained above, use this object with the with
statement (you may need to do from __future__ import with_statement
at the top of the file if you're on Python 2.5).
with DatabaseConnection() as mydbconn:
# do stuff
PEP343 -- The 'with' statement' has a nice writeup as well.
The singular form dtype
is used to check the data type for a single column. And the plural form dtypes
is for data frame which returns data types for all columns. Essentially:
For a single column:
dataframe.column.dtype
For all columns:
dataframe.dtypes
Example:
import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})
df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')
df.dtypes
#A int64
#B bool
#C object
#dtype: object
According to MSDN:
An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.
So basically, the Thread
object does not necessarily correspond to an OS thread - which is why it doesn't have the native ID exposed.
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
Postgresql does not have bare variables, you could use a temporary table. variables are only available in code blocks or as a user-interface feature.
If you need a bare variable you could use a temporary table:
CREATE TEMP TABLE list AS VALUES ('foobar');
SELECT dbo.PubLists.*
FROM dbo.PubLists,list
WHERE Name = list.column1;
I had this problem and like Anderson Imes said it had to do with app settings. My problem was the scope of one of my settings was set to "User" when it should have been "Application".
The return type of a procedure is int.
You can also return result sets (as your code currently does) (okay, you can also send messages, which are strings)
Those are the only "returns" you can make. Whilst you can add table-valued parameters to a procedure (see BOL), they're input only.
Edit:
(Or as another poster mentioned, you could also use a Table Valued Function, rather than a procedure)
Try this one:
var lastfoucsin;
$('.txtclassname').click(function(e)
{
lastfoucsin=$(this);
//the virtual keyboard appears automatically
//Do your stuff;
});
//to check ipad virtual keyboard appearance.
//First check last focus class and close the virtual keyboard.In second click it closes the wrapper & lable
$(".wrapperclass").click(function(e)
{
if(lastfoucsin.hasClass('txtclassname'))
{
lastfoucsin=$(this);//to avoid error
return;
}
//Do your stuff
$(this).css('display','none');
});`enter code here`
Destination Host Unreachable
This message indicates one of two problems: either the local system has no route to the desired destination, or a remote router reports that it has no route to the destination.
If the message is simply "Destination Host Unreachable," then there is no route from the local system, and the packets to be sent were never put on the wire.
If the message is "Reply From < IP address >: Destination Host Unreachable," then the routing problem occurred at a remote router, whose address is indicated by the "< IP address >" field.
Request Timed Out
This message indicates that no Echo Reply messages were received within the default time of 1 second. This can be due to many different causes; the most common include network congestion, failure of the ARP request, packet filtering, routing error, or a silent discard.
For more info Refer: http://technet.microsoft.com/en-us/library/cc940095.aspx
Ever heard of substr()
?
For a starter :
$("#test").text($("#test").text().substr(0,1).toUpperCase()+$("#test").text().substr(1,$("#test").text().length));
[Update:]
Thanks to @FelixKling for the tip:
$("#test").text(function(i, text) {
return text.substr(0,1).toUpperCase() + text.substr(1);
});
An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.
It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.
Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.
Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.
For IE: window.close();
and self.close();
should work fine.
If you want just open the IE browser and type
javascript:self.close()
and hit enter, it should ask you for a prompt.
Note: this method doesn't work for Chrome or Firefox.
I used this code:
public class MainActivity extends Activity
{
.
.
.
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.
.
.
}
@Override
protected void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onPause()
{
super.onPause();
unregisterReceiver(broadcastReceiver);
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION))
{
if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false))
{
// wifi is enabled
}
else
{
// wifi is disabled
}
}
}
};
}
jQuery.ajax({
type: 'GET',
url: "../struktur2/load.php",
async: false,
contentType: "application/json",
dataType: 'json',
success: function(json) {
items = json;
},
error: function(e) {
console.log("jQuery error message = "+e.message);
}
});
There are helper classes in bootstrap 3 with contextual colors please use these classes in html attributes.
<p class="text-muted">...</p>
<p class="text-primary">...</p>
<p class="text-success">...</p>
<p class="text-info">...</p>
<p class="text-warning">...</p>
<p class="text-danger">...</p>
Reference: http://getbootstrap.com/css/#type
I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.
Your code doesn't work (parse) because you have an extra )
at the end that causes a Parse Error. Count, you have 2 (
and 3 )
. It would work fine if you fix that, but strtotime()
returns a timestamp, so to get a human readable time use date()
.
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the )
is the main issue here.
cls
$exactadminfile = "C:\temp\files\admin" #First folder to check the file
$userfile = "C:\temp\files\user" #Second folder to check the file
$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
foreach ($filename in $filenames) {
if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
Write-Warning "$filename absent from both locations"
} else {
Write-Host " $filename File is there in one or both Locations" #if file exists there at both locations or at least in one location
}
}
http://localhost:80
type above line in your browser you realize IIS installed or not
You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.
The data and the error are available directly via these callbacks.
The library is called angular-extended-http-client.
angular-extended-http-client library on GitHub
angular-extended-http-client library on NPM
Very easy to use.
In the traditional approach you return Observable<HttpResponse<
T>
> from Service API. This is tied to HttpResponse.
With this approach you have to use .subscribe(x => ...) in the rest of your code.
This creates a tight coupling between the http layer and the rest of your code.
You only deal with your Models in these strongly-typed callbacks.
Hence, The rest of your code only knows about your Models.
The strongly-typed callbacks are
Success:
T
>T
>Failure:
TError
>TError
>import { HttpClientExtModule } from 'angular-extended-http-client';
and in the @NgModule imports
imports: [
.
.
.
HttpClientExtModule
],
export class SearchModel {
code: string;
}
//Normal response returned by the API.
export class RacingResponse {
result: RacingItem[];
}
//Custom exception thrown by the API.
export class APIException {
className: string;
}
In your Service, you just create params with these callback types.
Then, pass them on to the HttpClientExt's get method.
import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.
@Injectable()
export class RacingService {
//Inject HttpClientExt component.
constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {
}
//Declare params of type IObservable<T> and IObservableError<TError>.
//These are the success and failure callbacks.
//The success callback will return the response objects returned by the underlying HttpClient call.
//The failure callback will return the error objects returned by the underlying HttpClient call.
searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
let url = this.config.apiEndpoint;
this.client.post<SearchModel, RacingResponse>(url, model,
ResponseType.IObservable, success,
ErrorType.IObservableError, failure);
}
}
In your Component, your Service is injected and the searchRaceInfo API called as shown below.
search() {
this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
error => this.errorMsg = error.className);
}
Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.
prevArrow/nextArrow
Type:
string (html|jQuery selector) | object (DOM node|jQuery object)
Some example code
$(document).ready(function(){
$('.slick-carousel-1').slick({
// @type {string} html
nextArrow: '<button class="any-class-name-you-want-next">Next</button>',
prevArrow: '<button class="any-class-name-you-want-previous">Previous</button>'
});
$('.slick-carousel-2').slick({
// @type {string} jQuery Selector
nextArrow: '.next',
prevArrow: '.previous'
});
$('.slick-carousel-3').slick({
// @type {object} DOM node
nextArrow: document.getElementById('slick-next'),
prevArrow: document.getElementById('slick-previous')
});
$('.slick-carousel-4').slick({
// @type {object} jQuery Object
nextArrow: $('.example-4 .next'),
prevArrow: $('.example-4 .previous')
});
});
A little note on styling
Once Slick knows about your new buttons, you can style them to your heart's content; looking at the above example, you could target them based on class
name, id
name or even element
.
You can have more than one statement when still return:
[]() -> your_type {return (
your_statement,
even_more_statement = just_add_comma,
return_value);}
import java.io.IOException;
import java.lang.ProcessBuilder;
public class handlingexe {
public static void main(String[] args) throws IOException {
ProcessBuilder p = new ProcessBuilder();
System.out.println("Started EXE");
p.command("C:\\Users\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
p.start();
System.out.println("Started EXE");
}
}
I think, the differences between ArrayList
and List<T>
are:
List<T>
, where T is value-type is faster than ArrayList
. This is
because List<T>
avoids boxing/unboxing (where T is value-type).ArrayList
used just for backward
compatibility. (is not a real difference, but i think it is
important note).ArrayList
then List<T>
ArrayList
has IsSynchronized
property. So, It is easy
to create and use syncronised ArrayList
. I didin't found IsSynchronized
property for List<T>
. Also Keep in mind this type of synchronization is relatively inefficient, msdn):
var arraylist = new ArrayList();
var arrayListSyncronized = ArrayList.Synchronized(arraylist
Console.WriteLine($"syncronized {arraylist.IsSynchronized}");
Console.WriteLine($"syncronized {arrayListSyncronized.IsSynchronized}");
var list = new List<object>();
var listSyncronized = ArrayList.Synchronized(list);
Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
ArrayList
has ArrayList.SyncRoot
property which can be used for syncronisation (msdn). List<T>
hasn't SyncRoot
property, so in
the following construction you need to use some object if you use List<T>
:
ArrayList myCollection = new ArrayList();
lock(myCollection.SyncRoot) // ofcourse you can use another object for this goal
{
foreach (object item in myCollection)
{
// ...
}
}
I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.
Beside of the inbuilt 'reindent' function, you can also install other plugins, such as SublimeAStyleFormatter and CodeFormatter. These plugins are better for their specify language.
Since some years some devices support <input type="date">
but others don't, so one needs to be careful. Here are some observations from 2012, which still might be valid today:
One can detect if type="date"
is supported by setting that attribute and then reading back its value. Browsers/devices that don't support it will ignore setting the type to date
and return text
when reading back that attribute. Alternatively, Modernizr can be used for detection. Beware that it's not enough to check for some Android version; like the Samsung Galaxy S2 on Android 4.0.3 does support type="date"
, but the Google/Samsung Nexus S on the more recent Android 4.0.4 does not.
When presetting the date for the native date picker, be sure to use a format the device recognizes. When not doing that, devices might silently reject it, leaving one with an empty input field when trying to show an existing value. Like using the date picker on a Galaxy S2 running Android 4.0.3 might itself set the <input>
to 2012-6-1
for June 1st. However, when setting the value from JavaScript, it needs leading zeroes: 2012-06-01
.
When using things like Cordova (PhoneGap) to display the native date picker on devices that don't support type="date"
:
Be sure to properly detect built-in support. Like in 2012 on the Galaxy S2 running Android 4.0.3, erroneously also using the Cordova Android plugin would result in showing the date picker twice in a row: once again after clicking "set" in its first occurrence.
When there's multiple inputs on the same page, some devices show "previous" and "next" to get into another form field. On iOS 4, this does not trigger the onclick
handler and hence gives the user a regular input. Using onfocus
to trigger the plugin seemed to work better.
On iOS 4, using onclick
or onfocus
to trigger the 2012 iOS plugin first made the regular keyboard show, after which the date picker was placed on top of that. Next, after using the date picker, one still needed to close the regular keyboard. Using $(this).blur()
to remove focus before the date picker was shown helped for iOS 4 and did not affect other devices I tested. But it introduced some quick flashing of the keyboard on iOS, and things could be even more confusing on first usage as then the date picker was slower. One could fully disable the regular keyboard by making the input readonly
if one were using the plugin, but that disabled the "previous" and "next" buttons when typing in other inputs on the same screen. It also seems the iOS 4 plugin did not make the native date picker show "cancel" or "clear".
On an iOS 4 iPad (simulator), in 2012 the Cordova plugin did not seem to render correctly, basically not giving the user any option to enter or change a date. (Maybe iOS 4 doesn't render its native date picker nicely on top of a web view, or maybe my web view's CSS styling has some effect, and surely this might be different on a real device: please comment or edit!)
Though, again in 2012, the Android date picker plugin tried to use the same JavaScript API as the iOS plugin, and its example used allowOldDates
, the Android version actually did not support that. Also, it returned the new date as 2012/7/2
while the iOS version returned Mon Jul 02 2012 00:00:00 GMT+0200 (CEST)
.
Even when <input type="date">
is supported, things might look messy:
iOS 5 nicely displays 2012-06-01
in a localized format, like 1 Jun. 2012
or June 1, 2012
(and even updates that immediately while still operating the date picker). However, the Galaxy S2 running Android 4.0.3 shows the ugly 2012-6-1
or 2012-06-01
, no matter which locale is used.
iOS 5 on an iPad (simulator) does not hide the keyboard when that is already visible when touching the date input, or when using "previous" or "next" in another input. It then simultaneously shows the date picker below the input and the keyboard at the bottom, and seems to allow any input from both. However, though it does change the visible value, the keyboard input is actually ignored. (Shown when reading back the value, or when invoking the date picker again.) When the keyboard was not yet shown, then touching the date input only shows the date picker, not the keyboard. (This might be different on a real device, please comment or edit!)
Devices might show a cursor in the input field, and a long press might trigger the clipboard options, possibly showing the regular keyboard too. When clicking, some devices might even show the regular keyboard for a split second, before changing to show the date picker.
A bit shorter answer since PHP >= 5.3.0:
$csvFile = file('../somefile.csv');
$data = [];
foreach ($csvFile as $line) {
$data[] = str_getcsv($line);
}
Well I fond this post because I got a similar error. So I added the top line like in your controller respond_to :html, :json
then I got a different error(see below)
The controller-level respond_to' feature has been extracted to the
responders` gem. Add it to your Gemfile to continue using this feature: gem 'responders', '~> 2.0' Consult the Rails upgrade guide for details.
But that had nothing to do with it.
There is no difference, except that Pragma
is only defined as applicable to the requests by the client, whereas Cache-Control
may be used by both the requests of the clients and the replies of the servers.
So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:
HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.
Note: because the meaning of "Pragma: no-cache as a response header field is not actually specified, it does not provide a reliable replacement for "Cache-Control: no-cache" in a response
The way I would read the above:
if you're writing a client and need no-cache
:
Pragma: no-cache
in your requests, since you may not know if Cache-Control
is supported by the server;Cache-Control
if you're writing a server:
Cache-Control
; if not found, check for Pragma: no-cache
, and execute the Cache-Control: no-cache
logic;Cache-Control
.Of course, reality might be different from what's written or implied in the RFC!
Do the following changes in servlet-context.xml
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.enable_lazy_load_no_trans">true</beans:prop>
</beans:props>
</beans:property>
I had a similar-looking problem after adding a directory tree which contained .svn directories (because it was an svn:external in its source environment): svn status told me "?", but when trying to add it, it was "already under version control".
Since no other versioned directories were present, I did
find . -mindepth 2 -name '.svn' -exec rm -rf '{}' \;
to remove the wrong .svn directories; after doing this, I was able to add the new directory.
Note:
Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.
I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home
There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.
You can also use the hasFocus() method:
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (Field2.hasfocus()){
Field1.setText("");
}
}
Tested this for a college assignment I was working on to convert temperature scales as the user typed them in. Worked perfectly, and it's way simpler.
python 2.7
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
cur = conn.cursor()
n = cur.execute('select * from actor')
c = cur.fetchall()
for i in c:
print i[1]
andorid-support-v4.jar is an external jar file that you have to import into your project.
This is how you do it in Android Studio:
Go to File -> Project Structure
Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"
Select the support library "support-v4 (com.android.support:support-v4:23.0.1)"
Now to go your "build.gradle" file in your app and make sure the android support library has been added to your dependencies. Alternatively, you could've also just typed compile 'com.android.support:support-v4:23.0.1'
directly into your dependencies{}
instead of doing it through the GUI.
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
Serializable
transient
I have not used the classes from the Java NIO package, but it seems they might be of some help here. Specifically, java.nio.channels.Channels and java.nio.channels.InterruptibleChannel.
You've got the syntax right:
WITH AuthorRating(AuthorName, AuthorRating) AS
SELECT aname AS AuthorName,
AVG(quantity) AS AuthorRating
FROM Book
GROUP By Book.aname
However, as others have mentioned, MySQL does not support this command. WITH was added in SQL:1999; the newest version of the SQL standard is SQL:2008. You can find some more information about databases that support SQL:1999's various features on Wikipedia.
MySQL has traditionally lagged a bit in support for the SQL standard, whereas commercial databases like Oracle, SQL Server (recently), and DB2 have followed them a bit more closely. PostgreSQL is typically pretty standards compliant as well.
You may want to look at MySQL's roadmap; I'm not completely sure when this feature might be supported, but it's great for creating readable roll-up queries.
There is one slight difference: return code.
The thing is that unless shopt -o pipefail
is set the return code of the piped command will be return code of the last one. And uniq
always returns zero (success). Try examining exit code, and you'll see something like this (pipefail
is not set here):
pavel@lonely ~ $ sort -u file_that_doesnt_exist ; echo $?
sort: open failed: file_that_doesnt_exist: No such file or directory
2
pavel@lonely ~ $ sort file_that_doesnt_exist | uniq ; echo $?
sort: open failed: file_that_doesnt_exist: No such file or directory
0
Other than this, the commands are equivalent.
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab
key). Read MDN Web Docs for full reference.
$( "#division" ).keydown(function(evt) {
evt = evt || window.event;
console.log("keydown: " + evt.keyCode);
});
_x000D_
#division {
width: 90px;
height: 30px;
background: lightgrey;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="division" tabindex="0"></div>
_x000D_
var el = document.getElementById("division");
el.onkeydown = function(evt) {
evt = evt || window.event;
console.log("keydown: " + evt.keyCode);
};
_x000D_
#division {
width: 90px;
height: 30px;
background: lightgrey;
}
_x000D_
<div id="division" tabindex="0"></div>
_x000D_
First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties
. In a WAR, WEB-INF/classes
is a classpath entry, so it will work just fine.
After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:
<context:property-placeholder location="classpath:config/properties/database.properties"/>
Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties
:
<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
There's usually not any reason to define them separately, though.
you can set the default value with empty_data
$builder->add('myField', 'number', ['empty_data' => 'Default value'])
You can use the following function to extract data
CREATE FUNCTION [dbo].[SplitString]
(
@RowData NVARCHAR(MAX),
@Delimeter NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE
(
ID INT IDENTITY(1,1),
Data NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @Iterator INT
SET @Iterator = 1
DECLARE @FoundIndex INT
SET @FoundIndex = CHARINDEX(@Delimeter,@RowData)
WHILE (@FoundIndex>0)
BEGIN
INSERT INTO @RtnValue (data)
SELECT
Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))
SET @RowData = SUBSTRING(@RowData,
@FoundIndex + DATALENGTH(@Delimeter) / 2,
LEN(@RowData))
SET @Iterator = @Iterator + 1
SET @FoundIndex = CHARINDEX(@Delimeter, @RowData)
END
INSERT INTO @RtnValue (Data)
SELECT Data = LTRIM(RTRIM(@RowData))
RETURN
END
koding.com has a free VM running Ubuntu. The specs are pretty good, 1 gig memory for example. They have a terminal online you can access through their website, or use SSH. The VM will go to sleep approximately 20 minutes after you log out. The reason is to discourage users from running live production code on the VM. The VM resides behind a proxy. Running web servers that only speak HTTP (port 80) should work just fine, but I think you'll get into a lot of trouble whenever you want to work directly with other ports. Many mind-like alternatives offer similar setups. Good luck!
I had the same idea as you but given all restrictions everybody keep imposing everywhere I feel that I must go out and pay for a VPS.
This will test if strings are made up of some combination or digits, the dollar sign, and a commas. Is that what you're looking for?
import re s1 = 'Testing string' s2 = '1234,12345$' regex = re.compile('[0-9,$]+$') if ( regex.match(s1) ): print "s1 matched" else: print "s1 didn't match" if ( regex.match(s2) ): print "s2 matched" else: print "s2 didn't match"
I used the logic in the replies by rampion and schnaader. I will summarise how I confirmed the results. I changed the numbers to binary and then used the XOR-operation. Alternatively, you can use the Hexadecimal tables: Click here!
For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…
The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.
The problem with s += "stuff"
is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff"
is extremely costly.
If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:
StringBuilder sb = new StringBuilder(5000);
for (; ; )
{
sb.Append("stuff");
}
StringBuilder
will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.
I faced this issue because my selector was depend on id
meanwhile I did not set id for my element
my selector
was
$("#EmployeeName")
but my HTML element
<input type="text" name="EmployeeName">
so just make sure that your selector criteria are valid
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
You are passing pointers (Complex*
) when your function takes references (const Complex&
). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.
To get an object to pass to your function, you would need to dereference your pointers:
Complex::distanta(*firstComplexNumber, *secondComplexNumber);
Or get your function to take pointer arguments.
However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete
what you have new
ed), you're better off not using pointers in the first place:
Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);
Kafka uses ZooKeeper so you need to first start a ZooKeeper server if you don't already have one.
If you do not want to install and have a separate zookeeper server, you can use the convenience script packaged with kafka to get a quick-and-dirty single-node ZooKeeper instance.
Starting the single-node Zookeeper instance:
bin/zookeeper-server-start.sh config/zookeeper.properties
Starting the Kafka Server:
bin/kafka-server-start.sh config/server.properties
Listing the Topics available in Kafka:
bin/kafka-topics.sh --list --zookeeper localhost:2181
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
In Swift 2.0, the following function returns a substring before a given character.
func substring(before sub: String) -> String {
if let range = self.rangeOfString(sub),
let index: Int = self.startIndex.distanceTo(range.startIndex) {
return sub_range(0, index)
}
return ""
}
Here's a short way to convert it to hex:
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
Compiling Programs on Windows 7:
You have to download configured Borland Compiler from http://www.4shared.com/get/Gs41_5yA/borland_for_graphics.html or http://dwij.co.in/graphics-c-programming-for-windows-7-borland-compiler/.
Put your Borland’s ‘bin’ folder into Environmental Variables.
Now go inside folder ‘bin’ & edit file bcc32.cfg as per your folder structure. This file contains settings of headers & libraries.
-I"D:\Borland\include;"
-L"D:\Borland\lib;D:\Borland\Lib\PSDK"
Now create any C/C++ Program say myprogram.cpp
Use following command to compile this bunch of code:
F:\>bcc32 myprogram.cpp
From ggplot2 2.0.0
you can use the margin =
argument of element_text()
to change the distance between the axis title and the numbers. Set the values of the margin
on t
op, r
ight, b
ottom, and l
eft side of the element.
ggplot(mpg, aes(cty, hwy)) + geom_point()+
theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin
can also be used for other element_text
elements (see ?theme
), such as axis.text.x
, axis.text.y
and title
.
addition
in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top")
, you'll need a different theme setting - e.g. axis.title.x.top
. See https://github.com/tidyverse/ggplot2/issues/4343.
It will be more flexible with hover()
:
$(".my-popover").hover(
function() { // mouse in event
$this = $(this);
$this.popover({
html: true,
content: "Your content",
trigger: "manual",
animation: false
});
$this.popover("show");
$(".popover").on("mouseleave", function() {
$this.popover("hide");
});
},
function() { // mouse out event
setTimeout(function() {
if (!$(".popover:hover").length) {
$this.popover("hide");
}
}, 100);
}
)
It's not possible to achieve the required level of control over presentation in a regular textarea
.
If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).
From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors
If you're doing this for manual validation of the data, you can do this with LINQPad.
Create a connection to the database in LinqPad then create C# statements similar to the following:
DataTable table = MyStoredProc (param1, param2).Tables[0];
(from row in table.AsEnumerable()
select new
{
Col1 = row.Field<string>("col1"),
Col2 = row.Field<string>("col2"),
}).Dump();
Keep it Simple
Adding Floating Action Button using TextView by giving rounded xml background.
- Add compile com.android.support:design:23.1.1
to gradle file
Circle Xml is
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/colorPrimary"/>
<size
android:width="30dp"
android:height="30dp"/>
</shape>
Layout xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="5"
>
<RelativeLayout
android:id="@+id/viewA"
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1.6"
android:background="@drawable/contact_bg"
android:gravity="center_horizontal|center_vertical"
>
</RelativeLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="3.4"
android:orientation="vertical"
android:padding="16dp"
android:weightSum="10"
>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Name"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:id="@+id/name"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="Ritesh Kumar Singh"
android:singleLine="true"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Phone"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:id="@+id/number"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="8283001122"
android:textSize="22dp"
android:textColor="@android:color/black"
android:singleLine="true"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Email"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="[email protected]"
android:textSize="22dp"
android:singleLine="true"
android:textColor="@android:color/black"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="City"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="Panchkula"
android:textSize="22dp"
android:textColor="@android:color/black"
android:singleLine="true"
android:padding="3dp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/floating"
android:transitionName="@string/transition_name_circle"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="16dp"
android:clickable="false"
android:background="@drawable/circle"
android:elevation="10dp"
android:text="R"
android:textSize="40dp"
android:gravity="center"
android:textColor="@android:color/black"
app:layout_anchor="@id/viewA"
app:layout_anchorGravity="bottom"/>
</android.support.design.widget.CoordinatorLayout>
There are a few more differences regarding the structure you could mention.
Characteristics
member of IMAGE_FILE_HEADER
inside IMAGE_NT_HEADERS
. For a DLL, it has the IMAGE_FILE_DLL
(0x2000) flag turned on. For a EXE it's the IMAGE_FILE_EXECUTABLE_IMAGE
(0x2) flag.IMAGE_OPTIONAL_HEADER
) is the ImageBase
member. It specifies the virtual address at which the PE assumes it will be loaded. If it is loaded at another address, some pointers could point to the wrong memory. As EXE files are amongst the first to be loaded into their new address space, the Windows loader can assure a constant load address and that's usually 0x00400000. That luxury doesn't exist for a DLL. Two DLL files loaded into the same process can request the same address. This is why a DLL has another data directory called Base Relocation Directory that usually resides in its own section - .reloc
. This directory contains a list of places in the DLL that need to be rebased/patched so they'll point to the right memory. Most EXE files don't have this directory, but some old compilers do generate them.You can read more on this topic @ MSDN.
I often find that I only need to strip out comments and script elements. This has worked reliably for me for 15 years and can easily be extended to handle any element name in HTML or XML:
// delete all comments
response = response.replaceAll("<!--[^>]*-->", "");
// delete all script elements
response = response.replaceAll("<(script|SCRIPT)[^+]*?>[^>]*?<(/script|SCRIPT)>", "");
I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.
The steps are:
Open fiddler.
If on https go to menu Tools -> Options -> Https and tick the Capture & Decrypt https options
Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:
static function OnBeforeResponse(oSession: Session) {
//....
oSession.oResponse.headers.Remove("Access-Control-Allow-Origin");
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
//...
}
This will make every web response to have the Access-Control-Allow-Origin: * header.
This still won't work as the OPTIONS preflight will pass through and cause the request to block before our above rule gets the chance to modify the headers. So to fix this, in the fiddler main window, on the right hand side there's an AutoResponder tab. Add a new rule and response: METHOD:OPTIONS https://yoursite.com/ with auto response: *CORSPreflightAllow and tick the boxes: "Enable Rules" and "Unmatched requests passthrough".
See picture below for reference:
You can always do
git clone git://repo.org/fossproject.git && rm -rf fossproject/.git
Try removing the staticContent section from your web.config.
<system.webServer>
<staticContent>
...
</staticContent>
</system.webServer>
I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")"
, just add .Dispose()
to it.
File.Create("filename").Dispose();
This way it creates and closes the file for the next process to use it.
You need to create a function, but it is for your own convenience. It works perfect and I never encountered any faulty computations using this function.
CREATE FUNCTION [dbo].[get_days](@date datetime)
RETURNS int
AS
BEGIN
SET @date = DATEADD(MONTH, 1, @date)
DECLARE @result int = (select DAY(DATEADD(DAY, -DAY(@date), @date)))
RETURN @result
END
How it works: subtracting the date's day number from the date itself gives you the last day of previous month. So, you need to add one month to the given date, subtract the day number and get the day component of the result.
As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils
module (Thanks Oliver)
Here is the proper way to do it:
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.
If you're not interested in the details that git diff
outputs you can just run git cherry
which will output a list of commits your remote tracking branch has ahead of your local branch.
For example:
git fetch origin
git cherry master origin/master
Will output something like :
+ 2642039b1a4c4d4345a0d02f79ccc3690e19d9b1
+ a4870f9fbde61d2d657e97b72b61f46d1fd265a9
Indicates that there are two commits in my remote tracking branch that haven't been merged into my local branch.
This also works the other way :
git cherry origin/master master
Will show you a list of local commits that you haven't pushed to your remote repository yet.
ok, so if you are using bootstrap-rtl.css, what you can do is go to the following class .modal-backdrop and remove the z-index attribute. after that all should be fine
Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).
And it is working well...
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
JavaScript
function printDiv()
{
var divToPrint=document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}
I used underscore
javascript library to tweak this issue.
function containsObject(obj, list) {
var res = _.find(list, function(val){ return _.isEqual(obj, val)});
return (_.isObject(res))? true:false;
}
please refer to underscore.js documentation for the underscore functions used in the above example.
note: This is not a pure javascript solution. Shared for educational purposes.
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
$(document).ready(function(){
$("input[type=search]").attr("placeholder","this is a test");
});
As an alternative to PHPMailer, Pear's Mail and others you could use the Zend's library
$config = array('auth' => 'login',
'ssl' => 'ssl',
'port'=> 465,
'username' => '[email protected]',
'password' => 'XXXXXXX');
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
$mail = new Zend_Mail();
$mail->setBodyText('This is the text of the mail.');
$mail->setFrom('[email protected]', 'Some Sender');
$mail->addTo('[email protected]', 'Some Recipient');
$mail->setSubject('TestSubj');
$mail->send($transport);
That is my set up in localhost server and I can able to see incoming mail to my mail box.
I had a similar error and thought I'd answer in case anyone was having something similar. I was looping over a directory of json files and deserializing them but was getting this same error.
The problem was that it was trying to grab hidden files as well. Make sure the file you're passing in is a .json file. I'm guessing it'll handle text as well. Hope this helps.
ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.
The hidden
attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden
property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:
https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden
Using these standards can make it easier for disabled people to use the web.
Quick way to print something is:
select '** Place your mesage here' AS '** DEBUG:';
If you have a char array allocated you can simply put a '\0'
wherever you want.
Then point a new char * pointer to the location just after the newly inserted '\0'
.
This will destroy your original string though depending on where you put the '\0'
A very late answer, but hope this will help
^(.+?)/([\w]+\.log)$
This uses lazy check for /
, and I just modified the accepted answer
Just to add on these answers is that, mod_php is the oldest and slowest method available in HTTPD server to use PHP. It is not recommended, unless you are running old versions of Apache HTTPD and PHP. php-fpm and proxy_cgi are the preferred methods.
In eclipse Galileo :
From there you can Add External Jars
In R the equivalent function is seq
and you can use it with the option by
:
seq(from = 5, to = 100, by = 5)
# [1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
In addition to by
you can also have other options such as length.out
and along.with
.
length.out: If you want to get a total of 10 numbers between 0 and 1, for example:
seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1
along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).
seq(along.with=c(10,20,30))
# [1] 1 2 3
Although, instead of using the along.with
option, it is recommended to use seq_along
in this case. From the documentation for ?seq
seq
is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to useseq_along
in that case.
seq_along: Instead of seq(along.with(.))
seq_along(c(10,20,30))
# [1] 1 2 3
Hope this helps.
a reply to @DarinDimitrov for a case where i have used foreach in a razor view.
<li><label for="category">Category</label>
<select id="category">
<option value="0">All</option>
@foreach(Category c in Model.Categories)
{
<option title="@c.Description" value="@c.CategoryID">@c.Name</option>
}
</select>
</li>
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
Yes you will have to escape all double quotes by a backslash.
I got the same error when issuing a URL without the protocol (like localhost:4200
) instead of a correct one also specifying the protocol (e.g. http://localhost:4200).
Google Chrome works fine without the protocol (it takes http as the default), but Firefox crashes with this error.
As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.
public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
{
return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
}
This is the best way that I've found. You can just paste it into your appDelegate's didFinishLaunchingWithOptions
method:
Swift 3 / 4
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Sets background to a blank/empty image
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
// Sets shadow (line below the bar) to a blank image
UINavigationBar.appearance().shadowImage = UIImage()
// Sets the translucent background color
UINavigationBar.appearance().backgroundColor = .clear
// Set translucent. (Default value is already true, so this can be removed if desired.)
UINavigationBar.appearance().isTranslucent = true
return true
}
Swift 2.0
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Sets background to a blank/empty image
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default)
// Sets shadow (line below the bar) to a blank image
UINavigationBar.appearance().shadowImage = UIImage()
// Sets the translucent background color
UINavigationBar.appearance().backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
// Set translucent. (Default value is already true, so this can be removed if desired.)
UINavigationBar.appearance().translucent = true
return true
}
source: Make navigation bar transparent regarding below image in iOS 8.1
Just using math.isnan(x), Return True if x is a NaN (not a number), and False otherwise.
Try:
var Wrapper = React.createClass({
render: function() {
return (
<div className="wrapper">
before
{this.props.children}
after
</div>
);
}
});
See Multiple Components: Children and Type of the Children props in the docs for more info.
Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:
a = (1, 2, 3)
b = a + (4, 5, 6) # (1, 2, 3, 4, 5, 6)
c = b[1:] # (2, 3, 4, 5, 6)
And, of course, build them from existing values:
name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)
If you have some given list, and want to iterate over its items and indices, you can use enumerate()
:
for index, item in enumerate(my_list):
print index, item
If you only need the indices, you can use range()
:
for i in range(len(my_list)):
print i
If you want to keep the row with the lowest id
value:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MIN(n.id)
FROM NAMES n
GROUP BY n.name) x)
If you want the id
value that is the highest:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MAX(n.id)
FROM NAMES n
GROUP BY n.name) x)
The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
Borders on tables are always a bit flaky. One possibility would be to add a border-right declaration to each table cell except for the ones in right-most column. If you're using any kind of table-spacing this won't work very well.
Another option would be to use a 1px high background image with the borders inside it, but that'll only work if you can guarantee the width of each cell at all times.
Another possibility is to experiment with colgroup / col. This had fairly horrible support cross-browser the last time i looked at it but could have improved since then: http://www.webmasterworld.com/forum83/6826.htm
A terser way, either with rev
:
x[!(!duplicated(x) & rev(!duplicated(rev(x))))]
... rather than fromLast
:
x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]
... and as a helper function to provide either logical vector or elements from original vector :
duplicates <- function(x, as.bool = FALSE) {
is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
if (as.bool) { is.dup } else { x[is.dup] }
}
Treating vectors as data frames to pass to table
is handy but can get difficult to read, and the data.table
solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.
If you plan using background images a lot throughout your project you may find it useful to create a really simple custom pipe that will create the url for you.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'asUrl'
})
export class BackgroundUrlPipe implements PipeTransform {
transform(value: string): string {
return `url(./images/${value})`
}
}
Then you can add background images without all the string concatenation.
<div [ngStyle]="{ background: trls.img | asUrl }"></div>
Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:
The main idea behind this is to encapsulate the text and the circle in the same "div
" as you would do in html to have the logo and the name of the company in the same div
in a page header.
The main code is:
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
d3.json("data.json", function(json) {
/* Define the data for the circles */
var elem = svg.selectAll("g")
.data(json.nodes)
/*Create and place the "blocks" containing the circle and the text */
var elemEnter = elem.enter()
.append("g")
.attr("transform", function(d){return "translate("+d.x+",80)"})
/*Create the circle for each block */
var circle = elemEnter.append("circle")
.attr("r", function(d){return d.r} )
.attr("stroke","black")
.attr("fill", "white")
/* Create the text for each block */
elemEnter.append("text")
.attr("dx", function(d){return -20})
.text(function(d){return d.label})
})
and the json file is:
{"nodes":[
{"x":80, "r":40, "label":"Node 1"},
{"x":200, "r":60, "label":"Node 2"},
{"x":380, "r":80, "label":"Node 3"}
]}
The resulting html code shows the encapsulation you want:
<svg width="960" height="500">
<g transform="translate(80,80)">
<circle r="40" stroke="black" fill="white"></circle>
<text dx="-20">Node 1</text>
</g>
<g transform="translate(200,80)">
<circle r="60" stroke="black" fill="white"></circle>
<text dx="-20">Node 2</text>
</g>
<g transform="translate(380,80)">
<circle r="80" stroke="black" fill="white"></circle>
<text dx="-20">Node 3</text>
</g>
</svg>
I found another problem causing this issue and already solved it. I accidentally saved my script in UTF-16
encoding. It seems that PHP5 can't recognize <?php
tag in 16 bit encoding by default.
I was having multiple date formats into json, and was extracting csv with universal format. I looked multiple places, tried different ways, but at the end I'm able to convert with the following simple code.
private String getDate(String anyDateFormattedString) {
@SuppressWarnings("deprecation")
Date date = new Date(anyDateFormattedString);
SimpleDateFormat dateFormat = new SimpleDateFormat(yourDesiredDateFormat);
String convertedDate = dateFormat.format(date);
return convertedDate;
}
Solved it. So by default, all packages that falls under @SpringBootApplication
declaration will be scanned.
Assuming my main class ExampleApplication
that has @SpringBootApplication
declaration is declared inside com.example.something
, then all components that falls under com.example.something
is scanned while com.example.applicant
will not be scanned.
So, there are two ways to do it based on this question. Use
@SpringBootApplication(scanBasePackages={
"com.example.something", "com.example.application"})
That way, the application will scan all the specified components, but I think what if the scale were getting bigger ?
So I use the second approach, by restructuring my packages and it worked ! Now my packages structure became like this.
src/
+-- main/
¦ +-- java/
| +-- com.example/
| | +-- Application.java
| +-- com.example.model/
| | +-- User.java
| +-- com.example.controller/
| | +-- IndexController.java
| | +-- UsersController.java
| +-- com.example.service/
| +-- UserService.java
+-- resources/
+-- application.properties
A library solution (although I know this was not asked for).
If you happen to use Qt:
QCoreApplication::applicationDirPath()
All this tricks just look (more or less) as local functions, but they don't work like that. In a local function you can use local variables of it's super functions. It's kind of semi-globals. Non of these tricks can do that. The closest is the lambda trick from c++0x, but it's closure is bound in definition time, not the use time.
dojox.grid.DataGrid offers a JS abstraction for data so you can hook it up to various backends with provided dojo.data stores or write your own. You'll obviously need one that supports random access for this many records. DataGrid also provides full accessibility.
Edit so here's a link to Matthew Russell's article that should provide the example you need, viewing millions of records with dojox.grid. Note that it uses the old version of the grid, but the concepts are the same, there were just some incompatible API improvements.
Oh, and it's totally free open source.
SELECT column1 FROM table WHERE ISNUMERIC(column1) = 1
Note, as Damien_The_Unbeliever has pointed out, this will include any valid numeric type.
To filter out columns containing non-digit characters (and empty strings), you could use
SELECT column1 FROM table WHERE column1 not like '%[^0-9]%' and column1 != ''
The legend titles can be labeled by specific aesthetic.
This can be achieved using the guides()
or labs()
functions from ggplot2
(more here and here). It allows you to add guide/legend properties using the aesthetic mapping.
Here's an example using the mtcars
data set and labs()
:
ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
geom_point() +
labs(x="miles per gallon", y="displacement", size="horsepower",
col="# of cylinders", shape="# of gears")
Answering the OP's question using guides()
:
# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")
# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) +
geom_point(size=5) +
labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
guides(color=guide_legend("my title")) # add guide properties by aesthetic
I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.
try this.. I had it too but now it solved in XP..
C:\ YourFolder >set path=C:\Program Files\Java\jdk1.7.0_09\bin;
C:\ YourFolder >javac YourCode.java
Here is an easy implementation.
#include <Windows.h>
#include <iostream>
using namespace std;
class SingletonClass {
public:
static SingletonClass* getInstance() {
return (!m_instanceSingleton) ?
m_instanceSingleton = new SingletonClass :
m_instanceSingleton;
}
private:
// private constructor and destructor
SingletonClass() { cout << "SingletonClass instance created!\n"; }
~SingletonClass() {}
// private copy constructor and assignment operator
SingletonClass(const SingletonClass&);
SingletonClass& operator=(const SingletonClass&);
static SingletonClass *m_instanceSingleton;
};
SingletonClass* SingletonClass::m_instanceSingleton = nullptr;
int main(int argc, const char * argv[]) {
SingletonClass *singleton;
singleton = singleton->getInstance();
cout << singleton << endl;
// Another object gets the reference of the first object!
SingletonClass *anotherSingleton;
anotherSingleton = anotherSingleton->getInstance();
cout << anotherSingleton << endl;
Sleep(5000);
return 0;
}
Only one object created and this object reference is returned each and every time afterwords.
SingletonClass instance created!
00915CB8
00915CB8
Here 00915CB8 is the memory location of singleton Object, same for the duration of the program but (normally!) different each time the program is run.
N.B. This is not a thread safe one.You have to ensure thread safety.
public class Example extends Activity
{
private ListView lv;
ArrayList<String> arrlist=new ArrayList<String>();
//let me assume that you are putting the values in this arraylist
//Now convert your arraylist to array
//You will get an exmaple here
//http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html
private String arr[]=convert(arrlist);
@Override
public void onCreate(Bundle bun)
{
super.onCreate(bun);
setContentView(R.layout.main);
lv=(ListView)findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
}
}
This is documented in the iOS 7 UI Transition Guide, which you need an Apple developer ID to access directly. The relevant excerpt:
Because the status bar is transparent, the view behind it shows through. [...] Use a
UIStatusBarStyle
constant to specify whether the statusbar content should be dark or light:
UIStatusBarStyleDefault
displays dark content. [...]
UIStatusBarStyleLightContent
displays light content. Use when dark content is behind the status bar.
Also possibly of interest:
In iOS 7, you can control the style of the status bar from an individual vew controller and change it while the app runs. To opt in to this behavior, add the
UIViewControllerBasedStatusBarAppearance
key to an app'sInfo.plist
file and give it the valueYES
.
I'd definitely recommend having a look through the document, which, again, you can access with your Apple developer ID.
The problem I see here is that "sum" is an aggregate function.
first, you need to fix the query itself.
Select sum(c_counts + f_counts) total, [column to group sums by]
from table
group by [column to group sums by]
then, you can sort it:
Select *
from (query above) a
order by total
EDIT: But see post by Virat. Perhaps what you want is not the sum of your total fields over a group, but just the sum of those fields for each record. In that case, Virat has the right solution.
I wrote an add-on to overcome this issue in Firefox (Chrome, Opera version will have soon). It works with the latest Firefox version, with beautiful UI and support JS regex: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors
The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):
$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );
So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:
$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );
Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,
The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.
That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.
you could search with
aptitude search intl
after you can choose the right one, for example
sudo aptitude install php-intl
and finally
sudo service apache2 restart
good Luck!
No need to hack your editor, or switch editors.
Instead we can come up with a script to watch your development directories and chmod files as they're created. This is what I've done in the attached bash script. You probably want to read through the comments and edit the 'config' section as fits your needs, then I would suggest putting it in your $HOME/bin/ directory and adding its execution to your $HOME/.login or similar file. Or you can just run it from the terminal.
This script does require inotifywait, which comes in the inotify-tools package on Ubuntu,
sudo apt-get install inotify-tools
Suggestions/edits/improvements are welcome.
#!/usr/bin/env bash
# --- usage --- #
# Depends: 'inotifywait' available in inotify-tools on Ubuntu
#
# Edit the 'config' section below to reflect your working directory, WORK_DIR,
# and your watched directories, WATCH_DIR. Each directory in WATCH_DIR will
# be logged by inotify and this script will 'chmod +x' any new files created
# therein. If SUBDIRS is 'TRUE' this script will watch WATCH_DIRS recursively.
# I recommend adding this script to your $HOME/.login or similar to have it
# run whenever you log into a shell, eg 'echo "watchdirs.sh &" >> ~/.login'.
# This script will only allow one instance of itself to run at a time.
# --- config --- #
WORK_DIR="$HOME/path/to/devel" # top working directory (for cleanliness?)
WATCH_DIRS=" \
$WORK_DIR/dirA \
$WORK_DIR/dirC \
" # list of directories to watch
SUBDIRS="TRUE" # watch subdirectories too
NOTIFY_ARGS="-e create -q" # watch for create events, non-verbose
# --- script starts here --- #
# probably don't need to edit beyond this point
# kill all previous instances of myself
SCRIPT="bash.*`basename $0`"
MATCHES=`ps ax | egrep $SCRIPT | grep -v grep | awk '{print $1}' | grep -v $$`
kill $MATCHES >& /dev/null
# set recursive notifications (for subdirectories)
if [ "$SUBDIRS" = "TRUE" ] ; then
RECURSE="-r"
else
RECURSE=""
fi
while true ; do
# grab an event
EVENT=`inotifywait $RECURSE $NOTIFY_ARGS $WATCH_DIRS`
# parse the event into DIR, TAGS, FILE
OLDIFS=$IFS ; IFS=" " ; set -- $EVENT
E_DIR=$1
E_TAGS=$2
E_FILE=$3
IFS=$OLDIFS
# skip if it's not a file event or already executable (unlikely)
if [ ! -f "$E_DIR$E_FILE" ] || [ -x "$E_DIR$E_FILE" ] ; then
continue
fi
# set file executable
chmod +x $E_DIR$E_FILE
done
I also solved my problem with Mosh's answer and I thought PeterB's answer was a bit of since it used an enum as foreign key. Remember that you will need to add a new migration after adding this code.
I can also recommend this blog post for other solutions:
http://www.kianryan.co.uk/2013/03/orphaned-child/
Code:
public class Child
{
[Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Heading { get; set; }
//Add other properties here.
[Key, Column(Order = 1)]
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
The easiest solution is to redirect the standard output. In your python program file use the following:
if __name__ == "__main__":
sys.stdout = open('file.log', 'w')
#sys.stdout = open('/dev/null', 'w')
main()
Any std output (e.g. the output of print 'hi there'
) will be redirected to file.log
or if you uncomment the second line, any output will just be suppressed.
No one here posted an answer with all of the correct CSS variations, so here it is:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
Considering only one row is returned, only one loop will be done in both cases. Though it will check for the loop entering condition twice on each.
datetime has fields hour
and minute
. So to get the hours and minutes, you would use t1.hour
and t1.minute
.
However, when you subtract two datetimes, the result is a timedelta, which only has the days
and seconds
fields. So you'll need to divide and multiply as necessary to get the numbers you need.
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.
Try to change type of ScoreIfNoMatch, like this:
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
// the type should be string
public string ScoreIfNoMatch { get; set; }
}
I solved my problem on IE, using an alert("With a message")
to prevent default Behavior:
window.addEventListener("keydown", function (e) {
if(e.ctrlKey || e.metaKey){
e.preventDefault(); //Good browsers
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { //hack for ie
alert("Please, use the print button located on the top bar");
return;
}
}
});
Then, in your javascript:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
Now you can look at the console, click on the statement and see what is inside blah
<style type="text/css">
td { word-wrap: break-word;max-width:50px; }
</style>
how about window.location.replace(window.location.href);
You can use <hr>
for a vertical line as well.
Set the width
to 1
and the size(height) as long as you want.
I used 500 in my example(demo):
With <hr width="1" size="500">
If you are using react's templates, where the end of your react file looks like this: export default SomeComponent
you need to use the higher-order component (often referred to as an "HOC"), withRouter
.
First, you'll need to import withRouter
like so:
import {withRouter} from 'react-router-dom';
Next, you'll want to use withRouter
. You can do this by change your component's export. It's likely you want to change from export default ComponentName
to export default withRouter(ComponentName)
.
Then you can get the route (and other information) from props. Specifically, location
, match
, and history
. The code to spit out the pathname would be:
console.log(this.props.location.pathname);
A good writeup with additional information is available here: https://reacttraining.com/react-router/core/guides/philosophy
Compare of the flags of fromHtml().
<p style="color: blue;">This is a paragraph with a style</p>
<h4>Heading H4</h4>
<ul>
<li style="color: yellow;">
<font color=\'#FF8000\'>li orange element</font>
</li>
<li>li #2 element</li>
</ul>
<blockquote>This is a blockquote</blockquote>
Text after blockquote
Text before div
<div>This is a div</div>
Text after div
if you want the object on the stack, try this:
MyClass myclass;
myclass.DoSomething();
If you need a pointer to that object:
MyClass* myclassptr = &myclass;
myclassptr->DoSomething();
Try (maybe as root)
lsof -i -P
and grep the output for the port you are looking for.
For example to check for port 80 do
lsof -i -P | grep :80
The browser discloses it in navigator.userAgent
. If you're using jQuery, you're better off using jQuery.browser
as @Rab Nawaz said. However, as the API documentation says, it's better to check for feature support if possible. Quoting the documentation:
We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.
Here is a code example:
function isIE() {
if (window.jQuery) {
return jQuery.browser.msie || false;
} else {
// adapted from jQuery's source:
return navigator.userAgent.toLowerCase().indexOf('msie') >= 0;
}
}
You can simply use the isinstance function to make sure that the input data is of format string or unicode. Below examples will help you to understand easily.
>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string', unicode)
True
if your date filed is timestamp into database then this is the easy way to get record
$this->db->where('DATE(RecordDate) >=', date('Y-m-d',strtotime($startDate)));
$this->db->where('DATE(RecordDate) <=', date('Y-m-d',strtotime($endDate)));
Like this:
#include <vector>
// ...
std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));
(Pre-C++11 you need to leave whitespace between the angled brackets.)
Collections.synchronizedMap() method synchronizes all the methods of the HashMap and effectively reduces it to a data structure where one thread can enter at a time because it locks every method on a common lock.
In ConcurrentHashMap synchronization is done a little differently. Rather than locking every method on a common lock, ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map. By default there are 16 buckets and also separate locks for separate buckets. So the default concurrency level is 16. That means theoretically any given time 16 threads can access ConcurrentHashMap if they all are going to separate buckets.
The above answers didn't work for me. Possibly the option names were changed since '11, but the following did the trick for me:
ChartJsProvider.setOptions
scaleBeginAtZero: true
I heard of RTM (The RT FAQ Manager). Never used it, however.
The python-shell
module by extrabacon
is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling.
Installation: npm install python-shell
.
var PythonShell = require('python-shell');
PythonShell.run('my_script.py', function (err) {
if (err) throw err;
console.log('finished');
});
var PythonShell = require('python-shell');
var options = {
mode: 'text',
pythonPath: 'path/to/python',
pythonOptions: ['-u'],
scriptPath: 'path/to/my/scripts',
args: ['value1', 'value2', 'value3']
};
PythonShell.run('my_script.py', options, function (err, results) {
if (err)
throw err;
// Results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
For the full documentation and source code, check out https://github.com/extrabacon/python-shell
With PowerShell on Windows, you can use:
Get-Content ~/.ssh/id_rsa.pub | Set-Clipboard
If you are working on a windows forms project you can try the following:
Add items to the ListBox
as KeyValuePair
objects:
listBox.Items.Add(new KeyValuePair(key, value);
Then you will be able to retrieve them the following way:
KeyValuePair keyValuePair = listBox.Items[index];
var value = keyValuePair.Value;
Use something like this (Not compiler checked)
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSRange range=[self.myLabel.text rangeOfString:texts[sliderValue]]; //myLabel is the outlet from where you will get the text, it can be same or different
NSArray *colors=@[[UIColor redColor],
[UIColor redColor],
[UIColor yellowColor],
[UIColor greenColor]
];
[string addAttribute:NSForegroundColorAttributeName
value:colors[sliderValue]
range:range];
[self.scanLabel setAttributedText:texts[sliderValue]];
I faced the same issue. Our application running on four application servers and due to invalid schema location mentioned on one of the web service WSDL, hung threads are generated on the servers . The appliucations got down frequently. After corrected the schema Location , the issue got resolved.
One way:
some_list[::len(some_list)-1]
A better way (Doesn't use slicing, but is easier to read):
[some_list[0], some_list[-1]]
IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
I am going with the answer from here:
bash -c 'while [ 0 ]; do <your command>; sleep 5; done'
But you're really better off installing watch as this isn't very clean...
I'm posting this here, because I've spent like 3 and 4 hours on it, and I've only found answers like those one above, that say do add the executionTime
, but it doesn't solve the problem in the case that you're using ASP .NET Core. For it, this would work:
At web.config file, add the requestTimeout
attribute at aspNetCore
node.
<system.webServer>
<aspNetCore requestTimeout="00:10:00" ... (other configs goes here) />
</system.webServer>
In this example, I'm setting the value for 10 minutes.
Generally to avoid this kind of exceptions, you will need to surround your code by try and catch like this
try{
// your intent here
} catch (ActivityNotFoundException e) {
// show message to user
}
It sounds like it's your browser caching the image (which I now notice you wrote in your question). You can force the browser to reload the image by passing an extra variable like so:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
If you just want to change file permissions, you want to be careful about using -R
on chmod
since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:
sudo chmod -R a+w /var/www
But if you want to use the literal permissions of read/write, you may want to select files versus folders:
sudo find /var/www -type f -exec chmod 666 {} \;
(Which, by the way, for security reasons, I wouldn't recommend either of these.)
Or for folders:
sudo find /var/www -type d -exec chmod 755 {} \;
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
$ sbt sbtVersion
This prints the sbt version used in your current project, or if it is a multi-module project for each module.
$ sbt 'inspect sbtVersion'
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.1
[info] Description:
[info] Provides the version of sbt. This setting should be not be modified.
[info] Provided by:
[info] */*:sbtVersion
[info] Defined at:
[info] (sbt.Defaults) Defaults.scala:68
[info] Delegates:
[info] *:sbtVersion
[info] {.}/*:sbtVersion
[info] */*:sbtVersion
[info] Related:
[info] */*:sbtVersion
You may also want to use sbt about
that (copying Mark Harrah's comment):
The about command was added recently to try to succinctly print the most relevant information, including the sbt version.
Yeah, your current solution is prone to SQL injection attacks.
The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use this one from my blog) and then join that to your table. Something like:
SELECT d.[Name]
FROM Department d
JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId
This will work from anywhere, inside Form(), Form_Load(), or any event handler. I posted before, but I don't see it now?!?
public void exit(int exitCode)
{
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are in a running Form
System.Windows.Forms.Application.Exit();
System.Environment.Exit(exitCode);
}
else
{
// Form ended or never .Run
System.Environment.Exit(exitCode);
}
} //* end exit()
Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)
Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....
However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.
As you're partially working on Linux and Windows, make sure core.eol
is set to native
and core.autocrlf
is set to true
.
Then, replace the content of your .gitattributes
file with the following
* text=auto
This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.
However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.
Provided you work on a C based image processing project, replace the content of your .gitattributes
file with the following
* text=auto
*.txt text
*.c text
*.h text
*.jpg binary
This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.
In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.
As a real world example, you can also peek at this commit where those changes to a .gitattributes
file are demonstrated.
UPDATE to the answer considering the following comment
I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory
Makes sense. Thanks for the clarification. In this specific context, the .gitattributes
file by itself won't be enough.
Run the following commands against your repository
$ git config core.eol lf
$ git config core.autocrlf input
As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol
will make sure text files bear LF line endings on checkouts. core.autocrlf
will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.
Optionally, you can help Git distinguish what is a text file by creating a .gitattributes
file containing something similar to the following:
# Autodetect text files
* text=auto
# ...Unless the name matches the following
# overriding patterns
# Definitively text files
*.txt text
*.c text
*.h text
# Ensure those won't be messed up with
*.jpg binary
*.data binary
If you decided to create a .gitattributes
file, commit it.
Lastly, ensure git status
mentions "nothing to commit (working directory clean)", then perform the following operation
$ git checkout-index --force --all
This will recreate your files in your working directory, taking into account your config changes and the .gitattributes
file and replacing any potential overlooked CRLF in your text files.
Once this is done, every text file in your working directory WILL bear LF line endings and git status
should still consider the workdir as clean.
You could try to source your profile file to update your environment:
$ source ~/.profile
I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this:
print repr(temp)
You'll likely see something in there that's escaped in the form \x00
. These non-printing characters don't show up when you print directly to the console, but their presence is enough to negatively impact the parsing of a string value into a float.
-- Edited for question changes --
It turns this is partly accurate for your issue - the root cause however appears to be that you're reading more information than you expect from your socket or otherwise receiving multiple values. You could do something like
map(float, temp.strip().split('\r\n'))
In order to convert each of the values, but if your function is supposed to return a single float value this is likely to cause confusion. Anyway, the issue certainly revolves around the presence of characters you did not expect to see in the value you retrieved from your socket.
I had the same error. In my case wasn't because of a variable named str
. But because I named a function with a str parameter and the variable the same.
same_name = same_name(var_name: str)
I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (same_name =
) as a call to the function and detects that the str
parameter is not present, so it's missing, then it throws that error.
You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):
Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
Write-Host $_.IP1
Write-Host $_.IP2
...
}
declare @cur cursor
declare @idx int
declare @Approval_No varchar(50)
declare @ReqNo varchar(100)
declare @M_Id varchar(100)
declare @Mail_ID varchar(100)
declare @temp table
(
val varchar(100)
)
declare @temp2 table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)
declare @slice varchar(8000)
declare @String varchar(100)
--set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(',',@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
--select @slice
insert into @temp values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
-- select distinct(val) from @temp
SET @cur = CURSOR FOR select distinct(val) from @temp
--open cursor
OPEN @cur
--fetchng id into variable
FETCH NEXT
FROM @cur into @Approval_No
--
--loop still the end
while @@FETCH_STATUS = 0
BEGIN
select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No
insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)
FETCH NEXT
FROM @cur into @Approval_No
end
--close cursor
CLOSE @cur
select * from @tem
mysql -u root -p;
And mysql will ask for the password
I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...
c map (_.getP) zip c
Works well and is very intuitiv
Microsoft has an article about this issue. It goes through it all step by step.
In short it involves starting up the instance of sqlserver with -m
like all the other answers suggest. However Microsoft provides slightly more detailed instructions.
From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already registered, right-click Local Server Groups, point to Tasks, and then click Register Local Servers.)
In the Registered Servers area, right-click your server, and then click SQL Server Configuration Manager. This should ask for permission to run as administrator, and then open the Configuration Manager program.
Close Management Studio.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, find your instance of SQL Server. (The default instance of SQL Server includes (MSSQLSERVER) after the computer name. Named instances appear in upper case with the same name that they have in Registered Servers.) Right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Specify a startup parameter box, type -m and then click Add. (That's a dash then lower case letter m.)
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then click OK. (That's a semi-colon then a dash then lower case letter m.)
Click OK, and after the message to restart, right-click your server name, and then click Restart.
After SQL Server has restarted your server will be in single-user mode. Make sure that that SQL Server Agent is not running. If started, it will take your only connection.
On the Windows 8 start screen, right-click the icon for Management Studio. At the bottom of the screen, select Run as administrator. (This will pass your administrator credentials to SSMS.)
Note
For earlier versions of Windows, the Run as administrator option appears as a sub-menu.
In some configurations, SSMS will attempt to make several connections. Multiple connections will fail because SQL Server is in single-user mode. You can select one of the following actions to perform. Do one of the following.
a) Connect with Object Explorer using Windows Authentication (which includes your Administrator credentials). Expand Security, expand Logins, and double-click your own login. On the Server Roles page, select sysadmin, and then click OK.
b) Instead of connecting with Object Explorer, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). (You can only connect this way if you did not connect with Object Explorer.) Execute code such as the following to add a new Windows Authentication login that is a member of the sysadmin fixed server role. The following example adds a domain user named CONTOSO\PatK.
CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS; ALTER SERVER ROLE sysadmin ADD MEMBER [CONTOSO\PatK];
c) If your SQL Server is running in mixed authentication mode, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Execute code such as the following to create a new SQL Server Authentication login that is a member of the sysadmin fixed server role.
CREATE LOGIN TempLogin WITH PASSWORD = '************'; ALTER SERVER ROLE sysadmin ADD MEMBER TempLogin;
Warning:
Replace ************ with a strong password.
d) If your SQL Server is running in mixed authentication mode and you want to reset the password of the sa account, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Change the password of the sa account with the following syntax.
ALTER LOGIN sa WITH PASSWORD = '************'; Warning
Replace ************ with a strong password.
The following steps now change SQL Server back to multi-user mode. Close SSMS.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Existing parameters box, select -m and then click Remove.
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Remove the ;-m which you added earlier, and then click OK.
Right-click your server name, and then click Restart.
Now you should be able to connect normally with one of the accounts which is now a member of the sysadmin fixed server role.
If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:
Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:
In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.
Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx
I'm adding this answer late since this is the answer that pops up most on Google...
You can use PHP to...
$url = "www.google.co.uk";
$host = parse_url($url, PHP_URL_HOST);
// $host == "www.google.co.uk"
to grab the host but not the private domain to which the host refers. (Example www.google.co.uk
is the host, but google.co.uk
is the private domain)
To grab the private domain, you must need know the list of public suffixes to which one can register a private domain. This list happens to be curated by Mozilla at https://publicsuffix.org/
The below code works when an array of public suffixes has been created already. Simply call
$domain = get_private_domain("www.google.co.uk");
with the remaining code...
// find some way to parse the above list of public suffix
// then add them to a PHP array
$suffix = [... all valid public suffix ...];
function get_public_suffix($host) {
$parts = split("\.", $host);
while (count($parts) > 0) {
if (is_public_suffix(join(".", $parts)))
return join(".", $parts);
array_shift($parts);
}
return false;
}
function is_public_suffix($host) {
global $suffix;
return isset($suffix[$host]);
}
function get_private_domain($host) {
$public = get_public_suffix($host);
$public_parts = split("\.", $public);
$all_parts = split("\.", $host);
$private = [];
for ($x = 0; $x < count($public_parts); ++$x)
$private[] = array_pop($all_parts);
if (count($all_parts) > 0)
$private[] = array_pop($all_parts);
return join(".", array_reverse($private));
}
You can use:
a = [1, 3, 4, 5, 9, 6, 7, 8]
b = [1, 7, 0, 9]
same_values = set(a) & set(b)
print same_values
Output:
set([1, 7, 9])
Although the accepted answer works fine, since v0.21.0rc1 it gives a warning
UserWarning: Pandas doesn't allow columns to be created via a new attribute name
Instead, one can do
df[["X", "A", "B", "C"]].plot(x="X", kind="bar")
Tomcat (Headless) can be integrated with IntelliJ Idea - Community edition.
Step-by-step instructions are as below:
Add tomcatX-maven-plugin
to pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>SampleProject</path>
</configuration>
</plugin>
</plugins>
</build>
Add new run configuration as below:
Run >> Edit Configurations >> + >> Maven
Parameters tab ...
Name :: Tomcat
Working Directory :: Project Root Directory
Command Line :: tomcat7:run
Runner tab ...
VM Options :: <user needed options>
JRE :: <project needed>
Invoke Tomcat in Run/Debug mode directly from IntelliJ Run >> Run/Debug menu
NOTE: Though this is considered a hacking of using using Tomcat integration features of IntelliJ - Enterprise version features, but I would consider this a programmatic way integrating tomcat to the IntelliJ Idea - community edition.