Set settings without quotes - sublimetext2

I'm trying to update Sublime settings using it's API. Here is the code for this task:
import sublime
import sublime_plugin
class FileNameOnStatusBar(sublime_plugin.EventListener):
def on_activated(self, view):
sublime.load_settings("Preferences.sublime-settings").set("wrap_width", "80")
sublime.load_settings("Preferences.sublime-settings").set("word_wrap", "true")
sublime.save_settings("Preferences.sublime-settings")
This is what I'm trying to achieve:
{
wrap_width: 80,
word_wrap: true
}
And this is what I currently get:
{
wrap_width: "80",
word_wrap: "true"
}
As you can see, in the second example the values are placed inside quotes, and this is the reason why it doesn't work.
How it may be fixed?

The reason why the values are being quoted is because you are passing strings to the set method. Use the appropriate Python datatype instead.
import sublime
import sublime_plugin
class FileNameOnStatusBar(sublime_plugin.EventListener):
def on_activated(self, view):
settings = sublime.load_settings("Preferences.sublime-settings")
settings.set("wrap_width", 80)
settings.set("word_wrap", True)
sublime.save_settings("Preferences.sublime-settings")

Related

Using flask_excel within Blueprints

I have an application that is using Blueprints and I need to be able to generate csv files for download. I found the flask_excel package which works great, but none of the examples I've found use Blueprints. Here is an example application that works:
#app.py
from flask import Flask
import flask_excel as excel
app=Flask(__name__)
excel.init_excel(app)
#app.route("/example", methods=['GET'])
def example():
return excel.make_response_from_array([[1,2], [3, 4]], "csv", file_name="example_data")
if __name__ == "__main__":
app.run()
However, I need something structured like this:
#__init__.py
from flask import Flask
import flask_excel as excel
from download_csv import download_csv_bp
def create_app():
app = Flask(__name__)
app.register_blueprint(download_csv_bp)
excel.init_excel(app)
return app
app = create_app()
and
#download_csv.py
from flask import Flask, Blueprint
download_csv_bp=Blueprint('download_csv',__name__)
#download_csv_bp.route("/example", methods=['GET'])
def example():
return excel.make_response_from_array([[1,2], [3, 4]], "csv", file_name="example_data")
How do I import the flask_excel functions that are initialized in __init__.py? If I put import flask_excel as excel in my download_csv.py file, the response generated just prints the resulting text to the screen.
The solution was simpler than I thought. If I add the line from app import excel to download_csv.py then it works. My new issue is with ajax calling this route, but as this is unrelated to my original question, I won't ask it here.

properly import default export from JSON module

I have a JSON translation file "./countries/es.json" in my Angular application that I want to import and loop through.
{
...
"Solomon Islands": "Islas Salomón",
"South Sudan": "Sudán del Sur",
...
}
I have "resolveJsonModule": true, in my tsconfig.json file, so in general import goes well.
import * as countries from './countries/es.json';
and if I access the object say countries['Solomon Islands'] I get 'Islas Salomón' that is correct.
However if want to enumerate all countries:
const countries_keys = Object.keys(countries);
countries_keys is an array with one value 'default'. In order to obtain the country list I need to do:
const countries_keys = Object.keys(countries['default']);
My question - is there a way to do the import cleanly so I get the object exactly as in JSON file?
If I had the source file like:
{
countries: {
...
"Solomon Islands": "Islas Salomón",
"South Sudan": "Sudán del Sur",
...
}
}
I could simply do:
import { countries } from './countries/es.json';
but is there a clean way to import my original file as equivalent JSON object without the additional 'default' property.
You need add allowSyntheticDefaultImports in your tsconfig.json.
tsconfig.json
{
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true
}
TS
import countries from './countries/es.json';
import is not a good idea here later on if you want to move your file to some server you will need to rewrite the whole logic i would suggest to use httpclient get call here.So move you file to assets folder and then
constructor(private http:HttpClient){
this.http.get('assets/yourfilepath').subscribe(data=>{
const countries_keys = Object.keys(data['countries']);
console.log(data['countries'])//data is your json object here
})
}
What worked form me was:
import countries from './countries/es.json';
This is the "default import"

Simple http operator headers value jinja template not supported

