I am trying to set up an autocomplete feature for Codemirror for the Python language. Unfortunately, it seems that Codemirror only includes the files necessary for Javascript key term completion.
Has anyone built Python hint file for CodeMirror similar to the JavaScript Version?
(Edit for future reference: link to similar question on CodeMirror Google Group)
I'm the original author of the Python parser for Codemirror (1 and 2). You are correct that the Python parser does not offer enough information for autocomplete. I tried to build it into the parser when Codemirror 2 came around but it proved too difficult for my JS skills at the time.
I have far more skills now but far less time. Perhaps someday I'll get back to it. Or if someone wants to take it up, I would be glad to help.
Add python-hint.js, show-hint.js, show-hint.css. Then
var editor = CodeMirror.fromTextArea(your editor instance codes here;
editor.on('inputRead', function onChange(editor, input) {
if (input.text[0] === ';' || input.text[0] === ' ' || input.text[0] === ":") {
return;
}
editor.showHint({
hint: CodeMirror.pythonHint
});
});
< script >
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: {
name: "python",
version: 3,
singleLineStringErrors: false
},
lineNumbers: true,
indentUnit: 4,
extraKeys: {
"Ctrl-Space": "autocomplete"
},
matchBrackets: true
});
CodeMirror.commands.autocomplete = function (cm) {
CodeMirror.simpleHint(cm, CodeMirror.pythonHint);
}
</script>
I start the python autocomplete with a js based on pig-hint from codemirror 3.
You can get the python-hint.js from here.
to work, you need in your html:
include simple-hint,js and python-hint.js, simple-hint.css plus codemirror.js
add this script:
<script>
CodeMirror.commands.autocomplete = function(cm) {
CodeMirror.simpleHint(cm, CodeMirror.pythonHint);
}
</script>
python-hint.js is a basic js I have created today and not reviewed in depth.
You can initialize this way also, adding extraKeys parameter to CodeMirror initialization:
CodeMirror(function(elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {
mode: "python",
lineNumbers: true,
autofocus: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});
Related
I need to produce a screencast of an IPython session, and to avoid confusing viewers, I want to disable all warnings emitted by warnings.warn calls from different packages. Is there a way to configure the ipythonrc file to automatically disable all such warnings?
Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
I hide the warnings in the pink boxes by running the following code in a cell:
from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
if (code_show_err){
$('div.output_stderr').hide();
} else {
$('div.output_stderr').show();
}
code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click here.''')
The accepted answer does not work in Jupyter (at least when using some libraries).
The JavaScript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.
To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles CSS to hide/unhide warnings.
%%javascript
(function(on) {
const e = $("<a>Setup failed</a>");
const ns = "js_jupyter_suppress_warnings";
var cssrules = $("#" + ns);
if(!cssrules.length)
cssrules = $("<style id='" + ns + "' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
var s = 'Showing';
cssrules.empty()
if(on) {
s = 'Hiding';
cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
}
e.text(s + ' warnings (click to toggle)');
on = !on;
}).click();
$(element).append(e);
})(true);
For JupyterLab, this should work (#Alasja):
from IPython.display import HTML
HTML('''<script>
var code_show_err = false;
var code_toggle_err = function() {
var stderrNodes = document.querySelectorAll('[data-mime-type="application/vnd.jupyter.stderr"]')
var stderr = Array.from(stderrNodes)
if (code_show_err){
stderr.forEach(ele => ele.style.display = 'block');
} else {
stderr.forEach(ele => ele.style.display = 'none');
}
code_show_err = !code_show_err
}
document.addEventListener('DOMContentLoaded', code_toggle_err);
</script>
To toggle on/off output_stderr, click <a onclick="javascript:code_toggle_err()">here</a>.''')
I am using pyperclip.py to grab a list of E-Mail Addresses in my web app using a form so a user can paste it locally via clipboard. It works perfect locally. However, while running it on a server (Linux 14.04 with Apache2) and accessed from a client system through the browser it doesn't copy. How can I get it to copy to the clipboard of the client's system?
Right now I'm just trying to get it to work and as such I'm only using a single line. I'm using pyperclip 1.5.15 with xclip and Python 3.4. The server is running Linux 14.04 and the client has noticed issues on Windows 8 and Windows 10 using Google Chrome and IE. No other os has currently been tested.
pyperclip.copy("HELLO")
Since I couldn't find many details on this subject I thought I'd answer my question. Unfortunately, it doesn't appear that browsers will support pyperclip so an HTML + Javascript work around is required (meaning on pyperclip). First, add your Django Template var as an HTML attribute from there you can use Javascript to handle the copy functionality. Below is an example of how to do this, sorry in advance because stackoverflow was giving some weird formatting to the example. It also assumes you have a form below with the id of email_list_clipboard. I hope this helps anyone else who may of run into a similar issue!
Example:
<html email-list="{{request.session.email_list}}">
<script>
$(document).ready(function () {
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
// set things up so my function will be called when field_three changes
$('#email_list_clipboard').click(function (click) {
event.preventDefault();
copyTextToClipboard(document.documentElement.getAttribute("email-list"));
});
</script>
I was following the example Blockly Code Generators and was able to generate Python codes. But when I run the Python code, I get an error. It seems the error is 'eval(code)' below, what should I do if I want to execute the Python code right inside the browser? Thanks for any help!
Blockly.JavaScript.addReservedWords('code');
var code = Blockly.JavaScript.workspaceToCode(workspace);
try {
eval(code);
} catch (e) {
alert(e);
}
here is the snapshot Unfortunately i dont have enough points to post the image here
Can you try this with a simple code , like - print('Hello World!')
According to the image , the issue could be with indentation , and indentation is very important in python, othewise it can cause syntax errors .
You should have also changed the code to -
Blockly.Python.addReservedWords('code');
var code = Blockly.JavaScript.workspaceToCode(workspace);
try {
eval(code);
} catch (e) {
alert(e);
}
Try to eval with a Python interp written is JS, like http://brython.info/.
as you using eval function of javascript you are actually saying to print the page as print() means to print the page in javascript.
The solution to this is there in the Blockly itself as to rn the code they call this function.
function() {
Blockly.JavaScript.INFINITE_LOOP_TRAP = 'checkTimeout();\n';
var timeouts = 0;
var checkTimeout = function() {
if (timeouts++ > 1000000) {
throw MSG['timeout'];
}
};
var code = Blockly.JavaScript.workspaceToCode(Code.workspace);
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
try {
eval(code);
} catch (e) {
alert(MSG['badCode'].replace('%1', e));
}
The above code is from code.js in demos/code/code.js line 553.
Update 2
I upgraded from 0.6.1 to 1.0.9 which fixed the issue. It appears as thought there were two fixes in versions 0.8.7 and 0.8.8 that were needed to make this work. In 0.8.7 it does make the call to the reourceExtractor, but still errors out w/ this trace:
Error: $digest already in progress
at Error ()
at beginPhase (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8334:15)
at Object.$get.Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8136:11)
at HTMLDivElement.ngEventDirectives.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:12986:17)
at event.preventDefault (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:1992:10)
at Array.forEach (native)
at forEach (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:130:11)
at eventHandler (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:1991:5)
at HTMLDivElement.forEach.bind.events.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2067:15)
at event.preventDefault (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:1992:10)
however 0.8.8 seems to have cleared all that up. I am going to continue to poke around and see if there are any other oddities.
I don't know how I ended up with such an old version of restangular.
Update:
so tracing through the javascript
angular-resource.js::ResourceFactory
is being called the success variable is the anonymous function from
restangular.js::fetchFunction
where the responseExtractor is the function I set up in my app. So this all looks good??? in
angular-resource.js::ResourceFactory
the REST call is made and the data variable contains the correct REST response. It is falling apart here in the same function:
if (data) {
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
copy(data, value);
}
}
the error is occurring # value.push(new Resource(item)); where value is essentially the JSON rest response.
I read that angular resource requires you to define the rest resource and response and part of the definition is defining the array portions. I don't know if that is the root cause - but I thought restangular took care of that for me. Still more digging to do. Any help is -still- appreciated.
Thx
So I am learning Angular and Django simultaneously. I have used Django rest services to build a service to return some simple JSON. That part is working fine, but I cannot seem to get it hooked up with /restangular. The REST call is happening, and json is being returned - but the responseExtractor doesn't seem to be getting called. I have been fidgeting around and can't seem to put my finger on it.
Thank you in advance
adding the call stack:
TypeError: Object # has no method 'push'
at U (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:10:257)
at new Resource (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:350:9)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:407:32
at m (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:6:494)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:406:19
at h (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:78:33)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:78:266
at Object.e.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:88:347)
at Object.e.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:86:198)
at Object.e.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:88:506)
non min stack
TypeError: Object # has no method 'push'
at copy (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:593:21)
at new Resource (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:350:9)
at angular.module.factory.Resource.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:407:32)
at forEach (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:137:20)
at angular.module.factory.Resource.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:406:19)
at deferred.promise.then.wrappedCallback (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:6846:59)
at ref.then (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:6883:26)
at Object.$get.Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8057:28)
at Object.$get.Scope.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:7922:25)
at Object.$get.Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8143:24)
looking at the code, the responseExtractor method is stored in the variable "a" which I don't see in the stack.
JSON
{
"count": 2
, "next": null
, "previous": null
, "results": [{"file": "tb.png", "caption": "dfsdffs", "id": 1}
, {"file": "tannin_tasting.jpg", "caption": "tannin tasting", "id": 2}
]
}
Javascript (edit: fixed cut paste error mentioned by sza)
angular.module('spaceJam', ['ui.bootstrap', 'restangular'])
.config(function(RestangularProvider) {
RestangularProvider.setResponseExtractor(function(response, operation) {
alert('here')
if (operation === "getList") {
var newResponse = response.results;
newResponse._resultmeta = {
"count": response.count,
"next": response.next,
"previous": response.previous
};
return newResponse;
}
return response;
});
});
var CarouselCtrl = function ($scope, Restangular) {
Restangular.all('images/?format=json').getList().then(function(images) {
alert(1)
$scope.items = images;
});
$scope.myInterval = 3000;
$scope.template = "/resources/angularViews/carousel.html"
var slides = $scope.slides = [
{'type': 'image', 'name': '/resources/img/pinot_noir_glass.jpg'}
, {'type': 'image', 'name': '/resources/img/toast1.jpg'}
, {'type': 'image', 'name': '/resources/img/vinyard1.jpg'}
, {'type': 'image', 'name': '/resources/img/tannin_tasting.jpg'}
]
}
Basically you were having that problem because Restangular was using $resource underneath. Since version 0.8.7 and 0.8.8 I ditched $resource and started using $http below as $resource was bringing a lot of problems. Once of them was the one you were facing.
If you find any other issue, please add an issue at Github.
Thanks!
See original post. Upgrade solved the problem.
I have a config(text) file with the following content :
hello {
if name == "foo" {
//do something
else {
// something else
}
# contents
}
world {
if name == "bar" {
//do something
else {
// do something else
}
# comments
}
I want to search in this file all the if else blocks with "foo". What is the best way in python ?
The comments warning you away from overly complex languages for configuration aren't wrong. But if this is something you must do, the next step is to build a parser that can read your grammar, and give you the token tree. Perhaps something lie pyparsing would be useful?