本文整理汇总了Python中execjs.compile函数的典型用法代码示例。如果您正苦于以下问题:Python compile函数的具体用法?Python compile怎么用?Python compile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了compile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: calculate_interest_and_credit
def calculate_interest_and_credit(price, first_payment, credit_length, no_insurance, no_confirmation, variation):
js_calc_filename = 'kreddb/js/creditcalc/calculator.js'
py_start_token = '// py_start'
py_end_token = '// py_end'
js_calc_filepath = finders.find(js_calc_filename)
with open(js_calc_filepath) as js_calc_file:
js_calc = js_calc_file.read()
py_start = js_calc.index(py_start_token) + len(py_start_token)
py_end = js_calc.index(py_end_token)
js_context = execjs.compile(js_calc[py_start:py_end])
interest = js_context.call(
'recalculate_interest',
price,
first_payment,
credit_length,
no_insurance,
no_confirmation,
variation
)
credit = js_context.call(
'calculate_credit',
price,
first_payment,
credit_length,
interest
)
return int(float(credit['total']) / (credit_length * 30))
开发者ID:kromkrom,项目名称:kreditiki,代码行数:32,代码来源:calculator.py
示例2: __parse_token
def __parse_token(self, html_str):
pattern = re.compile('\\$\\$_=.*~\\[\\];.*\"\"\\)\\(\\)\\)\\(\\);')
match = pattern.search(html_str)
if not match:
raise "Can't find obfuscated token data."
obfuscated = match.group()
ctx = execjs.compile("""
function getToken() {
var token = null;
localStorage = {
setItem: function(key, value) {
if (key === 'gv-token')
token=value
}
};
""" +
obfuscated +
"""
return token;
}"""
)
self.__token_value = ctx.call('getToken')
开发者ID:master94,项目名称:UaTrainTicketsBookingClient,代码行数:25,代码来源:client.py
示例3: buildBundle
def buildBundle(self, rebuild=None):
""" Builds CommonJS bundle """
rebuild = self._rebuild_bundle if rebuild is None else rebuild
if not os.path.exists(os.path.dirname(self._js_bundle)):
os.makedirs(os.path.dirname(self._js_bundle))
js_bundle_ts = os.path.getmtime(self._js_bundle) if os.path.exists(self._js_bundle) else 0
css_bundle_ts = os.path.getmtime(self._css_bundle) if os.path.exists(self._css_bundle) else 0
js_files_max_ts = max([os.path.getmtime(filename) for filename in self._scripts.values()]) if self._scripts else 0
css_files_max_ts = max([os.path.getmtime(filename) for filename in self._styles.values()]) if self._styles else 0
with open(os.path.join(os.path.dirname(__file__), 'CommonMixin.js')) as file:
ctx = execjs.compile(file.read())
if self._scripts and (js_files_max_ts>js_bundle_ts or rebuild):
files = list(self._scripts.items())
try:
ctx.call('bundle_scripts', self._js_bundle, self._requires, files, self._debug)
except execjs.RuntimeError as exc:
raise RuntimeError('execjs.RuntimeError: {0}'.format(exc.args[0].decode('utf8')))
logging.warning("Rebuilded: '{0}'.".format(self._js_bundle))
if self._styles and (css_files_max_ts>css_bundle_ts or rebuild):
files = list(self._styles.values())
try:
ctx.call('bundle_styles', self._css_bundle, files, self._debug)
except execjs.RuntimeError as exc:
raise RuntimeError('execjs.RuntimeError: {0}'.format(exc.args[0].decode('utf8')))
logging.warning("Rebuilded: '{0}'.".format(self._css_bundle))
开发者ID:Alesh,项目名称:tornado-jsmixin,代码行数:25,代码来源:CommonMixin.py
示例4: std_encode
def std_encode(s):
import base64
import execjs
ctx = execjs.compile("""
btoa = function (input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var str = String(input);
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
}
""")
temp = ctx.call("encodeURIComponent", s)
return ctx.call("btoa", temp)
开发者ID:codecola1,项目名称:neauoj,代码行数:29,代码来源:judge.py
示例5: create_gid
def create_gid(self):
temp = execjs.compile('''function create_gid() {
return "xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,
function(c) {var r = Math.random() * 16 | 0,v = c == "x" ? r : (r & 3 | 8);
return v.toString(16);})}''')
self.gid = temp.call('create_gid')
return self.gid
开发者ID:sclbeta,项目名称:bdy,代码行数:7,代码来源:baidu.py
示例6: buildBundle
def buildBundle(self, rebuild=None):
""" Builds CommonJS bundle and prepare it for server page prerendering. """
# scans all templates and registers all found components
template_path = self.settings.get('template_path')
if os.path.exists(template_path) and os.path.isdir(template_path):
for dirname, _, filelist in os.walk(template_path):
for filename in filelist:
filename = os.path.join(dirname, filename)
with open(filename) as file:
for alias in re.findall(self._RE, file.read()):
if alias not in self._scripts:
try:
name = alias.split('.')[-1]
module = importlib.import_module('.'.join(alias.split('.')[:-1]))
component = getattr(module, name)
if component:
self.registerComponent(component)
else:
raise
except:
raise ValueError("Component: {0} is not found.".format(alias))
CommonMixin.buildBundle(self, rebuild)
if os.path.exists(self._js_bundle):
with open(self._js_bundle) as file:
bundle = file.read()
with open(os.path.join(os.path.dirname(__file__), 'ReactMixin.js')) as file:
self._ctx = execjs.compile(bundle+file.read());
if self.settings.get('debug'):
for filename in self._styles.values():
tornado.autoreload.watch(filename)
for filename in self._scripts.values():
tornado.autoreload.watch(filename)
开发者ID:Alesh,项目名称:tornado-jsmixin,代码行数:33,代码来源:ReactMixin.py
示例7: retrieve
def retrieve(palabra):
buffer = BytesIO()
#change to use `requests'
c = pycurl.Curl()
address = 'http://lema.rae.es/drae/srv/search?'
palabra_enc = urllib.parse.urlencode({'key':palabra})
c.setopt(c.URL, address+palabra_enc)
c.setopt(c.WRITEDATA, buffer)
c.perform()
body = buffer.getvalue()
l = body.decode().split("<script>")[1].split("</script>")[1].replace('<script type="text/javascript">', '').replace('document.forms[0].elements[1].value=', 'return ')
ctx = execjs.compile(l)
chall = ctx.call("challenge")
pdata = "&".join(body.decode().split("<body")[1].replace("/>", "\n").split("\n")[1:-1]).replace('<input type="hidden" name="', '').replace('" value="', '=').replace('"','').replace('TS014dfc77_cr=', 'TS014dfc77_cr=' + urllib.parse.quote_plus(chall))
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, address+palabra_enc)
c.setopt(c.WRITEDATA, buffer)
c.setopt(pycurl.HTTPHEADER, ["Referer: http://lema.rae.es/drae/srv/search?key=hola",
"Cache-Control: max-age=0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Origin: http://lema.rae.es",
"User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36"
])
c.setopt(c.POSTFIELDS, pdata)
c.perform()
body = buffer.getvalue().decode()
return body
开发者ID:ne555,项目名称:rae,代码行数:31,代码来源:rae.py
示例8: get_globals_from_js
def get_globals_from_js(javascript, js_var_names):
ctx = execjs.compile(javascript)
extracted_vars = {}
for js_var_name in js_var_names:
extracted_vars[js_var_name] = ctx.eval(js_var_name)
return extracted_vars
开发者ID:Benny-,项目名称:emoticon_server,代码行数:7,代码来源:RedditEmoteScraper.py
示例9: fix_javascript
def fix_javascript(url, content):
""" 中南文交所的幺蛾子
假定至少安装过node
"""
import execjs
try:
if 'znypjy' in url:
text = content.decode('gb18030', 'ignore')
m = re.compile('(function.*?;})window.location').search(text)
if m:
script = m.group(1)
code = execjs.compile(script).call('decoder')
content = session.get(
url + '?' + code, timeout=(5, 10)).content
elif 'xhcae' in url:
text = content.decode('gb18030', 'ignore')
m = re.compile(
'/notice/\w+/\?WebShieldSessionVerify=\w+').search(text)
if m:
url = m.group(0)
content = session.get(
'http://www.xhcae.com' + url, timeout=(5, 10)).content
except:
log.exception('')
return content
开发者ID:sopnic,项目名称:ybk,代码行数:26,代码来源:crawler.py
示例10: __init__
def __init__(self,path):
try:
self.javascript = execjs.compile(open(path).read())
except:
self.pyv8 = False
else:
self.pyv8 = True
开发者ID:dayjaby,项目名称:yomisama,代码行数:7,代码来源:deinflect.py
示例11: __init__
def __init__(self):
self.tkk = get_tkk() #从服务器获取TKK
self.ctx = execjs.compile("""
function b(a, b) {
for (var d = 0; d < b.length - 2; d += 3) {
var c = b.charAt(d + 2),
c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
}
return a
}
function tk(a,TKK) {
for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
var c = a.charCodeAt(f);
128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
}
a = h;
for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
a = b(a, "+-3^+b+-f");
a ^= Number(e[1]) || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1E6;
return a.toString() + "." + (a ^ h)
}
""")
开发者ID:lyf1134,项目名称:fanyi,代码行数:26,代码来源:gtk.py
示例12: getimgurls
def getimgurls(html, url):
sFiles = re.search('sFiles="([^"]+)"', html).group(1)
sPath = re.search('sPath="([^"]+)"', html).group(1)
viewhtm = grabhtml("http://www.iibq.com/script/viewhtm.js")
env = """
window = {
"eval": eval,
"parseInt": parseInt,
"String": String,
"RegExp": RegExp
};
location = {
"hostname": "www.iibq.com"
};
"""
unsuan = partial(
execjs.compile(
env + re.search(r'(.+?)var cuImg', viewhtm, re.DOTALL).group(1)
).call,
"unsuan"
)
arrFiles = unsuan(sFiles).split("|")
ds = grabhtml("http://www.iibq.com/script/ds.js")
SLUrl = re.search('sDS = "([^"]+)"', ds).group(1).split("^")[0].split("|")[1]
return [SLUrl + sPath + f for f in arrFiles]
开发者ID:v7368858,项目名称:ComicCrawler,代码行数:32,代码来源:iibq.py
示例13: __init__
def __init__(self, username, password):
"""
:param username: username (student id)
:param password: password (default: birthday - yyyymmdd)
"""
self._username = username
self._password = password
self._s = requests.Session()
self._s.headers.update({
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'http://zyfw.bnu.edu.cn'
})
self._lt = ''
self._execution = ''
self._info = {}
self._select_info = {}
self._grade_info = {}
self._table_parser = TableHTMLParser()
self._result_parser = ResultHTMLParser()
self._evaluate_parser = EvaluateHTMLParser()
# des js
with open('des.js', 'r', encoding='utf8') as f:
self._des = execjs.compile(f.read())
开发者ID:xuhongxu96,项目名称:BNU-Schoolwork-Assist,代码行数:26,代码来源:bnujwc.py
示例14: __setup
def __setup(self):
global src
if not src:
for js in ['compiler', 'handlebars', 'ember-template-compiler']:
src += resource_string(__name__, 'js/{0}.js'.format(js))
self.ctx = execjs.compile(src)
开发者ID:campbellr,项目名称:ember-compressor-compiler,代码行数:7,代码来源:__init__.py
示例15: getimgurl
def getimgurl(html, url, page):
if url not in cache:
key = search(r'id="dm5_key".+?<script[^>]+?>\s*eval(.+?)</script>', html, DOTALL)
if key:
key = eval(key.group(1)).split(";")[1]
key = search(r"=(.+)$", key).group(1)
key = eval(key)
else:
key = ""
length = search("DM5_IMAGE_COUNT=(\d+);", html).group(1)
cid = search("DM5_CID=(\d+);", html).group(1)
funs = []
for p in range(1, int(length) + 1):
fun_url = urljoin(url, "chapterfun.ashx?cid={}&page={}&language=1&key={}>k=6".format(cid, p, key))
funs.append(fun_url)
cache[url] = funs
# Grab cookies?
grabhtml(funs[0], referer=url)
if page - 1 >= len(cache[url]):
del cache[url]
raise LastPageError
fun_url = cache[url][page - 1]
text = grabhtml(fun_url, referer=url)
d = compile(text).eval("(typeof (hd_c) != 'undefined' && hd_c.length > 0 && typeof (isrevtt) != 'undefined') ? hd_c : d")
return d[0]
开发者ID:v7368858,项目名称:ComicCrawler,代码行数:29,代码来源:dm5.py
示例16: _rsa_encrypt
def _rsa_encrypt(session: requests.Session, url: str, modulus: str, public_exp: str, rsaiv: str, pw: str):
""" Hilariously runs the RSA javascript with some of our own javascript injected so that we can
get the correct ciphertext for our password.
Eventually need to switch to using a Python library once we figure out how to do that.
"""
rsaencrypt_response = session.get(url)
assert rsaencrypt_response.status_code == requests.codes.ok, \
"Unable to get RSAEncrypt.js. Status: {}\nBody:\n{}".format(rsaencrypt_response.status_code,
rsaencrypt_response.text)
assert "RSAKey" in rsaencrypt_response.text, "Got unexpected content for RSA encryption."
script_additions = """
var navigator = {};
var window = {};
window.crypto = null;
function my_encrypt(modulus, publicExponent, rsaiv, password) {
var rsa = new RSAKey();
rsa.setPublic(modulus, publicExponent);
return rsa.encrypt(rsaiv + password);
}
function MaskElement(elem) {}
"""
new_script = script_additions + rsaencrypt_response.text
ctx = execjs.compile(new_script)
return ctx.call("my_encrypt", modulus, public_exp, rsaiv, pw)
开发者ID:dmwyatt,项目名称:makebank,代码行数:33,代码来源:login.py
示例17: group
def group(self, key, condition, initial, reduce, finalize=None):
if execjs is None:
raise NotImplementedError(
"PyExecJS is required in order to use group. "
"Use 'pip install pyexecjs pymongo' to support group mock."
)
reduce_ctx = execjs.compile(
"""
function doReduce(fnc, docList) {
reducer = eval('('+fnc+')');
for(var i=0, l=docList.length; i<l; i++) {
try {
reducedVal = reducer(docList[i-1], docList[i]);
}
catch (err) {
continue;
}
}
return docList[docList.length - 1];
}
"""
)
ret_array = []
doc_list_copy = []
ret_array_copy = []
reduced_val = {}
doc_list = [doc for doc in self.find(condition)]
for doc in doc_list:
doc_copy = copy.deepcopy(doc)
for k in doc:
if isinstance(doc[k], ObjectId):
doc_copy[k] = str(doc[k])
if k not in key and k not in reduce:
del doc_copy[k]
for initial_key in initial:
if initial_key in doc.keys():
pass
else:
doc_copy[initial_key] = initial[initial_key]
doc_list_copy.append(doc_copy)
doc_list = doc_list_copy
for k in key:
doc_list = sorted(doc_list, key=lambda x: _resolve_key(k, x))
for k in key:
if not isinstance(k, basestring):
raise TypeError("Keys must be a list of key names, " "each an instance of %s" % (basestring.__name__,))
for k2, group in itertools.groupby(doc_list, lambda item: item[k]):
group_list = [x for x in group]
reduced_val = reduce_ctx.call("doReduce", reduce, group_list)
ret_array.append(reduced_val)
for doc in ret_array:
doc_copy = copy.deepcopy(doc)
for k in doc:
if k not in key and k not in initial.keys():
del doc_copy[k]
ret_array_copy.append(doc_copy)
ret_array = ret_array_copy
return ret_array
开发者ID:kevinmarceloph,项目名称:mongomock,代码行数:59,代码来源:collection.py
示例18: import_script
def import_script(self):
try:
local_file = bpy.data.texts[self.script_name].as_string()
ctx = execjs.compile(local_file)
self.set_node_function(ctx.call)
self.STATE = 'LOADED'
except:
self.STATE = 'UNLOADED'
print(self.STATE)
开发者ID:BitByte01,项目名称:myblendercontrib,代码行数:9,代码来源:prototyper_js.py
示例19: fixes
def fixes(wikitext):
wikitext = correctIPA(wikitext)
wikitext = removeDecl(wikitext)
wikitext = correctDecl(wikitext)
f = open("scripts/myscript/code.js", "r"); source = f.read(); f.close();
jscode = execjs.compile(source)
wikitext = jscode.call("clean", wikitext);
return wikitext
开发者ID:Dixtosa,项目名称:Wiktionary,代码行数:9,代码来源:source.py
示例20: eval_expression
def eval_expression(self, exp, data):
if exp is None:
return exp
res = re.search("\$\((.*)\)", exp)
if res:
ctx = execjs.compile("inputs = %s" % (json.dumps(data)))
return ctx.eval(res.group(1))
else:
return exp
开发者ID:bmeg,项目名称:cwllib,代码行数:9,代码来源:cwl-alt.py
注:本文中的execjs.compile函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论