I am trying to use templating in headers value of my http request using my custom http operator ( Extends simpleHttpOperator ). Seems like templating is supported only in data field. How can implemente the same in headers field. I wanted to pass authorization header templated. Please find my code below.
import airflow
from airflow import DAG
from airflow.configuration import conf
from airflow.operators.python_operator import PythonOperator
from airflow.operators.auth_plugins import SipAuthOperator
from airflow.operators.util_plugins import AuthUtility
DEFAULT_VERSION = '2.0'
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': airflow.utils.dates.days_ago(2),
'email': ['airflow#example.com'],
'email_on_failure': False,
'email_on_retry': False
}
DAG_ID = 'test_dag'
dag = DAG(DAG_ID, default_args=default_args,
schedule_interval=None,
catchup=False)
dag.doc_md = __doc__
auth_endpoint = conf['auth_apis']['authenticate_end_point']
def inspect_params(**context):
token = context['task_instance'].xcom_push(key='JWT_TOKEN',value='helloooo'
)
print(token)
test_operator = PythonOperator(dag=dag,task_id='init_api',
python_callable=inspect_params,
provide_context=True, )
# data={'token':'{{task_instance.xcom_pull(key=\'JWT_TOKEN\')}}'}
# {'Authorization':'Bearer '+'{{task_instance.xcom_pull(key=\'JWT_TOKEN\')}}'
http_operator = SipAuthOperator( dag=dag,task_id='authenticate_api',http_conn_id='auth_api',endpoint=auth_endpoint,headers={'token':'{{task_instance.xcom_pull(key=\'JWT_TOKEN\')}}'})
test_operator >> http_operator
Header value coming as {'token': "{{task_instance.xcom_pull(key='JWT_TOKEN')}}"} which is not as desred. If I put the same value in data field it works fine as expected. Is jinja templating supported on headers ? Any work around for this issue ?
The template_fields attribute in an operator determines which parameters can be templated. For example, in the original SimpleHttpOperator you can see the following
class SimpleHttpOperator(BaseOperator):
...
template_fields = ('endpoint', 'data',)
...
Which is why endpoint and data are supported template fields. Similarly in your custom operator, you'll want to include header.
class SipAuthOperator(SimpleHttpOperator):
...
template_fields = ('endpoint', 'data', 'header',)
...

grails excel-import plugin csv issue

I am using grails Excel-import plugin to import Excel and csv files.For excel files it works fine.But I am having a tough time to make it work for csv. I refferd the code in the following stack overflow Question
Import CSV with import-excel plugin in grails
I tried to bind the csv file with my csvImport class by using readFromFile and readFromURL method(these i found in the plugin'test directory in bootstrap.groovy).this is the code for my csvImport file
import org.grails.plugins.excelimport.*
class csvImport extends AbstractCsvImporter {
static Map configMap = [
startRow: 1,
columnMap: [
0: 'title',
1: 'author',
2: 'numSold'
]
]
def readCsv(File fileName){
read(fileName)
}
List<Map> getList(CONFIG_COLUMN_MAP) {
getData(CONFIG_COLUMN_MAP)
}
List<Map> createListFromCSV(CONFIG_COLUMN_MAP) {
def csvList = this.getList(CONFIG_COLUMN_MAP)
log.info("<<<csvList>>>>"+csvList)
}
and in controller i am trying to call it like this
def csvImportIntance=new csvImport()
csvImportIntance.readCsv(new File("D:\\Folder\\testCSV.csv"))
def bookParamsList= csvImportIntance.createListFromCSV(CONFIG_COLUMN_MAP)
the file is ms-excel csv file.
Thanks in advance for any help.
First of all you class name should start with a capital letter.

scrapy request form for scraping data

I am using this code and i am using url=http://money.moneygram.com.au/forex-tools/currency-converter-widget-part
from __future__ import absolute_import
#import __init__
#from scrapy.spider import BaseSpider
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.http import Request
from scrapy.http import FormRequest
from scrapy.http import Response
from scrapy.selector import HtmlXPathSelector
import MySQLdb
class DmozSpider(CrawlSpider):
name = "moneygram"
allowed_domains = ["moneygram.com"]
start_urls = ["http://money.moneygram.com.au/forex-tools/currency-converter-widget-part"]
def parse(self,response):
# yield FormRequest.from_response(response,formname='firstSelector',formdata="FromCurrency=USD&ToCurrency=INR&FromCurrency_dropDown=USD&ToCurrency_dropDown=INR",callback=self.parse1)
# request_with_cookies = Request(url="http://money.moneygram.com.au",
# cookies={'FromCurrency': 'USD', 'ToCurrency': 'INR'},callback=self.parse1)
yield FormRequest.from_response(response,formname=None,formnumber=0,formpath=None,formdata="FromCurrency=AED&ToCurrency=VND&FromCurrency_dropDown=AED&ToCurrency_dropDown=VND&FromAmount=2561&ToAmount=&X-Requested-With=XMLHttpRequest",callback=self.parse1)
To send the form data as required to me but is giving error that
raise ValueError("No <form> element found in %s" % response)
exceptions.ValueError: No <form> element found in <200 http://money.moneygram.com.au/forex-tools/currency-converter-widget-part>
How can I convert from usd to inr ?
The page you mentioned is not a valid HTML. Looks it's a SSI block which should be part of another page.
You the error because This page uses Javascript heavily. It doesn't have a
FormRequest.from_response tries to make the request using an existing form, but the form is not there.
You should either work with the whole page, or make up the FormRequest filling it's attributes manually and then submitting it to the URL from the whole page.