prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>bar.js<|end_file_name|><|fim▁begin|>import shaven from 'shaven' const svgNS = 'http://www.w3.org/2000/svg' export default function (svg, config) { const yDensity = 0.1 const yRange = config.max.value - config.min.value const graphHeight = config.height * 0.8 const graphWidth = config.width * 0.95 const coSysHeight = config.height * 0.6 const coSysWidth = config.width * 0.85 const barchart = shaven( ['g', { transform: 'translate(' + [graphWidth * 0.1, graphHeight].join() + ')', }], svgNS, )[0] const coordinateSystem = shaven(['g'], svgNS)[0] const bars = shaven(['g'], svgNS)[0] function buildCoordinateSystem () { function ordinates () { let cssClass let index for (index = 0; index < config.size; index++) { cssClass = index === 0 ? 'vectual_coordinate_axis_y' : 'vectual_coordinate_lines_y' shaven( [coordinateSystem, ['line', { class: cssClass, x1: (coSysWidth / config.size) * index, y1: '5', x2: (coSysWidth / config.size) * index, y2: -coSysHeight, }], ['text', config.keys[index], { class: 'vectual_coordinate_labels_x', transform: 'rotate(40 ' + ((coSysWidth / config.size) * index) + ', 10)', // eslint-disable-next-line id-length x: (coSysWidth / config.size) * index, y: 10, // eslint-disable-line id-length }], ], svgNS, ) } } function abscissas () { let styleClass let index for (index = 0; index <= (yRange * yDensity); index++) { styleClass = index === 0 ? 'vectual_coordinate_axis_x' : 'vectual_coordinate_lines_x' shaven( [coordinateSystem, ['line', { class: styleClass, x1: -5, y1: -(coSysHeight / yRange) * (index / yDensity), x2: coSysWidth, y2: -(coSysHeight / yRange) * (index / yDensity), }], ['text', String(index / yDensity + config.min.value), { class: 'vectual_coordinate_labels_y', x: -coSysWidth * 0.05, // eslint-disable-line id-length // eslint-disable-next-line id-length y: -(coSysHeight / yRange) * (index / yDensity), }], ], svgNS, ) } } abscissas() ordinates() } function buildBars () { function drawBar (element, index) { const height = config.animations ? 0 : (config.values[index] - config.min.value) * (coSysHeight / yRange) const bar = shaven( ['rect', { class: 'vectual_bar_bar', // eslint-disable-next-line id-length x: index * (coSysWidth / config.size), // eslint-disable-next-line id-length y: -(config.values[index] - config.min.value) * (coSysHeight / yRange), height: height, width: 0.7 * (coSysWidth / config.size), }, ['title', config.keys[index] + ': ' + config.values[index]], ], svgNS,<|fim▁hole|> shaven( [bar, ['animate', { attributeName: 'height', to: (config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'y', from: 0, to: -(config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'fill', to: 'rgb(100,210,255)', begin: 'mouseover', dur: '100ms', fill: 'freeze', additive: 'replace', }], ['animate', { attributeName: 'fill', to: 'rgb(0,150,250)', begin: 'mouseout', dur: '200ms', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function localInject () { shaven([bars, [bar]]) } if (config.animations) localSetAnimations() localInject() } config.data.forEach(drawBar) } function setAnimations () { shaven( [bars, ['animate', { attributeName: 'opacity', from: 0, to: 0.8, begin: '0s', dur: '1s', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function inject () { shaven( [svg, [barchart, [coordinateSystem], [bars], ], ], ) } buildCoordinateSystem() buildBars() if (config.animations) setAnimations() inject() return svg }<|fim▁end|>
)[0] function localSetAnimations () {
<|file_name|>ajax.js<|end_file_name|><|fim▁begin|>/** * Ajax函数 */ // 创建一个XMLHttpRequest对象 var createXHR; if (window.XMLHttpRequest) { createXHR = function() { return new XMLHttpRequest(); }; } else if (window.ActiveXObject) { createXHR = function() { return new ActiveXObject('Microsoft.XMLHTTP'); };<|fim▁hole|>} // 发起异步请求,默认为GET请求 function ajax(url, opts) { var type = opts.type || 'get', async = opts.async || true, data = opts.data || null, headers = opts.headers || {}; var xhr = createXHR(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { opts.onsuccess && opts.onsuccess(xhr.responseText); } else { opts.onerror && opts.onerror(); } }; xhr.open(url, type, async); for (var p in headers) { xhr.setRequestHeader(p, headers[p]); } xhr.send(data); }<|fim▁end|>
<|file_name|>test_base.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import atexit import json import logging import os import subprocess import time from nose.tools import assert_true, assert_false from django.core.urlresolvers import reverse from django.contrib.auth.models import User from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.paths import get_run_root from desktop.lib.python_util import find_unused_port from desktop.lib.security_util import get_localhost_name from desktop.lib.test_utils import add_to_group, grant_access from hadoop import pseudo_hdfs4 from hadoop.pseudo_hdfs4 import is_live_cluster, get_db_prefix import beeswax.conf from beeswax.server.dbms import get_query_server_config from beeswax.server import dbms HIVE_SERVER_TEST_PORT = find_unused_port() _INITIALIZED = False _SHARED_HIVE_SERVER_PROCESS = None _SHARED_HIVE_SERVER = None _SHARED_HIVE_SERVER_CLOSER = None LOG = logging.getLogger(__name__) def _start_server(cluster): args = [beeswax.conf.HIVE_SERVER_BIN.get()] env = cluster._mr2_env.copy() hadoop_cp_proc = subprocess.Popen(args=[get_run_root('ext/hadoop/hadoop') + '/bin/hadoop', 'classpath'], env=env, cwd=cluster._tmpdir, stdout=subprocess.PIPE, stderr=subprocess.PIPE) hadoop_cp_proc.wait() hadoop_cp = hadoop_cp_proc.stdout.read().strip() env.update({ 'HADOOP_HOME': get_run_root('ext/hadoop/hadoop'), # Used only by Hive for some reason 'HIVE_CONF_DIR': beeswax.conf.HIVE_CONF_DIR.get(), 'HIVE_SERVER2_THRIFT_PORT': str(HIVE_SERVER_TEST_PORT), 'HADOOP_MAPRED_HOME': get_run_root('ext/hadoop/hadoop') + '/share/hadoop/mapreduce', # Links created in jenkins script. # If missing classes when booting HS2, check here. 'AUX_CLASSPATH': get_run_root('ext/hadoop/hadoop') + '/share/hadoop/hdfs/hadoop-hdfs.jar' + ':' + get_run_root('ext/hadoop/hadoop') + '/share/hadoop/common/lib/hadoop-auth.jar' + ':' + get_run_root('ext/hadoop/hadoop') + '/share/hadoop/common/hadoop-common.jar' + ':' + get_run_root('ext/hadoop/hadoop') + '/share/hadoop/mapreduce/hadoop-mapreduce-client-core.jar' , 'HADOOP_CLASSPATH': hadoop_cp, }) if os.getenv("JAVA_HOME"): env["JAVA_HOME"] = os.getenv("JAVA_HOME") LOG.info("Executing %s, env %s, cwd %s" % (repr(args), repr(env), cluster._tmpdir)) return subprocess.Popen(args=args, env=env, cwd=cluster._tmpdir, stdin=subprocess.PIPE) def get_shared_beeswax_server(db_name='default'): global _SHARED_HIVE_SERVER global _SHARED_HIVE_SERVER_CLOSER if _SHARED_HIVE_SERVER is None: cluster = pseudo_hdfs4.shared_cluster() if is_live_cluster(): def s(): pass else: s = _start_mini_hs2(cluster) start = time.time() started = False sleep = 1 make_logged_in_client() user = User.objects.get(username='test') query_server = get_query_server_config() db = dbms.get(user, query_server) while not started and time.time() - start <= 30: try: db.open_session(user) started = True break except Exception, e: LOG.info('HiveServer2 server could not be found after: %s' % e) time.sleep(sleep) if not started: raise Exception("Server took too long to come up.") _SHARED_HIVE_SERVER, _SHARED_HIVE_SERVER_CLOSER = cluster, s return _SHARED_HIVE_SERVER, _SHARED_HIVE_SERVER_CLOSER def _start_mini_hs2(cluster): HIVE_CONF = cluster.hadoop_conf_dir finish = ( beeswax.conf.HIVE_SERVER_HOST.set_for_testing(get_localhost_name()), beeswax.conf.HIVE_SERVER_PORT.set_for_testing(HIVE_SERVER_TEST_PORT),<|fim▁hole|> ) default_xml = """<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:derby:;databaseName=%(root)s/metastore_db;create=true</value> <description>JDBC connect string for a JDBC metastore</description> </property> <property> <name>hive.server2.enable.impersonation</name> <value>false</value> </property> <property> <name>hive.querylog.location</name> <value>%(querylog)s</value> </property> </configuration> """ % {'root': cluster._tmpdir, 'querylog': cluster.log_dir + '/hive'} file(HIVE_CONF + '/hive-site.xml', 'w').write(default_xml) global _SHARED_HIVE_SERVER_PROCESS if _SHARED_HIVE_SERVER_PROCESS is None: p = _start_server(cluster) LOG.info("started") cluster.fs.do_as_superuser(cluster.fs.chmod, '/tmp', 01777) _SHARED_HIVE_SERVER_PROCESS = p def kill(): LOG.info("Killing server (pid %d)." % p.pid) os.kill(p.pid, 9) p.wait() atexit.register(kill) def s(): for f in finish: f() cluster.stop() return s def wait_for_query_to_finish(client, response, max=60.0): # Take a async API execute_query() response in input start = time.time() sleep_time = 0.05 if is_finished(response): # aka Has error at submission return response content = json.loads(response.content) watch_url = content['watch_url'] response = client.get(watch_url, follow=True) # Loop and check status while not is_finished(response): time.sleep(sleep_time) sleep_time = min(1.0, sleep_time * 2) # Capped exponential if (time.time() - start) > max: message = "Query took too long! %d seconds" % (time.time() - start) LOG.warning(message) raise Exception(message) response = client.get(watch_url, follow=True) return response def is_finished(response): status = json.loads(response.content) return 'error' in status or status.get('isSuccess') or status.get('isFailure') def fetch_query_result_data(client, status_response, n=0, server_name='beeswax'): # Take a wait_for_query_to_finish() response in input status = json.loads(status_response.content) response = client.get("/%(server_name)s/results/%(id)s/%(n)s?format=json" % {'server_name': server_name, 'id': status.get('id'), 'n': n}) content = json.loads(response.content) return content def make_query(client, query, submission_type="Execute", udfs=None, settings=None, resources=None, wait=False, name=None, desc=None, local=True, is_parameterized=True, max=60.0, database='default', email_notify=False, params=None, server_name='beeswax', **kwargs): """ Prepares arguments for the execute view. If wait is True, waits for query to finish as well. """ if settings is None: settings = [] if params is None: params = [] if local: # Tests run faster if not run against the real cluster. settings.append(('mapreduce.framework.name', 'local')) # Prepares arguments for the execute view. parameters = { 'query-query': query, 'query-name': name if name else '', 'query-desc': desc if desc else '', 'query-is_parameterized': is_parameterized and "on", 'query-database': database, 'query-email_notify': email_notify and "on", } if submission_type == 'Execute': parameters['button-submit'] = 'Whatever' elif submission_type == 'Explain': parameters['button-explain'] = 'Whatever' elif submission_type == 'Save': parameters['saveform-save'] = 'True' if name: parameters['saveform-name'] = name if desc: parameters['saveform-desc'] = desc parameters["functions-next_form_id"] = str(len(udfs or [])) for i, udf_pair in enumerate(udfs or []): name, klass = udf_pair parameters["functions-%d-name" % i] = name parameters["functions-%d-class_name" % i] = klass parameters["functions-%d-_exists" % i] = 'True' parameters["settings-next_form_id"] = str(len(settings)) for i, settings_pair in enumerate(settings or []): key, value = settings_pair parameters["settings-%d-key" % i] = str(key) parameters["settings-%d-value" % i] = str(value) parameters["settings-%d-_exists" % i] = 'True' parameters["file_resources-next_form_id"] = str(len(resources or [])) for i, resources_pair in enumerate(resources or []): type, path = resources_pair parameters["file_resources-%d-type" % i] = str(type) parameters["file_resources-%d-path" % i] = str(path) parameters["file_resources-%d-_exists" % i] = 'True' for name, value in params: parameters["parameterization-%s" % name] = value kwargs.setdefault('follow', True) execute_url = reverse("%(server_name)s:api_execute" % {'server_name': server_name}) if submission_type == 'Explain': execute_url += "?explain=true" if submission_type == 'Save': execute_url = reverse("%(server_name)s:api_save_design" % {'server_name': server_name}) response = client.post(execute_url, parameters, **kwargs) if wait: return wait_for_query_to_finish(client, response, max) return response def verify_history(client, fragment, design=None, reverse=False, server_name='beeswax'): """ Verify that the query fragment and/or design are in the query history. If reverse is True, verify the opposite. Return the size of the history; -1 if we fail to determine it. """ resp = client.get('/%(server_name)s/query_history' % {'server_name': server_name}) my_assert = reverse and assert_false or assert_true my_assert(fragment in resp.content, resp.content) if design: my_assert(design in resp.content, resp.content) if resp.context: try: return len(resp.context['page'].object_list) except KeyError: pass LOG.warn('Cannot find history size. Response context clobbered') return -1 class BeeswaxSampleProvider(object): """ Setup the test db and install sample data """ @classmethod def setup_class(cls): cls.db_name = get_db_prefix(name='hive') cls.cluster, shutdown = get_shared_beeswax_server(cls.db_name) cls.client = make_logged_in_client(username='test', is_superuser=False) add_to_group('test') grant_access("test", "test", "beeswax") # Weird redirection to avoid binding nonsense. cls.shutdown = [ shutdown ] cls.init_beeswax_db() @classmethod def teardown_class(cls): if is_live_cluster(): # Delete test DB and tables client = make_logged_in_client() user = User.objects.get(username='test') query_server = get_query_server_config() db = dbms.get(user, query_server) for db_name in [cls.db_name, '%s_other' % cls.db_name]: databases = db.get_databases() if db_name in databases: tables = db.get_tables(database=db_name) for table in tables: make_query(client, 'DROP TABLE IF EXISTS `%(db)s`.`%(table)s`' % {'db': db_name, 'table': table}, wait=True) make_query(client, 'DROP VIEW IF EXISTS `%(db)s`.`myview`' % {'db': db_name}, wait=True) make_query(client, 'DROP DATABASE IF EXISTS %(db)s' % {'db': db_name}, wait=True) # Check the cleanup databases = db.get_databases() assert_false(db_name in databases) @classmethod def init_beeswax_db(cls): """ Install the common test tables (only once) """ global _INITIALIZED if _INITIALIZED: return make_query(cls.client, 'CREATE DATABASE IF NOT EXISTS %(db)s' % {'db': cls.db_name}, wait=True) make_query(cls.client, 'CREATE DATABASE IF NOT EXISTS %(db)s_other' % {'db': cls.db_name}, wait=True) data_file = cls.cluster.fs_prefix + u'/beeswax/sample_data_échantillon_%d.tsv' # Create a "test_partitions" table. CREATE_PARTITIONED_TABLE = """ CREATE TABLE `%(db)s`.`test_partitions` (foo INT, bar STRING) PARTITIONED BY (baz STRING, boom STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' """ % {'db': cls.db_name} make_query(cls.client, CREATE_PARTITIONED_TABLE, wait=True) cls._make_data_file(data_file % 1) LOAD_DATA = """ LOAD DATA INPATH '%(data_file)s' OVERWRITE INTO TABLE `%(db)s`.`test_partitions` PARTITION (baz='baz_one', boom='boom_two') """ % {'db': cls.db_name, 'data_file': data_file % 1} make_query(cls.client, LOAD_DATA, wait=True, local=False) # Insert additional partition data into "test_partitions" table ADD_PARTITION = """ ALTER TABLE `%(db)s`.`test_partitions` ADD PARTITION(baz='baz_foo', boom='boom_bar') LOCATION '%(fs_prefix)s/baz_foo/boom_bar' """ % {'db': cls.db_name, 'fs_prefix': cls.cluster.fs_prefix} make_query(cls.client, ADD_PARTITION, wait=True, local=False) # Create a bunch of other tables CREATE_TABLE = """ CREATE TABLE `%(db)s`.`%(name)s` (foo INT, bar STRING) COMMENT "%(comment)s" ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' """ # Create a "test" table. table_info = {'db': cls.db_name, 'name': 'test', 'comment': 'Test table'} cls._make_data_file(data_file % 2) cls._make_table(table_info['name'], CREATE_TABLE % table_info, data_file % 2) if is_live_cluster(): LOG.warn('HUE-2884: We cannot create Hive UTF8 tables when live cluster testing at the moment') else: # Create a "test_utf8" table. table_info = {'db': cls.db_name, 'name': 'test_utf8', 'comment': cls.get_i18n_table_comment()} cls._make_i18n_data_file(data_file % 3, 'utf-8') cls._make_table(table_info['name'], CREATE_TABLE % table_info, data_file % 3) # Create a "test_latin1" table. table_info = {'db': cls.db_name, 'name': 'test_latin1', 'comment': cls.get_i18n_table_comment()} cls._make_i18n_data_file(data_file % 4, 'latin1') cls._make_table(table_info['name'], CREATE_TABLE % table_info, data_file % 4) # Create a "myview" view. make_query(cls.client, "CREATE VIEW `%(db)s`.`myview` (foo, bar) as SELECT * FROM `%(db)s`.`test`" % {'db': cls.db_name}, wait=True) _INITIALIZED = True @staticmethod def get_i18n_table_comment(): return u'en-hello pt-Olá ch-你好 ko-안녕 ru-Здравствуйте' @classmethod def _make_table(cls, table_name, create_ddl, filename): make_query(cls.client, create_ddl, wait=True, database=cls.db_name) LOAD_DATA = """ LOAD DATA INPATH '%(filename)s' OVERWRITE INTO TABLE `%(db)s`.`%(table_name)s` """ % {'filename': filename, 'table_name': table_name, 'db': cls.db_name} make_query(cls.client, LOAD_DATA, wait=True, local=False, database=cls.db_name) @classmethod def _make_data_file(cls, filename): """ Create data to be loaded into tables. Data contains two columns of: <num> 0x<hex_num> where <num> goes from 0 to 255 inclusive. """ cls.cluster.fs.setuser(cls.cluster.superuser) f = cls.cluster.fs.open(filename, "w") for x in xrange(256): f.write("%d\t0x%x\n" % (x, x)) f.close() @classmethod def _make_i18n_data_file(cls, filename, encoding): """ Create i18n data to be loaded into tables. Data contains two columns of: <num> <unichr(num)> where <num> goes from 0 to 255 inclusive. """ cls.cluster.fs.setuser(cls.cluster.superuser) f = cls.cluster.fs.open(filename, "w") for x in xrange(256): f.write("%d\t%s\n" % (x, unichr(x).encode(encoding))) f.close() @classmethod def _make_custom_data_file(cls, filename, data): f = cls.cluster.fs.open(filename, "w") for x in data: f.write("%s\n" % x) f.close()<|fim▁end|>
beeswax.conf.HIVE_SERVER_BIN.set_for_testing(get_run_root('ext/hive/hive') + '/bin/hiveserver2'), beeswax.conf.HIVE_CONF_DIR.set_for_testing(HIVE_CONF)
<|file_name|>assignment2_true.py<|end_file_name|><|fim▁begin|>import pandas as pd import matplotlib.pyplot as plt import matplotlib import assignment2_helper as helper # Look pretty... matplotlib.style.use('ggplot') # Do * NOT * alter this line, until instructed! scaleFeatures = True # TODO: Load up the dataset and remove any and all # Rows that have a nan. You should be a pro at this # by now ;-) # # .. your code here original_df = pd.read_csv ('Datasets/kidney_disease.csv') new_df = original_df.dropna() # Create some color coded labels; the actual label feature # will be removed prior to executing PCA, since it's unsupervised. # You're only labeling by color so you can see the effects of PCA labels = ['red' if i=='ckd' else 'green' for i in new_df.classification] # TODO: Use an indexer to select only the following columns: # ['bgr','wc','rc'] # # .. your code here .. new_df.head() print new_df.columns.get_loc("bgr") print new_df.columns.get_loc("wc") print new_df.columns.get_loc("rc") df = new_df.iloc[:,[10,17,18]] df.head() # TODO: Print out and check your dataframe's dtypes. You'll probably # want to call 'exit()' after you print it out so you can stop the # program's execution. df.dtypes # You can either take a look at the dataset webpage in the attribute info # section: https://archive.ics.uci.edu/ml/datasets/Chronic_Kidney_Disease # or you can actually peek through the dataframe by printing a few rows. # What kind of data type should these three columns be? If Pandas didn't # properly detect and convert them to that data type for you, then use # an appropriate command to coerce these features into the right type. # # .. your code here .. df.wc=pd.to_numeric(df.iloc[:,1], errors='coerce') df.rc=pd.to_numeric(df.iloc[:,2], errors='coerce') # TODO: PCA Operates based on variance. The variable with the greatest # variance will dominate. Go ahead and peek into your data using a # command that will check the variance of every feature in your dataset. # Print out the results. Also print out the results of running .describe # on your dataset. df.describe() # Hint: If you don't see all three variables: 'bgr','wc' and 'rc', then # you probably didn't complete the previous step properly.<|fim▁hole|># # .. your code here .. # TODO: This method assumes your dataframe is called df. If it isn't, # make the appropriate changes. Don't alter the code in scaleFeatures() # just yet though! # # .. your code adjustment here .. if scaleFeatures: df = helper.scaleFeatures(df) # TODO: Run PCA on your dataset and reduce it to 2 components # Ensure your PCA instance is saved in a variable called 'pca', # and that the results of your transformation are saved in 'T'. # # .. your code here .. from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(df) T = pca.transform(df) # Plot the transformed data as a scatter plot. Recall that transforming # the data will result in a NumPy NDArray. You can either use MatPlotLib # to graph it directly, or you can convert it to DataFrame and have pandas # do it for you. # Since we've already demonstrated how to plot directly with MatPlotLib in # Module4/assignment1.py, this time we'll convert to a Pandas Dataframe. # # Since we transformed via PCA, we no longer have column names. We know we # are in P.C. space, so we'll just define the coordinates accordingly: ax = helper.drawVectors(T, pca.components_, df.columns.values, plt, scaleFeatures) T = pd.DataFrame(T) T.columns = ['component1', 'component2'] T.plot.scatter(x='component1', y='component2', marker='o', c=labels, alpha=0.75, ax=ax) plt.show()<|fim▁end|>
<|file_name|>group.rs<|end_file_name|><|fim▁begin|>//! Fuctions and Structs for dealing with /etc/group use std::path::Path; use std::num::ParseIntError; use libc::gid_t; use entries::{Entries,Entry}; /// An entry from /etc/group #[derive(Debug, PartialEq, PartialOrd)] pub struct GroupEntry { /// Group Name pub name: String, /// Group Password pub passwd: String, /// Group ID pub gid: gid_t, /// Group Members pub members: Vec<String>, } impl Entry for GroupEntry { fn from_line(line: &str) -> Result<GroupEntry, ParseIntError> { let parts: Vec<&str> = line.split(":").map(|part| part.trim()).collect(); let members: Vec<String> = match parts[3].len() { 0 => Vec::new(), _ => parts[3] .split(",") .map(|member| member.trim()) .map(|member| member.to_string()) .collect() }; Ok(GroupEntry { name: parts[0].to_string(), passwd: parts[1].to_string(), gid: try!(parts[2].parse()), members: members, }) } } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `uid` and `&Path` pub fn get_entry_by_gid_from_path(path: &Path, gid: gid_t) -> Option<GroupEntry> { Entries::<GroupEntry>::new(path).find(|x| x.gid == gid) } <|fim▁hole|>pub fn get_entry_by_gid(gid: gid_t) -> Option<GroupEntry> { get_entry_by_gid_from_path(&Path::new("/etc/group"), gid) } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `name` and `&Path` pub fn get_entry_by_name_from_path(path: &Path, name: &str) -> Option<GroupEntry> { Entries::<GroupEntry>::new(path).find(|x| x.name == name) } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `name` from `/etc/group` pub fn get_entry_by_name(name: &str) -> Option<GroupEntry> { get_entry_by_name_from_path(&Path::new("/etc/group"), name) } /// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all /// [`GroupEntry`](struct.GroupEntry.html)'s for a given `&Path` pub fn get_all_entries_from_path(path: &Path) -> Vec<GroupEntry> { Entries::new(path).collect() } /// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all /// [`GroupEntry`](struct.GroupEntry.html)'s from `/etc/group` pub fn get_all_entries() -> Vec<GroupEntry> { get_all_entries_from_path(&Path::new("/etc/group")) }<|fim▁end|>
/// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `uid` from `/etc/group`
<|file_name|>knight_tour.rs<|end_file_name|><|fim▁begin|>extern crate nalgebra as na; extern crate num; use na::DMatrix; use na::Scalar; use na::dimension::Dynamic; use std::fmt::Display; use num::FromPrimitive; const N: usize = 5; //map size N x N trait ChessFunc { fn isSafe(&self, x: isize, y: isize) -> bool; fn solveKTUtil( &mut self, x: isize, y: isize, movei: usize, moves: &Vec<(isize, isize)>, ) -> bool; fn printSolution(&self); fn solveKT(&mut self); } impl<S> ChessFunc for DMatrix<S> where S: Scalar + Display + FromPrimitive, { fn solveKT(&mut self) { let moves = [ (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1), ].to_vec(); //knight movement if self.solveKTUtil(0, 0, 1, &moves) { self.printSolution(); } else { println!("Solution does not exist"); } } fn solveKTUtil( &mut self, x: isize, y: isize, movei: usize, moves: &Vec<(isize, isize)>, ) -> bool { if movei == N * N { true } else {<|fim▁hole|> let next_x: isize = x + moves[cnt].0; let next_y: isize = y + moves[cnt].1; if self.isSafe(next_x, next_y) { unsafe { *self.get_unchecked_mut(next_x as usize, next_y as usize) = FromPrimitive::from_usize(movei).unwrap(); } if self.solveKTUtil(next_x, next_y, movei + 1, moves) { result = true; break; } else { unsafe { *self.get_unchecked_mut(next_x as usize, next_y as usize) = FromPrimitive::from_isize(-1).unwrap(); } } } } result } } fn printSolution(&self) { for (idx, item) in self.iter().enumerate() { print!("{position:>3}", position = item); if idx % N == (N - 1) { println!(); } } } fn isSafe(&self, x: isize, y: isize) -> bool { let mut result = false; //println!("({},{})", x, y); match ((x + 1) as usize, (y + 1) as usize) { (1...N, 1...N) => { match self.iter().nth((y * N as isize + x) as usize) { Some(sc) => { let temp: S = FromPrimitive::from_isize(-1).unwrap(); if temp == *sc { result = true; } } None => {} }; } _ => {} } //println!("({})", result); result } } fn main() { let DimN = Dynamic::new(N); //from nalgebra make dynamic dimension in here make N dimension let mut chessmap = DMatrix::from_fn_generic(DimN, DimN, |r, c| match (r, c) { (0, 0) => 0, _ => -1, }); //initialize matrix (0,0) set 0 and the others set -1 //chessmap.printSolution(); chessmap.solveKT(); //solve problum }<|fim▁end|>
let mut result = false; for cnt in 0..moves.len() {
<|file_name|>[email protected]<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
module.exports = require("npm:[email protected]/dist/acorn");
<|file_name|>s3.go<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed With this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package output import "reflect" // S3Grantee ... type S3Grantee struct { ID string `json:"id"` Type string `json:"type"` Permissions string `json:"permissions"` } // S3 represents an aws S3 bucket type S3 struct { ProviderType string `json:"_type"` DatacenterName string `json:"datacenter_name,omitempty"` DatacenterRegion string `json:"datacenter_region"` AccessKeyID string `json:"aws_access_key_id"` SecretAccessKey string `json:"aws_secret_access_key"` Name string `json:"name"` ACL string `json:"acl"` BucketLocation string `json:"bucket_location"` BucketURI string `json:"bucket_uri"` Grantees []S3Grantee `json:"grantees,omitempty"` Tags map[string]string `json:"tags"` Service string `json:"service"` Status string `json:"status"` Exists bool } // HasChanged diff's the two items and returns true if there have been any changes func (s *S3) HasChanged(os *S3) bool { if s.ACL != os.ACL { return true } if len(s.Grantees) < 1 && len(os.Grantees) < 1 { return false } return !reflect.DeepEqual(s.Grantees, os.Grantees) } // GetTags returns a components tags func (s S3) GetTags() map[string]string { return s.Tags } // ProviderID returns a components provider id func (s S3) ProviderID() string { return s.Name<|fim▁hole|> return s.Name }<|fim▁end|>
} // ComponentName returns a components name func (s S3) ComponentName() string {
<|file_name|>fix_temp_rescale.cpp<|end_file_name|><|fim▁begin|>/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include <string.h> #include <stdlib.h> #include <math.h> #include "fix_temp_rescale.h" #include "atom.h" #include "force.h" #include "group.h" #include "update.h" #include "domain.h" #include "region.h" #include "comm.h" #include "input.h" #include "variable.h" #include "modify.h" #include "compute.h" #include "error.h" using namespace LAMMPS_NS; using namespace FixConst; enum{NOBIAS,BIAS}; enum{CONSTANT,EQUAL}; /* ---------------------------------------------------------------------- */ FixTempRescale::FixTempRescale(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg), tstr(NULL), id_temp(NULL), tflag(0) { if (narg < 8) error->all(FLERR,"Illegal fix temp/rescale command"); nevery = force->inumeric(FLERR,arg[3]); if (nevery <= 0) error->all(FLERR,"Illegal fix temp/rescale command"); scalar_flag = 1; global_freq = nevery; extscalar = 1; tstr = NULL; if (strstr(arg[4],"v_") == arg[4]) { int n = strlen(&arg[4][2]) + 1; tstr = new char[n]; strcpy(tstr,&arg[4][2]); tstyle = EQUAL; } else { t_start = force->numeric(FLERR,arg[4]); t_target = t_start; tstyle = CONSTANT; } t_stop = force->numeric(FLERR,arg[5]); t_window = force->numeric(FLERR,arg[6]); fraction = force->numeric(FLERR,arg[7]); // create a new compute temp // id = fix-ID + temp, compute group = fix group int n = strlen(id) + 6; id_temp = new char[n]; strcpy(id_temp,id); strcat(id_temp,"_temp"); char **newarg = new char*[6]; newarg[0] = id_temp; newarg[1] = group->names[igroup]; newarg[2] = (char *) "temp"; modify->add_compute(3,newarg); delete [] newarg; tflag = 1; energy = 0.0; } /* ---------------------------------------------------------------------- */ FixTempRescale::~FixTempRescale() { delete [] tstr; // delete temperature if fix created it if (tflag) modify->delete_compute(id_temp); delete [] id_temp; } /* ---------------------------------------------------------------------- */ int FixTempRescale::setmask() { int mask = 0; mask |= END_OF_STEP; mask |= THERMO_ENERGY; return mask; } /* ---------------------------------------------------------------------- */ void FixTempRescale::init() { // check variable if (tstr) { tvar = input->variable->find(tstr); if (tvar < 0) error->all(FLERR,"Variable name for fix temp/rescale does not exist"); if (input->variable->equalstyle(tvar)) tstyle = EQUAL; else error->all(FLERR,"Variable for fix temp/rescale is invalid style"); } int icompute = modify->find_compute(id_temp); if (icompute < 0) error->all(FLERR,"Temperature ID for fix temp/rescale does not exist"); temperature = modify->compute[icompute]; if (temperature->tempbias) which = BIAS; else which = NOBIAS; } /* ---------------------------------------------------------------------- */ void FixTempRescale::end_of_step() { double t_current = temperature->compute_scalar(); // there is nothing to do, if there are no degrees of freedom if (temperature->dof < 1) return; // protect against division by zero if (t_current == 0.0) error->all(FLERR,"Computed temperature for fix temp/rescale cannot be 0.0"); double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; // set current t_target // if variable temp, evaluate variable, wrap with clear/add if (tstyle == CONSTANT) t_target = t_start + delta * (t_stop-t_start); else { modify->clearstep_compute(); t_target = input->variable->compute_equal(tvar); if (t_target < 0.0) error->one(FLERR, "Fix temp/rescale variable returned negative temperature"); modify->addstep_compute(update->ntimestep + nevery); } // rescale velocity of appropriate atoms if outside window // for BIAS: // temperature is current, so do not need to re-compute // OK to not test returned v = 0, since factor is multiplied by v if (fabs(t_current-t_target) > t_window) { t_target = t_current - fraction*(t_current-t_target); double factor = sqrt(t_target/t_current); double efactor = 0.5 * force->boltz * temperature->dof; double **v = atom->v; int *mask = atom->mask; int nlocal = atom->nlocal; energy += (t_current-t_target) * efactor; if (which == NOBIAS) { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { v[i][0] *= factor; v[i][1] *= factor; v[i][2] *= factor; } } } else { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { temperature->remove_bias(i,v[i]); v[i][0] *= factor; v[i][1] *= factor; v[i][2] *= factor; temperature->restore_bias(i,v[i]); } } } } } /* ---------------------------------------------------------------------- */ int FixTempRescale::modify_param(int narg, char **arg) { if (strcmp(arg[0],"temp") == 0) { if (narg < 2) error->all(FLERR,"Illegal fix_modify command"); if (tflag) { modify->delete_compute(id_temp); tflag = 0; } delete [] id_temp; int n = strlen(arg[1]) + 1;<|fim▁hole|> if (icompute < 0) error->all(FLERR,"Could not find fix_modify temperature ID"); temperature = modify->compute[icompute]; if (temperature->tempflag == 0) error->all(FLERR, "Fix_modify temperature ID does not compute temperature"); if (temperature->igroup != igroup && comm->me == 0) error->warning(FLERR,"Group for fix_modify temp != fix group"); return 2; } return 0; } /* ---------------------------------------------------------------------- */ void FixTempRescale::reset_target(double t_new) { t_target = t_start = t_stop = t_new; } /* ---------------------------------------------------------------------- */ double FixTempRescale::compute_scalar() { return energy; } /* ---------------------------------------------------------------------- extract thermostat properties ------------------------------------------------------------------------- */ void *FixTempRescale::extract(const char *str, int &dim) { if (strcmp(str,"t_target") == 0) { dim = 0; return &t_target; } return NULL; }<|fim▁end|>
id_temp = new char[n]; strcpy(id_temp,arg[1]); int icompute = modify->find_compute(id_temp);
<|file_name|>negation.py<|end_file_name|><|fim▁begin|>import os from pynsett.discourse import Discourse from pynsett.drt import Drs from pynsett.extractor import Extractor from pynsett.knowledge import Knowledge <|fim▁hole|>drs = Drs.create_from_natural_language(text) drs.plot() print(drs)<|fim▁end|>
_path = os.path.dirname(__file__) text = "John Smith is not blond"
<|file_name|>task.js<|end_file_name|><|fim▁begin|>/** @jsx html */ import { html } from '../../../snabbdom-jsx'; import Type from 'union-type'; import { bind, pipe, isBoolean, targetValue, targetChecked } from './helpers'; import { KEY_ENTER } from './constants'; // model : {id: Number, title: String, done: Boolean, editing: Boolean, editingValue: String } const Action = Type({ SetTitle : [String], Toggle : [isBoolean], StartEdit : [], CommitEdit : [String], CancelEdit : [] }); function onInput(handler, e) { if(e.keyCode === KEY_ENTER) handler(Action.CommitEdit(e.target.value)) } const view = ({model, handler, onRemove}) => <li key={model.id} class-completed={!!model.done && !model.editing} class-editing={model.editing}> <div selector=".view"> <input selector=".toggle" type="checkbox" checked={!!model.done} on-click={ pipe(targetChecked, Action.Toggle, handler) } /> <label on-dblclick={ bind(handler, Action.StartEdit()) }>{model.title}</label> <button selector=".destroy" on-click={onRemove} /> </div> <input selector=".edit" value={model.title} on-blur={ bind(handler, Action.CancelEdit()) } on-keydown={ bind(onInput, handler) } /> </li> function init(id, title) { return { id, title, done: false, editing: false, editingValue: '' }; } function update(task, action) { return Action.case({ Toggle : done => ({...task, done}), <|fim▁hole|> CancelEdit : title => ({...task, editing: false, editingValue: ''}) }, action); } export default { view, init, update, Action }<|fim▁end|>
StartEdit : () => ({...task, editing: true, editingValue: task.title}), CommitEdit : title => ({...task, title, editing: false, editingValue: ''}),
<|file_name|>0011_menuitem_menu_url.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from urllib.parse import urljoin, urlsplit from django.db import migrations, models def forwards(apps, schema_editor): MenuItem = apps.get_model('external_services', 'MenuItem') items = (MenuItem.objects.all() .exclude(service=None) .exclude(menu_url=None) .exclude(menu_url='')) errors = [] for item in items: uri1 = urlsplit(item.menu_url) uri2 = urlsplit(item.service.url) if uri1.netloc and uri1.netloc != uri2.netloc: errors.append(item) if errors: print() msg = ['Database is in inconsistent state.'] for item in errors: msg.append(" MenuItem(pk=%s): %s <> %s" % (item.pk, item.menu_url, item.service.url)) msg.append("For above menuitems, domain in MenuItem.menu_url doesn't match domain in MenuItem.service.url.") msg.append("Database is in inconsistent state. Manual fixing is required.") raise RuntimeError('\n'.join(msg)) for item in items: uri = urlsplit(item.menu_url) url = uri._replace(scheme='', netloc='').geturl()<|fim▁hole|> item.menu_url = url item.save(update_fields=['menu_url']) def backwards(apps, schema_editor): MenuItem = apps.get_model('external_services', 'MenuItem') for item in MenuItem.objects.all(): item.menu_url = urljoin(item.service.url, item.menu_url) item.save(update_fields=['menu_url']) class Migration(migrations.Migration): atomic = False dependencies = [ ('external_services', '0010_auto_20180918_1916'), ] operations = [ migrations.RunPython(forwards, backwards), ]<|fim▁end|>
<|file_name|>login.js<|end_file_name|><|fim▁begin|>if (!com) var com = {} if (!com.corejsf) { com.corejsf = { showProgress: function(data) { var inputId = data.source.id var progressbarId = inputId.substring(0, inputId.length - "name".length) + "pole"; if (data.status == "begin")<|fim▁hole|> Element.show(progressbarId); else if (data.status == "success") Element.hide(progressbarId); } } }<|fim▁end|>
<|file_name|>amount-store.ts<|end_file_name|><|fim▁begin|>import { Map, List, Iterable, Iterator } from 'immutable'; import { Amount, Metric } from './amount'; export interface AmountStore<K, V extends Metric> { store: Map<K, Amount<V>>; } export class AmountStore<K, V extends Metric> implements AmountStore<K, V> { constructor(store: Map<K, Amount<V>>) {<|fim▁hole|> this.store = store; } get(key: K):Amount<V> { return this.store.get(key); } set(key: K, value: Amount<V>):Map<K, Amount<V>> { return this.store.set(key, value); } getKeys():Iterator<K> { return this.store.keys(); } update(key: K, newValue: Amount<V>):Map<K, Amount<V>> { return this.store.update(key, value => newValue); } forEach(sideEffect: (value: Amount<V>, key: K, iter: Iterable<K, Amount<V>>) => any):number { return this.store.forEach(sideEffect); } getStore() { return this.store; } }<|fim▁end|>
<|file_name|>test_logging.py<|end_file_name|><|fim▁begin|>from agrc import logging import unittest import sys import datetime import os import shutil from mock import Mock, patch class LoggerTests(unittest.TestCase):<|fim▁hole|> def setUp(self): self.logger = logging.Logger() def tearDown(self): del self.logger def test_init(self): # should get the name of the script and date self.assertEqual(self.logger.log, os.path.split(sys.argv[0])[1] + ' || ' + datetime.datetime.now().strftime('%Y-%m-%d') + ' : ' + datetime.datetime.now().strftime('%I:%M %p') + ' || None') def test_log(self): # should append the log message original_length = len(self.logger.log) self.logger.logMsg(self.logTxt) self.assertGreater(self.logger.log.find(self.logTxt), original_length) @patch('agrc.logging.Logger.logMsg') @patch('arcpy.GetMessages') def test_logGPMsg(self, GetMessages_mock, logMsg_mock): # should call get messages on arcpy self.logger.logGPMsg() self.assertTrue(GetMessages_mock.called) self.assertTrue(logMsg_mock.called) def test_writeToLogFile(self): if os.path.exists(self.logger.logFolder): shutil.rmtree(self.logger.logFolder) self.logger.writeLogToFile() # should create folder for script self.assertTrue(os.path.exists(self.logger.logFolder)) def test_logError(self): self.logger.logMsg = Mock() self.logger.logError() self.assertTrue(self.logger.logMsg.called) if __name__ == '__main__': unittest.main()<|fim▁end|>
logTxt = 'test log text' erTxt = 'test error text'
<|file_name|>test_geopackage.py<|end_file_name|><|fim▁begin|># coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.** Contact : [email protected] .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ import unittest import sys from tempfile import mktemp from qgis.core import QgsVectorLayer, QgsRasterLayer from PyQt4.QtCore import QFileInfo from osgeo import gdal from safe.test.utilities import ( get_qgis_app, load_test_vector_layer, standard_data_path) QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app() from safe.datastore.geopackage import GeoPackage # Decorator for expecting fails in windows but not other OS's # Probably we should move this somewhere in utils for easy re-use...TS def expect_failure_in_windows(exception): """Marks test to expect a fail in windows - call assertRaises internally. ..versionadded:: 4.0.0 """ def test_decorator(fn): def test_decorated(self, *args, **kwargs): if sys.platform.startswith('win'): self.assertRaises(exception, fn, self, *args, **kwargs) return test_decorated return test_decorator class TestGeoPackage(unittest.TestCase): """Test the GeoPackage datastore.""" def setUp(self): pass def tearDown(self): pass @unittest.skipIf( int(gdal.VersionInfo('VERSION_NUM')) < 2000000, 'GDAL 2.0 is required for geopackage.') def test_create_geopackage(self): """Test if we can store geopackage.""" # Create a geopackage from an empty file. path = QFileInfo(mktemp() + '.gpkg') self.assertFalse(path.exists()) data_store = GeoPackage(path) path.refresh() self.assertTrue(path.exists()) # Let's add a vector layer. layer_name = 'flood_test' layer = standard_data_path('hazard', 'flood_multipart_polygons.shp') vector_layer = QgsVectorLayer(layer, 'Flood', 'ogr') result = data_store.add_layer(vector_layer, layer_name) self.assertTrue(result[0]) # We should have one layer. layers = data_store.layers() self.assertEqual(len(layers), 1) self.assertIn(layer_name, layers) # Add the same layer with another name. layer_name = 'another_vector_flood' result = data_store.add_layer(vector_layer, layer_name) self.assertTrue(result[0]) # We should have two layers. layers = data_store.layers() self.assertEqual(len(layers), 2) self.assertIn(layer_name, layers) # Test the URI of the new layer. expected = path.absoluteFilePath() + '|layername=' + layer_name self.assertEqual(data_store.layer_uri(layer_name), expected) # Test a fake layer. self.assertIsNone(data_store.layer_uri('fake_layer'))<|fim▁hole|> layer = standard_data_path('hazard', 'classified_hazard.tif') raster_layer = QgsRasterLayer(layer, layer_name) result = data_store.add_layer(raster_layer, layer_name) self.assertTrue(result[0]) # We should have 3 layers inside. layers = data_store.layers() self.assertEqual(len(layers), 3) # Check the URI for the raster layer. expected = 'GPKG:' + path.absoluteFilePath() + ':' + layer_name self.assertEqual(data_store.layer_uri(layer_name), expected) # Add a second raster. layer_name = 'big raster flood' self.assertTrue(data_store.add_layer(raster_layer, layer_name)) self.assertEqual(len(data_store.layers()), 4) # Test layer without geometry layer = load_test_vector_layer( 'gisv4', 'impacts', 'exposure_summary_table.csv') tabular_layer_name = 'breakdown' result = data_store.add_layer(layer, tabular_layer_name) self.assertTrue(result[0]) @unittest.skipIf( int(gdal.VersionInfo('VERSION_NUM')) < 2000000, 'GDAL 2.0 is required for geopackage.') @expect_failure_in_windows(AssertionError) def test_read_existing_geopackage(self): """Test we can read an existing geopackage.""" path = standard_data_path('other', 'jakarta.gpkg') import os path = os.path.normpath(os.path.normcase(os.path.abspath(path))) geopackage = QFileInfo(path) data_store = GeoPackage(geopackage) # We should have 3 layers in this geopackage. self.assertEqual(len(data_store.layers()), 3) # Test we can load a vector layer. roads = QgsVectorLayer( data_store.layer_uri('roads'), 'Test', 'ogr' ) self.assertTrue(roads.isValid()) # Test we can load a raster layers. # This currently fails on windows... # So we have decorated it with expected fail on windows # Should pass on other platforms. path = data_store.layer_uri('flood') flood = QgsRasterLayer(path, 'flood') self.assertTrue(flood.isValid()) if __name__ == '__main__': unittest.main()<|fim▁end|>
# Test to add a raster layer_name = 'raster_flood'
<|file_name|>pulse.py<|end_file_name|><|fim▁begin|>''' Pulse characterization Created Fri May 12 2017 @author: cpkmanchee ''' import numpy as np import os.path import inspect from beamtools.constants import h,c,pi from beamtools.common import normalize, gaussian, sech2, alias_dict from beamtools.import_data_file import import_data_file as _import from beamtools.import_data_file import objdict from scipy.optimize import curve_fit __all__ = ['spectrumFT', 'fit_ac', 'ac_x2t', 'sigma_fwhm'] class FitResult(): def __init__(self, ffunc, ftype, popt, pcov=0, indep_var='time'): self.ffunc = ffunc self.ftype = ftype self.popt = popt self.pcov = pcov self.iv=indep_var def subs(self,x): return self.ffunc(x,*self.popt) def get_args(self): return inspect.getargspec(self.ffunc) def spectrumFT(data,from_file = False, file_type='oo_spec', units_wl='nm', n_interp=0): '''Compute transform limited pulse from spectrum. data = wavelength vs. PSD (intensity) if from_file=False = filename of spectrum file to be imported if from_file=True Units assumed to be nm for wavelength. If from_file is set True, data should be filename Optional file_format, default is oceanoptics_spectrometer. Currently can not change this (filetype handling for x/y). n_interp = bit depth of frequency interpolation, n = 2**n_interp. 0 = auto ''' if from_file: if type(data) is str: if not os.path.exists(data): print('File does not exist') return -1 imported_data = _import(data,file_type) #insert testing for wavelength/intensity location in dataobject wavelength = imported_data.wavelength intensity = imported_data.intensity #get units from dataobject else: print('invalid filetype') return -1 else: wavelength = data[0] intensity = data[1] imported_data = data if n_interp == 0: #insert here later - round up to nearest power of two. n = 2**12 else: n = 2**12 #use units to convert wavelength to SI wl = wavelength*1E-9 psd = normalize(intensity) nu = c/wl #nu is SI #interpolate psd, linear freq spacing nui = np.linspace(min(nu),max(nu),n) df = (max(nu)-min(nu))/(n-1) psdi = normalize(np.interp(nui,np.flipud(nu),np.flipud(psd))) #i = (np.abs(nui-nu0)).argmin() #centre freq index #perform FT-1, remove centre spike t = np.fft.ifftshift(np.fft.fftfreq(n,df)[1:-1]) ac =np.fft.ifftshift((np.fft.ifft(np.fft.ifftshift(psdi)))[1:-1]) output_dict = {'time': t, 'ac': ac, 'nu': nui, 'psd': psdi} output = objdict(output_dict) return output, imported_data def ac_x2t(position,aoi=15,config='sym'): '''Convert autocorrelation position to time Symmetric - stage moves perp to normal. Asymmetric - stage moves along incoming optical axis ''' if type(config) is not str: print('Unrecognized configuration. Must be symmetric or asymmetric.') return position if config.lower() in alias_dict['symmetric']: time = (1/c)*position*2*np.cos(aoi*pi/180) elif config.lower() in alias_dict['asymmetric']: time = (1/c)*position*(1+np.cos(2*aoi*pi/180)) else: print('Unrecognized configuration. Must be symmetric or asymmetric.') return position return time def fit_ac(data, from_file = False, file_type='bt_ac', form='all', bgform = 'constant'): '''Fit autocorrelation peak. data must be either: 1. 2 x n array - data[0] = time(delay), data[1] = intensity 2. datafile name --> from_file must be True If there is no 'delay' parameter in data file (only position), the position is auto converted to time delay. ''' if from_file: if type(data) is str: if not os.path.exists(data): print('File does not exist') return -1 imported_data = _import(data,file_type) #insert testing for power location in dataobject position = imported_data.position intensity = imported_data.power if 'delay' in imported_data.__dict__: delay = imported_data.delay else: delay = ac_x2t(position,aoi=15,config='sym') #get units from dataobject else: print('invalid filetype') return -1 else: imported_data = data delay = data[0] intensity = data[1] x = delay y = intensity bgpar, bgform = _background(x,y,form = bgform) mean = np.average(x,weights = y) stdv = np.sqrt(np.average((x-mean)**2 ,weights = y)) #set fitting function (including background) if bgform is None: def fitfuncGaus(x,sigma,a,x0): return gaussian(x,sigma,a,x0) def fitfuncSech2(x,sigma,a,x0): return sech2(x,sigma,a,x0) if bgform.lower() in alias_dict['constant']: def fitfuncGaus(x,sigma,a,x0,p0): return gaussian(x,sigma,a,x0) + p0 def fitfuncSech2(x,sigma,a,x0,p0): return sech2(x,sigma,a,x0) + p0 elif bgform.lower() in alias_dict['linear']: def fitfuncGaus(x,sigma,a,x0,p0,p1): return gaussian(x,sigma,a,x0) + p1*x + p0 def fitfuncSech2(x,sigma,a,x0,p0,p1): return sech2(x,sigma,a,x0) + p1*x + p0 elif bgform.lower() in alias_dict['quadratic']: def fitfuncGaus(x,sigma,a,x0,p0,p1,p2): return gaussian(x,sigma,a,x0) + p2*x**2 + p1*x + p0 def fitfuncSech2(x,sigma,a,x0,p0,p1,p2): return sech2(x,sigma,a,x0) + p2*x**2 + p1*x + p0 else: def fitfuncGaus(x,sigma,a,x0): return gaussian(x,sigma,a,x0) def fitfuncSech2(x,sigma,a,x0): return sech2(x,sigma,a,x0) nFitArgs = len(inspect.getargspec(fitfuncGaus).args) - 1 #sets which functions are to be fit... this can be streamlined i think if form.lower() in ['both', 'all']: fitGaus = True fitSech2 = True elif form.lower() in alias_dict['gaus']: fitGaus = True fitSech2 = False elif form.lower() in alias_dict['sech2']: fitGaus = False fitSech2 = True else: print('Unknown fit form: '+form[0]) fitGaus = False fitSech2 = False #start fitting popt=[] pcov=[] fit_results=[] if type(bgpar) is np.float64: p0=[stdv,max(y)-min(y),mean,bgpar] elif type(bgpar) is np.ndarray: p0=[stdv,max(y)-min(y),mean]+bgpar.tolist() else: p0=None if fitGaus: try: poptGaus,pcovGaus = curve_fit(fitfuncGaus,x,y,p0) except RuntimeError: poptGaus = np.zeros(nFitArgs)<|fim▁hole|> popt.append(poptGaus) pcov.append(pcovGaus) fit_results.append(FitResult(ffunc=fitfuncGaus, ftype='gaussian', popt=poptGaus, pcov=pcovGaus)) if fitSech2: try: poptSech2,pcovSech2 = curve_fit(fitfuncSech2,x,y,p0) except RuntimeError: poptSech2 = np.zeros(nFitArgs) pcovSech2 = np.zeros((nFitArgs,nFitArgs)) popt.append(poptSech2) pcov.append(pcovSech2) fit_results.append(FitResult(ffunc=fitfuncSech2, ftype='sech2', popt=poptSech2, pcov=pcovSech2)) return fit_results, imported_data def sigma_fwhm(sigma, shape='gaus'): '''Convert sigma to full-width half-max ''' if shape.lower() in alias_dict['gaus']: A = 2*np.sqrt(2*np.log(2)) elif shape.lower() in alias_dict['sech2']: A = 2*np.arccosh(np.sqrt(2)) else: A = 1 return A*sigma def _background(x,y,form = 'constant'): '''Provides starting values for background parameters. Takes x,y data and the desired background form (default to constant) returns p, the polynomial coefficients. p is variable in length. ''' if form is None: p = np.zeros((3)) if form.lower() in ['const','constant']: p = min(y) #p = np.hstack((p,[0,0])) elif form.lower() in ['lin','linear']: p = np.linalg.solve([[1,x[0]],[1,x[-1]]], [y[0],y[-1]]) #p = np.hstack((p,0)) elif form.lower() in ['quad','quadratic']: index = np.argmin(y) if index == 0: x3 = 2*x[0]-x[-1] y3 = y[-1] elif index == len(y)-1: x3 = 2*x[-1]-x[0] y3 = y[0] else: x3 = x[index] y3 = y[index] a = [[1,x[0],x[0]**2],[1,x[-1],x[-1]**2],[1,x3,x3**2]] b = [y[0],y[-1],y3] p = np.linalg.solve(a,b) else: print('Unknown background form') p = np.zeros((3)) return p, form<|fim▁end|>
pcovGaus = np.zeros((nFitArgs,nFitArgs))
<|file_name|>bitcoin_ach.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ach" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;CoinsBazar Core&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+29"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The CoinsBazar Core developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+30"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>C&amp;lose</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+74"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="-41"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-27"/> <source>&amp;Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="-30"/> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Sending addresses</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Receiving addresses</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>These are your CoinsBazar addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>These are your CoinsBazar addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+194"/> <source>Export Address List</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>There was an error trying to save the address list to %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+168"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+40"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>CoinsBazar will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinsBazarGUI</name> <message> <location filename="../bitcoingui.cpp" line="+295"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+335"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-407"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="-137"/> <source>Node</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show information about CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Sending addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Receiving addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open &amp;URI...</source> <translation type="unfinished"/> </message> <message> <location line="+325"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-405"/> <source>Send coins to a CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="+430"/> <source>CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="-643"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+146"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your CoinsBazar addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified CoinsBazar addresses</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="-284"/> <location line="+376"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="-401"/> <source>CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+163"/> <source>Request payments (generates QR codes and bitcoin: URIs)</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <location line="+2"/> <source>&amp;About CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open a bitcoin: URI or payment request</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the CoinsBazar Core help message to get a list with possible CoinsBazar command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+159"/> <location line="+5"/> <source>CoinsBazar client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+142"/> <source>%n active connection(s) to CoinsBazar network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+23"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="-85"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+438"/> <source>A fatal error occurred. CoinsBazar can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+119"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+63"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+42"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+323"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>higher</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lower</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Dust</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+5"/> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+4"/> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <location line="-3"/> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <location line="+66"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/><|fim▁hole|> <location line="+10"/> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+28"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid CoinsBazar address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+65"/> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>name</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageDialog</name> <message> <location filename="../forms/helpmessagedialog.ui" line="+19"/> <source>CoinsBazar Core - Command-line options</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+38"/> <source>CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Welcome to CoinsBazar Core.</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where CoinsBazar Core will store its data.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>CoinsBazar Core will download and store a copy of the CoinsBazar block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+85"/> <source>CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OpenURIDialog</name> <message> <location filename="../forms/openuridialog.ui" line="+14"/> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>URI:</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <location filename="../openuridialog.cpp" line="+47"/> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start CoinsBazar after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start CoinsBazar on system login</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>MB</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Connect to the CoinsBazar network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <location line="+224"/> <source>Active command-line options that override above options:</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="-323"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the CoinsBazar client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting CoinsBazar.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show CoinsBazar addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only)</source> <translation type="unfinished"/> </message> <message> <location line="+136"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+67"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+75"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+29"/> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>This change would require a client restart.</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the CoinsBazar network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-155"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-83"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Confirmed:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+120"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+403"/> <location line="+13"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI can not be parsed! This can be caused by an invalid CoinsBazar address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+96"/> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <location line="-221"/> <location line="+212"/> <location line="+13"/> <location line="+95"/> <location line="+18"/> <location line="+16"/> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <location line="-353"/> <source>Cannot start bitcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Net manager warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation type="unfinished"/> </message> <message> <location line="+73"/> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+71"/> <location line="+11"/> <source>CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> </context> <context> <name>QRImageWidget</name> <message> <location filename="../receiverequestdialog.cpp" line="+36"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+359"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-223"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>General</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Name</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="+72"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-521"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="+206"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the CoinsBazar debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the CoinsBazar RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <location filename="../forms/receivecoinsdialog.ui" line="+83"/> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>An optional label to associate with the new receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the CoinsBazar network.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Requested payments</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Show</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Remove</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <location filename="../forms/receiverequestdialog.ui" line="+29"/> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location filename="../receiverequestdialog.cpp" line="+56"/> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <location filename="../recentrequeststablemodel.cpp" line="+24"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>(no message)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+381"/> <location line="+80"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+115"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-228"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <location line="+5"/> <location line="+5"/> <location line="+4"/> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <location line="-136"/> <source>Enter a CoinsBazar address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Total Amount %1 (= %2)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>or</source> <translation type="unfinished"/> </message> <message> <location line="+202"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+112"/> <source>Warning: Invalid CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Warning: Unknown change address</source> <translation type="unfinished"/> </message> <message> <location line="-366"/> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+131"/> <location line="+521"/> <location line="+536"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="-1152"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+30"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="+57"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-40"/> <source>This is a normal payment.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+524"/> <location line="+536"/> <source>Remove this entry</source> <translation type="unfinished"/> </message> <message> <location line="-1008"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>A message that was attached to the CoinsBazar URI which will be stored with the transaction for your reference. Note: This message will not be sent over the CoinsBazar network.</source> <translation type="unfinished"/> </message> <message> <location line="+958"/> <source>This is a verified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="-991"/> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <location line="+459"/> <source>This is an unverified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <location line="+532"/> <source>Pay To:</source> <translation type="unfinished"/> </message> <message> <location line="-498"/> <location line="+536"/> <source>Memo:</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a CoinsBazar address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> </context> <context> <name>ShutdownWindow</name> <message> <location filename="../utilitydialog.cpp" line="+48"/> <source>CoinsBazar Core is shutting down...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not shut down the computer until this window disappears.</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified CoinsBazar address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+29"/> <location line="+3"/> <source>Enter a CoinsBazar address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter CoinsBazar signature</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+28"/> <source>CoinsBazar Core</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>The CoinsBazar Core developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+79"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+28"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+53"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-125"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+53"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <location line="+9"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-232"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+234"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+16"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <location line="+25"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+62"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+57"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+142"/> <source>Export Transaction History</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the transaction history to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Exporting Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The transaction history was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletFrame</name> <message> <location filename="../walletframe.cpp" line="+26"/> <source>No wallet has been loaded.</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+245"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+43"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+181"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+221"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-51"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-148"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-36"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;CoinsBazar Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. CoinsBazar is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong CoinsBazar will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>CoinsBazar Core Daemon</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>CoinsBazar RPC client version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect to JSON-RPC on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Fee per kB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to CoinsBazar server</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Start CoinsBazar server</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Usage (deprecated, use bitcoin-cli):</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Wallet options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="-79"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-105"/> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>SSL options: (see the CoinsBazar Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-70"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-132"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+161"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of CoinsBazar</source> <translation type="unfinished"/> </message> <message> <location line="+98"/> <source>Wallet needed to be rewritten: restart CoinsBazar to complete</source> <translation type="unfinished"/> </message> <message> <location line="-100"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Unable to bind to %s on this computer. CoinsBazar is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+67"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
</message> <message>
<|file_name|>forex.service-spec.ts<|end_file_name|><|fim▁begin|>/// <reference path="../models/forexDeal.ts"/> /// <reference path="../services/forex.service.ts"/> 'use strict'; describe("forex api service", function(): void { var forexService: any, httpBackend: any; beforeEach(function (){ <|fim▁hole|> forexService = _ForexService_; httpBackend = $httpBackend; } run.$inject = ['$httpBackend', 'app.services.ForexService']; inject(run); }); it("getAll() gives the correct amount of ForexDeals", function() { httpBackend.when('GET', '/api/forex/dataretrieval').respond( [{ FOREX_DEAL_EXT_NR: 0, COMPANY_NR: 36, BANK_NR: 38, CLIENT_NR: 0, CLIENT_BANK_ABBR: "BNP ESPANA SA", P_S_CODE: "P", TRANSACTION_DATE: "2015-06-01T00:00:00", DUE_DATE: "2015-06-01T00:00:00", CURRENCY_NR: 2, CURRENCY_ABBR: "USD", AMOUNT_FOREIGN: 1.83671e-40, EXCHANGE_RATE: 5.51013e-40, SALE_AMOUNT_FOREIGN: -1.83671e-40, SALE_CURRENCY_ABBR: "EUR", SALE_EXCHANGE_RATE: 0, STATUS: 1, LINKED_FOREX_DEAL_EXT_NR: 0, BOOKING_PERIOD: 201506, TRADER_USER_NR: 389, USER_ABBR: "MADARIAGA, F.", TRADE_DEPARTMENT_NR: 57, DEPARTMENT_ABBR: "BO CU MADRID", CREATOR_ID: 1301, CREATION_DATE: "2015-06-08T16:11:25", APPROVE_USER: 1301, APPROVE_DATE: "2015-06-08T16:11:28", USAGE_FOR_ID: "G", HOME_CURRENCY_NR: 35, HOME_CURRENCY_ABBR: "EUR", COMPANY_ABBR_SHORT: "GSP", TRADE_ID: "70292749_0_0_0", UTI: "YCDYZNMZ3J70292749L0A0", FIXING_DATE: "0001-01-01T00:00:00", C_FORMAT_A: "#,##0.00;-#,##0.00;0.00;#" }, { FOREX_DEAL_EXT_NR: 0, COMPANY_NR: 36, BANK_NR: 38, CLIENT_NR: 0, CLIENT_BANK_ABBR: "BNP ESPANA SA", P_S_CODE: "P", TRANSACTION_DATE: "2015-06-01T00:00:00", DUE_DATE: "2015-06-01T00:00:00", CURRENCY_NR: 2, CURRENCY_ABBR: "USD", AMOUNT_FOREIGN: 1.83671e-40, EXCHANGE_RATE: 5.51013e-40, SALE_AMOUNT_FOREIGN: -1.83671e-40, SALE_CURRENCY_ABBR: "EUR", SALE_EXCHANGE_RATE: 0, STATUS: 1, LINKED_FOREX_DEAL_EXT_NR: 0, BOOKING_PERIOD: 201506, TRADER_USER_NR: 389, USER_ABBR: "MADARIAGA, F.", TRADE_DEPARTMENT_NR: 57, DEPARTMENT_ABBR: "BO CU MADRID", CREATOR_ID: 1301, CREATION_DATE: "2015-06-08T16:11:25", APPROVE_USER: 1301, APPROVE_DATE: "2015-06-08T16:11:28", USAGE_FOR_ID: "G", HOME_CURRENCY_NR: 35, HOME_CURRENCY_ABBR: "EUR", COMPANY_ABBR_SHORT: "GSP", TRADE_ID: "70292749_0_0_0", UTI: "YCDYZNMZ3J70292749L0A0", FIXING_DATE: "0001-01-01T00:00:00", C_FORMAT_A: "#,##0.00;-#,##0.00;0.00;#" }]); forexService.getAll().then(function(forexDeals: app.models.IForexDeal[]) { expect(forexDeals.length).toEqual(2); }); }); });<|fim▁end|>
module('app.services'); var run = function($httpBackend: any, _ForexService_: any) {
<|file_name|>general_neighbor_searching.cpp<|end_file_name|><|fim▁begin|>#include <CGAL/Epick_d.h> #include <CGAL/point_generators_d.h> #include <CGAL/Manhattan_distance_iso_box_point.h> #include <CGAL/K_neighbor_search.h> #include <CGAL/Search_traits_d.h> typedef CGAL::Epick_d<CGAL::Dimension_tag<4> > Kernel; typedef Kernel::Point_d Point_d; typedef CGAL::Random_points_in_cube_d<Point_d> Random_points_iterator; typedef Kernel::Iso_box_d Iso_box_d; typedef Kernel TreeTraits; typedef CGAL::Manhattan_distance_iso_box_point<TreeTraits> Distance; typedef CGAL::K_neighbor_search<TreeTraits, Distance> Neighbor_search; typedef Neighbor_search::Tree Tree; int main() { const int N = 1000; const unsigned int K = 10; Tree tree; Random_points_iterator rpit(4,1000.0); for(int i = 0; i < N; i++){ tree.insert(*rpit++); } Point_d pp(0.1,0.1,0.1,0.1); Point_d qq(0.2,0.2,0.2,0.2);<|fim▁hole|> Distance tr_dist; Neighbor_search N1(tree, query, 5, 10.0, false); // eps=10.0, nearest=false std::cout << "For query rectangle = [0.1, 0.2]^4 " << std::endl << "the " << K << " approximate furthest neighbors are: " << std::endl; for (Neighbor_search::iterator it = N1.begin();it != N1.end();it++) { std::cout << " Point " << it->first << " at distance " << tr_dist.inverse_of_transformed_distance(it->second) << std::endl; } return 0; }<|fim▁end|>
Iso_box_d query(pp,qq);
<|file_name|>Random_Forrest_Classification.py<|end_file_name|><|fim▁begin|>import pandas as pd<|fim▁hole|> url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] df = pd.read_csv(url, names=names) array = df.values X = array[:,0:8] y = array[:,8] seed = 21 num_trees = 100 max_features = 3 kfold = model_selection.KFold(n_splits=10, random_state=seed) model = RandomForestClassifier(n_estimators=num_trees, max_features=max_features) results = model_selection.cross_val_score(model, X, y, cv=kfold) print('results: ') print(results) print() print('mean: ' + str(results.mean()))<|fim▁end|>
from sklearn import model_selection from sklearn.ensemble import RandomForestClassifier
<|file_name|>yelp_polarity_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for yelp dataset module.""" from tensorflow_datasets import testing from tensorflow_datasets.text import yelp_polarity class YelpPolarityReviewsTest(testing.DatasetBuilderTestCase): DATASET_CLASS = yelp_polarity.YelpPolarityReviews SPLITS = { "train": 2, "test": 2, } if __name__ == "__main__":<|fim▁hole|><|fim▁end|>
testing.test_main()
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin from alert.donate.models import Donation from alert.userHandling.models import UserProfile class DonorInline(admin.TabularInline): model = UserProfile.donation.through max_num = 1 raw_id_fields = (<|fim▁hole|>class DonationAdmin(admin.ModelAdmin): readonly_fields = ( 'date_modified', 'date_created', ) list_display = ( '__str__', 'amount', 'payment_provider', 'status', 'date_created', 'referrer', ) list_filter = ( 'payment_provider', 'status', 'referrer', ) inlines = ( DonorInline, ) admin.site.register(Donation, DonationAdmin)<|fim▁end|>
'userprofile', )
<|file_name|>a04869.js<|end_file_name|><|fim▁begin|>var a04869 = [<|fim▁hole|> [ "Label", "a04869.html#ad4701118c2e75f005c1f7e4c53abb35d", null ], [ "List", "a04869.html#a848ab6ee611dbc860f80a47ecef2faa7", null ], [ "SampleCount", "a04869.html#aab481329945e65c4aeee79b145e4de51", null ] ];<|fim▁end|>
[ "font_sample_count", "a04869.html#af23335c4319e0c5f010380d9de8f5a6d", null ],
<|file_name|>UUIDsManager.cpp<|end_file_name|><|fim▁begin|>// Benoit 2011-05-16 #include <ros/node_handle.h> #include <ros/subscriber.h> #include <ros/rate.h> #include <eu_nifti_env_msg_ros/RequestForUUIDs.h> #include "NIFTiROSUtil.h" #include "UUIDsManager.h" namespace eu { namespace nifti { namespace ocu { const char* UUIDsManager::TOPIC = "/eoi/RequestForUUIDs"; const u_int UUIDsManager::NUM_REQUESTED(10); UUIDsManager* UUIDsManager::instance = NULL; UUIDsManager* UUIDsManager::getInstance() { if (instance == NULL) { instance = new UUIDsManager(); } return instance; } UUIDsManager::UUIDsManager() : wxThread(wxTHREAD_JOINABLE) , condition(mutexForCondition) , keepManaging(true) { } void UUIDsManager::stopManaging() { //printf("IN UUIDsManager::stopManaging \n"); keepManaging = false; if (instance != NULL) { instance->condition.Signal(); // Will make it go out of the main loop and terminate } //printf("OUT UUIDsManager::stopManaging \n"); } void* UUIDsManager::Entry() { //printf("%s\n", "UUIDsManager::Entry()"); ::ros::ServiceClient client = NIFTiROSUtil::getNodeHandle()->serviceClient<eu_nifti_env_msg_ros::RequestForUUIDs > (TOPIC); eu_nifti_env_msg_ros::RequestForUUIDs srv; srv.request.numRequested = NUM_REQUESTED; mutexForCondition.Lock(); // This must be called before the first wait() while (keepManaging) { //ROS_INFO("In the loop (keepManaging)"); // This is a requirement from wxThread // http://docs.wxwidgets.org/2.8/wx_wxthread.html#wxthreadtestdestroy if (TestDestroy()) break; if (!client.call(srv)) { std::cerr << "Failed to call ROS service \"RequestForUUIDs\"" << std::endl; //return 0; // Removed this on 2012-03-02 so that it would re-check the service every time, since CAST is unstable } else { //ROS_INFO("Got UUIDs"); { wxMutexLocker lock(instance->mutexForQueue); // Adds all new UUIDs to the list for (u_int i = 0; i < srv.response.uuids.size(); i++) { availableUUIDs.push(srv.response.uuids.at(i)); //std::cout << "Added " << srv.response.uuids.at(i) << std::endl; } } } // Waits until more ids are needed (signal will be called on the condition) //ROS_INFO("Before waiting"); condition.Wait(); //ROS_INFO("After waiting"); } return 0; } int UUIDsManager::getUUID() { //ROS_INFO("int UUIDsManager::getUUID()"); int uuid; { wxMutexLocker lock(instance->mutexForQueue); //ROS_INFO("Num left: %i/%i", instance->availableUUIDs.size(), NUM_REQUESTED); //ROS_INFO("Enough? %i", instance->availableUUIDs.size() <= NUM_REQUESTED / 2); assert(instance != NULL); // Requests more id's when the list is half empty if (instance->availableUUIDs.size() <= NUM_REQUESTED / 2) { //ROS_INFO("Will try waking up the thread to request UUIDs"); instance->condition.Signal(); if (instance->availableUUIDs.size() == 0) { throw "No UUID available"; } }<|fim▁hole|> } //ROS_INFO("int UUIDsManager::getUUID() returned %i. Num left: %i", uuid, instance->availableUUIDs.size()); return uuid; } } } }<|fim▁end|>
uuid = instance->availableUUIDs.front(); instance->availableUUIDs.pop();
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # ----------------------------------------------------------------------------- # Copyright (C) 2015 Daniel Standage <[email protected]> # # This file is part of tag (http://github.com/standage/tag) and is licensed # under the BSD 3-clause license: see LICENSE. # ----------------------------------------------------------------------------- """Package-wide configuration""" try: import __builtin__ as builtins except ImportError: # pragma: no cover import builtins from tag.comment import Comment from tag.directive import Directive from tag.feature import Feature from tag.sequence import Sequence from tag.range import Range from tag.reader import GFF3Reader from tag.writer import GFF3Writer from tag.score import Score from tag import bae from tag import cli from tag import index from tag import locus from tag import select from tag import transcript from gzip import open as gzopen import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions <|fim▁hole|> if mode not in ['r', 'w']: raise ValueError('invalid mode "{}"'.format(mode)) if filename in ['-', None]: # pragma: no cover filehandle = sys.stdin if mode == 'r' else sys.stdout return filehandle openfunc = builtins.open if filename.endswith('.gz'): openfunc = gzopen mode += 't' return openfunc(filename, mode)<|fim▁end|>
def open(filename, mode):
<|file_name|>FlowableFlatMapSingle.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.rxjava3.internal.operators.flowable; import java.util.Objects; import java.util.concurrent.atomic.*; import org.reactivestreams.*; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.disposables.*; import io.reactivex.rxjava3.exceptions.Exceptions; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.internal.disposables.DisposableHelper; import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; import io.reactivex.rxjava3.internal.util.*; import io.reactivex.rxjava3.operators.SpscLinkedArrayQueue; /** * Maps upstream values into SingleSources and merges their signals into one sequence. * @param <T> the source value type * @param <R> the result value type */ public final class FlowableFlatMapSingle<T, R> extends AbstractFlowableWithUpstream<T, R> { final Function<? super T, ? extends SingleSource<? extends R>> mapper; final boolean delayErrors; final int maxConcurrency; public FlowableFlatMapSingle(Flowable<T> source, Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayError, int maxConcurrency) { super(source); this.mapper = mapper; this.delayErrors = delayError; this.maxConcurrency = maxConcurrency; } @Override protected void subscribeActual(Subscriber<? super R> s) { source.subscribe(new FlatMapSingleSubscriber<>(s, mapper, delayErrors, maxConcurrency)); } static final class FlatMapSingleSubscriber<T, R> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = 8600231336733376951L; final Subscriber<? super R> downstream; final boolean delayErrors; final int maxConcurrency; final AtomicLong requested; final CompositeDisposable set; final AtomicInteger active; final AtomicThrowable errors; final Function<? super T, ? extends SingleSource<? extends R>> mapper; final AtomicReference<SpscLinkedArrayQueue<R>> queue; Subscription upstream; volatile boolean cancelled; FlatMapSingleSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayErrors, int maxConcurrency) { this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.maxConcurrency = maxConcurrency; this.requested = new AtomicLong(); this.set = new CompositeDisposable(); this.errors = new AtomicThrowable(); this.active = new AtomicInteger(1); this.queue = new AtomicReference<>(); } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { this.upstream = s; downstream.onSubscribe(this); int m = maxConcurrency; if (m == Integer.MAX_VALUE) { s.request(Long.MAX_VALUE); } else { s.request(maxConcurrency); } } } @Override public void onNext(T t) { SingleSource<? extends R> ms; try { ms = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.cancel(); onError(ex); return; } active.getAndIncrement(); InnerObserver inner = new InnerObserver(); if (!cancelled && set.add(inner)) { ms.subscribe(inner); } } @Override public void onError(Throwable t) { active.decrementAndGet(); if (errors.tryAddThrowableOrReport(t)) { if (!delayErrors) { set.dispose(); } drain(); } } @Override public void onComplete() { active.decrementAndGet(); drain(); } @Override public void cancel() { cancelled = true; upstream.cancel(); set.dispose(); errors.tryTerminateAndReport(); } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.add(requested, n); drain(); } } void innerSuccess(InnerObserver inner, R value) { set.delete(inner); if (get() == 0 && compareAndSet(0, 1)) { boolean d = active.decrementAndGet() == 0; if (requested.get() != 0) { downstream.onNext(value); SpscLinkedArrayQueue<R> q = queue.get(); if (d && (q == null || q.isEmpty())) { errors.tryTerminateConsumer(downstream); return; } BackpressureHelper.produced(requested, 1); if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(1); } } else { SpscLinkedArrayQueue<R> q = getOrCreateQueue(); synchronized (q) { q.offer(value); } } if (decrementAndGet() == 0) { return; } } else { SpscLinkedArrayQueue<R> q = getOrCreateQueue(); synchronized (q) { q.offer(value); } active.decrementAndGet(); if (getAndIncrement() != 0) { return; } } drainLoop(); } SpscLinkedArrayQueue<R> getOrCreateQueue() { SpscLinkedArrayQueue<R> current = queue.get(); if (current != null) { return current; } current = new SpscLinkedArrayQueue<>(Flowable.bufferSize()); if (queue.compareAndSet(null, current)) { return current; } return queue.get(); } void innerError(InnerObserver inner, Throwable e) { set.delete(inner); if (errors.tryAddThrowableOrReport(e)) { if (!delayErrors) { upstream.cancel(); set.dispose(); } else { if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(1); } } active.decrementAndGet(); drain(); } } void drain() { if (getAndIncrement() == 0) { drainLoop(); } } void clear() { SpscLinkedArrayQueue<R> q = queue.get(); if (q != null) { q.clear(); } } void drainLoop() { int missed = 1; Subscriber<? super R> a = downstream; AtomicInteger n = active; AtomicReference<SpscLinkedArrayQueue<R>> qr = queue; for (;;) { long r = requested.get(); long e = 0L; while (e != r) { if (cancelled) { clear(); return; } if (!delayErrors) { Throwable ex = errors.get(); if (ex != null) { clear(); errors.tryTerminateConsumer(downstream); return; } } boolean d = n.get() == 0; SpscLinkedArrayQueue<R> q = qr.get(); R v = q != null ? q.poll() : null; boolean empty = v == null; if (d && empty) { errors.tryTerminateConsumer(a); return; } if (empty) { break; } a.onNext(v); e++; } if (e == r) { if (cancelled) { clear(); return; } if (!delayErrors) { Throwable ex = errors.get(); if (ex != null) { clear(); errors.tryTerminateConsumer(a); return; } } boolean d = n.get() == 0; SpscLinkedArrayQueue<R> q = qr.get(); boolean empty = q == null || q.isEmpty(); if (d && empty) { errors.tryTerminateConsumer(a); return; } } if (e != 0L) { BackpressureHelper.produced(requested, e); if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(e); } } missed = addAndGet(-missed); if (missed == 0) { break; } } } final class InnerObserver extends AtomicReference<Disposable> implements SingleObserver<R>, Disposable { private static final long serialVersionUID = -502562646270949838L; @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public void onSuccess(R value) { innerSuccess(this, value); } @Override<|fim▁hole|> @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } @Override public void dispose() { DisposableHelper.dispose(this); } } } }<|fim▁end|>
public void onError(Throwable e) { innerError(this, e); }
<|file_name|>note-has-filtered-read.js<|end_file_name|><|fim▁begin|>import getNotes from './get-notes';<|fim▁hole|>export const noteHasFilteredRead = ( noteState, noteId ) => noteState.filteredNoteReads.includes( noteId ); export default ( state, noteId ) => noteHasFilteredRead( getNotes( state ), noteId );<|fim▁end|>
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
export * from './rpcServer';
<|file_name|>ValueSerdeFactoryTest.java<|end_file_name|><|fim▁begin|>/** * Copyright 2011-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.directio.hive.serde; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.math.BigDecimal; import java.sql.Timestamp; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.serde2.io.HiveCharWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable; import org.apache.hadoop.hive.serde2.io.TimestampWritable; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveCharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector; import org.apache.hadoop.io.Text; import org.junit.Test; import com.asakusafw.runtime.value.Date; import com.asakusafw.runtime.value.DateOption; import com.asakusafw.runtime.value.DateTime; import com.asakusafw.runtime.value.DateTimeOption; import com.asakusafw.runtime.value.DecimalOption; import com.asakusafw.runtime.value.StringOption; /** * Test for {@link ValueSerdeFactory}. */ public class ValueSerdeFactoryTest { /** * constants. */ @Test public void constants() { for (ValueSerdeFactory serde : ValueSerdeFactory.values()) { serde.getDriver(serde.getInspector()); } } /** * char. */ @Test public void getChar() { ValueSerde serde = ValueSerdeFactory.getChar(10); HiveCharObjectInspector inspector = (HiveCharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveChar value = new HiveChar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveCharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * varchar. */ @Test public void getVarchar() { ValueSerde serde = ValueSerdeFactory.getVarchar(10); HiveVarcharObjectInspector inspector = (HiveVarcharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveVarchar value = new HiveVarchar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); // HiveVarchar cannot compare by equals assertThat(inspector.getPrimitiveJavaObject(option).compareTo(value), is(0)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveVarcharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * qualified decimal. */ @Test public void getDecimal() { ValueSerde serde = ValueSerdeFactory.getDecimal(10, 2); HiveDecimalObjectInspector inspector = (HiveDecimalObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45"));<|fim▁hole|> assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveDecimalWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * decimal by string. */ @Test public void decimal_by_string() { ValueSerde serde = StringValueSerdeFactory.DECIMAL; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45")); String value = "123.45"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by string. */ @Test public void date_by_string() { ValueSerde serde = StringValueSerdeFactory.DATE; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); String value = "2014-07-01"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(2014, 7, 1, 12, 5, 59)); String value = "2014-07-01 12:05:59"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string_w_zeros() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(1, 1, 1, 0, 0, 0)); String value = "0001-01-01 00:00:00"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by timestamp. */ @SuppressWarnings("deprecation") @Test public void date_by_timestamp() { ValueSerde serde = TimestampValueSerdeFactory.DATE; TimestampObjectInspector inspector = (TimestampObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); Timestamp value = new Timestamp(2014 - 1900, 7 - 1, 1, 0, 0, 0, 0); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new TimestampWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } }<|fim▁end|>
HiveDecimal value = HiveDecimal.create(new BigDecimal("123.45")); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
<|file_name|>MSVSUserFile.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.4 # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Visual Studio user preferences file writer.""" import common import os import re import socket # for gethostname import xml.dom import xml_fix #------------------------------------------------------------------------------ def _FindCommandInPath(command): """If there are no slashes in the command given, this function searches the PATH env to find the given command, and converts it to an absolute path. We have to do this because MSVS is looking for an actual file to launch a debugger on, not just a command line. Note that this happens at GYP time, so anything needing to be built needs to have a full path.""" if '/' in command or '\\' in command: # If the command already has path elements (either relative or # absolute), then assume it is constructed properly. return command else: # Search through the path list and find an existing file that # we can access. paths = os.environ.get('PATH','').split(os.pathsep) for path in paths: item = os.path.join(path, command) if os.path.isfile(item) and os.access(item, os.X_OK): return item return command def _QuoteWin32CommandLineArgs(args): new_args = [] for arg in args: # Replace all double-quotes with double-double-quotes to escape # them for cmd shell, and then quote the whole thing if there # are any. if arg.find('"') != -1: arg = '""'.join(arg.split('"')) arg = '"%s"' % arg # Otherwise, if there are any spaces, quote the whole arg. elif re.search(r'[ \t\n]', arg): arg = '"%s"' % arg new_args.append(arg) return new_args class Writer(object): """Visual Studio XML user user file writer.""" def __init__(self, user_file_path, version): """Initializes the user file. Args: user_file_path: Path to the user file. """ self.user_file_path = user_file_path self.version = version self.doc = None def Create(self, name): """Creates the user file document. Args: name: Name of the user file. """ self.name = name # Create XML doc xml_impl = xml.dom.getDOMImplementation() self.doc = xml_impl.createDocument(None, 'VisualStudioUserFile', None) # Add attributes to root element self.n_root = self.doc.documentElement self.n_root.setAttribute('Version', self.version.ProjectVersion()) self.n_root.setAttribute('Name', self.name) # Add configurations section self.n_configs = self.doc.createElement('Configurations') self.n_root.appendChild(self.n_configs) def _AddConfigToNode(self, parent, config_type, config_name): """Adds a configuration to the parent node. Args: parent: Destination node. config_type: Type of configuration node. config_name: Configuration name. """ # Add configuration node and its attributes n_config = self.doc.createElement(config_type) n_config.setAttribute('Name', config_name) parent.appendChild(n_config) def AddConfig(self, name): """Adds a configuration to the project. Args: name: Configuration name. """ self._AddConfigToNode(self.n_configs, 'Configuration', name) def AddDebugSettings(self, config_name, command, environment = {}, working_directory=""): """Adds a DebugSettings node to the user file for a particular config. Args: command: command line to run. First element in the list is the executable. All elements of the command will be quoted if necessary. working_directory: other files which may trigger the rule. (optional) """ command = _QuoteWin32CommandLineArgs(command) n_cmd = self.doc.createElement('DebugSettings') abs_command = _FindCommandInPath(command[0]) n_cmd.setAttribute('Command', abs_command) n_cmd.setAttribute('WorkingDirectory', working_directory) n_cmd.setAttribute('CommandArguments', " ".join(command[1:])) n_cmd.setAttribute('RemoteMachine', socket.gethostname()) if environment and isinstance(environment, dict): n_cmd.setAttribute('Environment', " ".join(['%s="%s"' % (key, val) for (key,val) in environment.iteritems()])) else: n_cmd.setAttribute('Environment', '') n_cmd.setAttribute('EnvironmentMerge', 'true') # Currently these are all "dummy" values that we're just setting # in the default manner that MSVS does it. We could use some of<|fim▁hole|> # not have parity with other platforms then. n_cmd.setAttribute('Attach', 'false') n_cmd.setAttribute('DebuggerType', '3') # 'auto' debugger n_cmd.setAttribute('Remote', '1') n_cmd.setAttribute('RemoteCommand', '') n_cmd.setAttribute('HttpUrl', '') n_cmd.setAttribute('PDBPath', '') n_cmd.setAttribute('SQLDebugging', '') n_cmd.setAttribute('DebuggerFlavor', '0') n_cmd.setAttribute('MPIRunCommand', '') n_cmd.setAttribute('MPIRunArguments', '') n_cmd.setAttribute('MPIRunWorkingDirectory', '') n_cmd.setAttribute('ApplicationCommand', '') n_cmd.setAttribute('ApplicationArguments', '') n_cmd.setAttribute('ShimCommand', '') n_cmd.setAttribute('MPIAcceptMode', '') n_cmd.setAttribute('MPIAcceptFilter', '') # Find the config, and add it if it doesn't exist. found = False for config in self.n_configs.childNodes: if config.getAttribute("Name") == config_name: found = True if not found: self.AddConfig(config_name) # Add the DebugSettings onto the appropriate config. for config in self.n_configs.childNodes: if config.getAttribute("Name") == config_name: config.appendChild(n_cmd) break def Write(self, writer=common.WriteOnDiff): """Writes the user file.""" f = writer(self.user_file_path) self.doc.writexml(f, encoding='Windows-1252', addindent=' ', newl='\r\n') f.close() #------------------------------------------------------------------------------<|fim▁end|>
# these to add additional capabilities, I suppose, but they might
<|file_name|>taghelpers.py<|end_file_name|><|fim▁begin|>""" :Requirements: django-tagging This module contains some additional helper tags for the django-tagging project. Note that the functionality here might already be present in django-tagging but perhaps with some slightly different behaviour or usage. """ from django import template from django.core.urlresolvers import reverse as url_reverse from tagging.utils import parse_tag_input register = template.Library() class TagsForObjectNode(template.Node):<|fim▁hole|> self.last_junctor = last_junctor is None and ' and ' or last_junctor.lstrip('"').rstrip('"') self.urlname = urlname def render(self, context): tags = parse_tag_input(self.tags_string.resolve(context)) tags = ['<a href="%s" rel="tag">%s</a>' % (url_reverse(self.urlname, kwargs={'tag':t}), t) for t in tags] if len(tags) > 2: first_part = self.junctor.join(tags[:-1]) return first_part + self.last_junctor + tags[-1] if len(tags) == 2: return self.last_junctor.join(tags) return self.junctor.join(tags) @register.tag('object_tags') def tags_for_object(parser, token): """ Simple tag for rendering tags of an object Usage:: {% object_tags object.tags blog-tag ", " " and " %} The last two arguments determine the junctor between the tag names with the last being the last junctor being used. """ variables = token.split_contents()[1:] return TagsForObjectNode(*variables)<|fim▁end|>
def __init__(self, tags_string, urlname, junctor=None, last_junctor=None): self.tags_string = template.Variable(tags_string) self.junctor = junctor is None and ', ' or junctor.lstrip('"').rstrip('"')
<|file_name|>F.rs<|end_file_name|><|fim▁begin|>#![allow(unused_imports)] use std::cmp::*; use std::collections::*; struct Scanner { buffer : std::collections::VecDeque<String> } impl Scanner { fn new() -> Scanner { Scanner { buffer: std::collections::VecDeque::new() } } fn next<T : std::str::FromStr >(&mut self) -> T { <|fim▁hole|> self.buffer.push_back(word.to_string()) } } let front = self.buffer.pop_front().unwrap(); front.parse::<T>().ok().unwrap() } } fn main() { let mut s = Scanner::new(); let n : usize = s.next(); println!("{}",n); }<|fim▁end|>
if self.buffer.len() == 0 { let mut input = String::new(); std::io::stdin().read_line(&mut input).ok(); for word in input.split_whitespace() {
<|file_name|>layout_interface.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to layout. Using this abstract //! interface helps reduce coupling between these two components, and enables //! the DOM to be placed in a separate crate from layout. use dom::node::LayoutData; use euclid::point::Point2D; use euclid::rect::Rect; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use libc::uintptr_t; use msg::compositor_msg::LayerId; use msg::constellation_msg::{ConstellationChan, Failure, PipelineExitType, PipelineId}; use msg::constellation_msg::{WindowSizeData}; use msg::compositor_msg::Epoch; use net_traits::image_cache_task::ImageCacheTask; use net_traits::PendingAsyncLoad; use profile_traits::mem::ReportsChan; use script_traits::{ConstellationControlMsg, LayoutControlMsg}; use script_traits::{OpaqueScriptLayoutChannel, StylesheetLoadResponder, UntrustedNodeAddress}; use selectors::parser::PseudoElement; use std::any::Any; use std::sync::mpsc::{channel, Receiver, Sender}; use string_cache::Atom; use style::animation::PropertyAnimation; use style::media_queries::MediaQueryList; use style::stylesheets::Stylesheet; use url::Url; use util::geometry::Au; pub use dom::node::TrustedNodeAddress; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. AddStylesheet(Stylesheet, MediaQueryList), /// Adds the given stylesheet to the document. LoadStylesheet(Url, MediaQueryList, PendingAsyncLoad, Box<StylesheetLoadResponder+Send>), /// Puts a document into quirks mode, causing the quirks mode stylesheet to be loaded. SetQuirksMode, /// Requests a reflow. Reflow(Box<ScriptReflow>), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout task render the next frame of all animations. TickAnimations, /// Updates the layout visible rects, affecting the area that display lists will be constructed /// for. SetVisibleRects(Vec<(LayerId, Rect<Au>)>), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapLayoutData(LayoutData), /// Requests that the layout task measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout task enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout task immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow(PipelineExitType), /// Get the last epoch counter for this layout task. GetCurrentEpoch(IpcSender<Epoch>), /// Creates a new layout task. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutTask(NewLayoutTaskInfo), } /// Synchronous messages that script can send to layout. /// /// In general, you should use messages to talk to Layout. Use the RPC interface /// if and only if the work is /// /// 1) read-only with respect to LayoutTaskData, /// 2) small, /// 3) and really needs to be fast. pub trait LayoutRPC { /// Requests the dimensions of the content box, as in the `getBoundingClientRect()` call. fn content_box(&self) -> ContentBoxResponse; /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call. fn content_boxes(&self) -> ContentBoxesResponse; /// Requests the geometry of this node. Used by APIs such as `clientTop`. fn node_geometry(&self) -> NodeGeometryResponse; /// Requests the node containing the point of interest fn hit_test(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<HitTestResponse, ()>; fn mouse_over(&self, node: TrustedNodeAddress, point: Point2D<f32>) -> Result<MouseOverResponse, ()>; /// Query layout for the resolved value of a given CSS property fn resolved_style(&self) -> ResolvedStyleResponse; fn offset_parent(&self) -> OffsetParentResponse; } pub struct ContentBoxResponse(pub Rect<Au>); pub struct ContentBoxesResponse(pub Vec<Rect<Au>>); pub struct NodeGeometryResponse { pub client_rect: Rect<i32>,<|fim▁hole|>pub struct HitTestResponse(pub UntrustedNodeAddress); pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>); pub struct ResolvedStyleResponse(pub Option<String>); #[derive(Clone)] pub struct OffsetParentResponse { pub node_address: Option<UntrustedNodeAddress>, pub rect: Rect<Au>, } impl OffsetParentResponse { pub fn empty() -> OffsetParentResponse { OffsetParentResponse { node_address: None, rect: Rect::zero(), } } } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, } /// Any query to perform with this reflow. #[derive(PartialEq)] pub enum ReflowQueryType { NoQuery, ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, Atom), OffsetParentQuery(TrustedNodeAddress), } /// Information needed for a reflow. pub struct Reflow { /// The goal of reflow: either to render to the screen or to flush layout info for script. pub goal: ReflowGoal, /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document_root: TrustedNodeAddress, /// The channel through which messages can be sent back to the script task. pub script_chan: Sender<ConstellationControlMsg>, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<()>, /// Unique identifier pub id: u32, /// The type of query if any to perform during this reflow. pub query_type: ReflowQueryType, } /// Encapsulates a channel to the layout task. #[derive(Clone)] pub struct LayoutChan(pub Sender<Msg>); impl LayoutChan { pub fn new() -> (Receiver<Msg>, LayoutChan) { let (chan, port) = channel(); (port, LayoutChan(chan)) } } /// A trait to manage opaque references to script<->layout channels without needing /// to expose the message type to crates that don't need to know about them. pub trait ScriptLayoutChan { fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> Self; fn sender(&self) -> Sender<Msg>; fn receiver(self) -> Receiver<Msg>; } impl ScriptLayoutChan for OpaqueScriptLayoutChannel { fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> OpaqueScriptLayoutChannel { let inner = (box sender as Box<Any+Send>, box receiver as Box<Any+Send>); OpaqueScriptLayoutChannel(inner) } fn sender(&self) -> Sender<Msg> { let &OpaqueScriptLayoutChannel((ref sender, _)) = self; (*sender.downcast_ref::<Sender<Msg>>().unwrap()).clone() } fn receiver(self) -> Receiver<Msg> { let OpaqueScriptLayoutChannel((_, receiver)) = self; *receiver.downcast::<Receiver<Msg>>().unwrap() } } /// Type of an opaque node. pub type OpaqueNode = uintptr_t; /// State relating to an animation. #[derive(Clone)] pub struct Animation { /// An opaque reference to the DOM node participating in the animation. pub node: OpaqueNode, /// A description of the property animation that is occurring. pub property_animation: PropertyAnimation, /// The start time of the animation, as returned by `time::precise_time_s()`. pub start_time: f64, /// The end time of the animation, as returned by `time::precise_time_s()`. pub end_time: f64, } impl Animation { /// Returns the duration of this animation in seconds. #[inline] pub fn duration(&self) -> f64 { self.end_time - self.start_time } } pub struct NewLayoutTaskInfo { pub id: PipelineId, pub url: Url, pub is_parent: bool, pub layout_pair: OpaqueScriptLayoutChannel, pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: ConstellationChan, pub failure: Failure, pub script_chan: Sender<ConstellationControlMsg>, pub image_cache_task: ImageCacheTask, pub paint_chan: Box<Any + Send>, pub layout_shutdown_chan: Sender<()>, }<|fim▁end|>
}
<|file_name|>inOutSelector.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ *************************************************************************** inOutSelector.py --------------------- Date : April 2011 Copyright : (C) 2011 by Giuseppe Sucameli Email : brush dot tyler at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Giuseppe Sucameli' __date__ = 'April 2011' __copyright__ = '(C) 2011, Giuseppe Sucameli' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from PyQt4.QtCore import SIGNAL, Qt, pyqtProperty from PyQt4.QtGui import QWidget, QComboBox from qgis.core import QgsMapLayerRegistry, QgsMapLayer from ui_inOutSelector import Ui_GdalToolsInOutSelector class GdalToolsInOutSelector(QWidget, Ui_GdalToolsInOutSelector): FILE = 0x1 LAYER = 0x2 MULTIFILE = 0x4 # NOT IMPLEMENTED YET FILE_LAYER = 0x1|0x2 FILES = 0x1|0x4 # NOT IMPLEMENTED YET FILES_LAYER = 0x3|0x4 # NOT IMPLEMENTED YET __pyqtSignals__ = ("selectClicked()", "filenameChanged(), layerChanged()") def __init__(self, parent=None, type=None): QWidget.__init__(self, parent) self.setupUi(self) self.setFocusPolicy(Qt.StrongFocus) self.combo.setInsertPolicy(QComboBox.NoInsert) self.clear() self.typ = None if type is None: self.resetType() else: self.setType(type)<|fim▁hole|> self.connect(self.fileEdit, SIGNAL("textChanged(const QString &)"), self.textChanged) self.connect(self.combo, SIGNAL("editTextChanged(const QString &)"), self.textChanged) self.connect(self.combo, SIGNAL("currentIndexChanged(int)"), self.indexChanged) def clear(self): self.filenames = [] self.fileEdit.clear() self.clearComboState() self.combo.clear() def textChanged(self): if self.getType() & self.MULTIFILE: self.filenames = self.fileEdit.text().split(",") if self.getType() & self.LAYER: index = self.combo.currentIndex() if index >= 0: text = self.combo.currentText() if text != self.combo.itemText( index ): return self.setFilename( text ) self.filenameChanged() def indexChanged(self): self.layerChanged() self.filenameChanged() def selectButtonClicked(self): self.emit(SIGNAL("selectClicked()")) def filenameChanged(self): self.emit(SIGNAL("filenameChanged()")) def layerChanged(self): self.emit(SIGNAL("layerChanged()")) def setType(self, type): if type == self.typ: return if type & self.MULTIFILE: # MULTITYPE IS NOT IMPLEMENTED YET type = type & ~self.MULTIFILE self.typ = type self.selectBtn.setVisible( self.getType() & self.FILE ) self.combo.setVisible( self.getType() & self.LAYER ) self.fileEdit.setVisible( not (self.getType() & self.LAYER) ) self.combo.setEditable( self.getType() & self.FILE ) if self.getType() & self.FILE: self.setFocusProxy(self.selectBtn) else: self.setFocusProxy(self.combo) # send signals to refresh connected widgets self.filenameChanged() self.layerChanged() def getType(self): return self.typ def resetType(self): self.setType( self.FILE_LAYER ) selectorType = pyqtProperty("int", getType, setType, resetType) def setFilename(self, fn=None): self.blockSignals( True ) prevFn, prevLayer = self.filename(), self.layer() if isinstance(fn, QgsMapLayer): fn = fn.source() elif isinstance(fn, str) or isinstance(fn, unicode): fn = unicode( fn ) # TODO test elif isinstance(fn, list): if len( fn ) > 0: if self.getType() & self.MULTIFILE: self.filenames = fn #fn = "".join( fn, "," ) fn = ",".join( fn ) else: fn = '' else: fn = '' if not (self.getType() & self.LAYER): self.fileEdit.setText( fn ) else: self.combo.setCurrentIndex(-1) self.combo.setEditText( fn ) self.blockSignals( False ) if self.filename() != prevFn: self.filenameChanged() if self.layer() != prevLayer: self.layerChanged() def setLayer(self, layer=None): if not (self.getType() & self.LAYER): return self.setFilename( layer ) self.blockSignals( True ) prevFn, prevLayer = self.filename(), self.layer() if isinstance(layer, QgsMapLayer): if self.combo.findData(layer.id()) >= 0: index = self.combo.findData( layer.id() ) self.combo.setCurrentIndex( index ) else: self.combo.setCurrentIndex( -1 ) self.combo.setEditText( layer.source() ) elif isinstance(layer, int) and layer >= 0 and layer < self.combo.count(): self.combo.setCurrentIndex( layer ) else: self.combo.clearEditText() self.combo.setCurrentIndex(-1) self.blockSignals( False ) if self.filename() != prevFn: self.filenameChanged() if self.layer() != prevLayer: self.layerChanged() def setLayers(self, layers=None): if layers is None or not hasattr(layers, '__iter__') or len(layers) <= 0: self.combo.clear() return self.blockSignals( True ) prevFn, prevLayer = self.filename(), self.layer() self.saveComboState() self.combo.clear() for l in layers: self.combo.addItem( l.name(), l.id() ) self.restoreComboState() self.blockSignals( False ) if self.filename() != prevFn: self.filenameChanged() if self.layer() != prevLayer: self.layerChanged() def clearComboState(self): self.prevState = None def saveComboState(self): index = self.combo.currentIndex() text = self.combo.currentText() layerID = self.combo.itemData(index) if index >= 0 else "" self.prevState = ( index, text, layerID ) def restoreComboState(self): if self.prevState is None: return index, text, layerID = self.prevState if index < 0: if text == '' and self.combo.count() > 0: index = 0 elif self.combo.findData( layerID ) < 0: index = -1 text = "" else: index = self.combo.findData( layerID ) self.combo.setCurrentIndex( index ) if index >= 0: text = self.combo.itemText( index ) self.combo.setEditText( text ) def layer(self): if self.getType() != self.FILE and self.combo.currentIndex() >= 0: layerID = self.combo.itemData(self.combo.currentIndex()) return QgsMapLayerRegistry.instance().mapLayer( layerID ) return None def filename(self): if not (self.getType() & self.LAYER): if self.getType() & self.MULTIFILE: return self.filenames return self.fileEdit.text() if self.combo.currentIndex() < 0: if self.getType() & self.MULTIFILE: return self.filenames return self.combo.currentText() layer = self.layer() if layer is not None: return layer.source() return ''<|fim▁end|>
self.connect(self.selectBtn, SIGNAL("clicked()"), self.selectButtonClicked)
<|file_name|>camera.rs<|end_file_name|><|fim▁begin|>use corange::*; #[derive(Clone)] pub enum CameraType { Manual, Orbit, Free, } #[derive(Clone)] pub struct Camera { pub position: vec3, pub target: vec3, pub fov: f32, pub near_clip: f32, pub far_clip: f32, pub movement: CameraType, pub frame: u64 } <|fim▁hole|> fn default() -> Camera { unsafe { Camera { movement: CameraType::Free, position: vec3_new(10.0, 10.0, 10.0), target: vec3_zero(), far_clip: 512.0, near_clip: 0.10, fov: 0.78, frame: 0 } } } } impl Camera { pub fn apply(self, camera:*mut camera) { unsafe { (*camera).position = self.position; (*camera).target = self.target; (*camera).far_clip = self.far_clip; (*camera).near_clip = self.near_clip; (*camera).fov = self.fov; } } }<|fim▁end|>
impl Default for Camera {
<|file_name|>SimpleCommandBus.spec.ts<|end_file_name|><|fim▁begin|>import * as sinon from "sinon"; import * as chai from "chai";<|fim▁hole|>import {CommandHandler} from "../../../main/Apha/CommandHandling/CommandHandler"; import {Command} from "../../../main/Apha/Message/Command"; import {NoCommandHandlerException} from "../../../main/Apha/CommandHandling/NoCommandHandlerException"; import {CommandHandlerAlreadyExistsException} from "../../../main/Apha/CommandHandling/CommandHandlerAlreadyExistsException"; chai.use(chaiAsPromised); describe("SimpleCommandBus", () => { let commandBus; beforeEach(() => { commandBus = new SimpleCommandBus(); }); describe("handle", () => { it("handles command by registered handler", (done) => { const command = new SimpleCommandBusCommand(); const handler = new SimpleCommandBusCommandHandler(); const handlerMock = sinon.mock(handler); handlerMock.expects("handle").once().withArgs(command); commandBus.registerHandler(SimpleCommandBusCommand, handler); commandBus.send(command).then(() => { handlerMock.verify(); done(); }); }); it("throws exception if command cannot be handled", (done) => { const command = new SimpleCommandBusCommand(); expect(commandBus.send(command)).to.be.rejectedWith(NoCommandHandlerException).and.notify(done); }); }); describe("registerHandler", () => { it("throws exception if a handler is already registered for a command type", () => { const handler1 = new SimpleCommandBusCommandHandler(); const handler2 = new SimpleCommandBusCommandHandler(); commandBus.registerHandler(SimpleCommandBusCommand, handler1); expect(() => { commandBus.registerHandler(SimpleCommandBusCommand, handler2); }).to.throw(CommandHandlerAlreadyExistsException); }); }); describe("unregisterHandler", () => { it("unregisters a handler by command type", (done) => { const command = new SimpleCommandBusCommand(); const handler = new SimpleCommandBusCommandHandler(); const handlerMock = sinon.mock(handler); handlerMock.expects("handle").never(); commandBus.registerHandler(SimpleCommandBusCommand, handler); commandBus.unregisterHandler(SimpleCommandBusCommand); expect(commandBus.send(command)).to.be.rejectedWith(NoCommandHandlerException).and.notify(() => { handlerMock.verify(); done(); }); }); it("is idempotent", () => { expect(() => { commandBus.unregisterHandler(SimpleCommandBusCommand); }).not.to.throw(Error); }); }); }); class SimpleCommandBusCommand extends Command {} class SimpleCommandBusCommandHandler implements CommandHandler { public async handle(command: Command): Promise<void> {} }<|fim▁end|>
import * as chaiAsPromised from "chai-as-promised"; import {expect} from "chai"; import {SimpleCommandBus} from "../../../main/Apha/CommandHandling/SimpleCommandBus";
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'Stephanie' from ODMconnection import dbconnection from readSensors import readSensors from updateSensors import updateSensors from createSensors import createSensors from deleteSensors import deleteSensors <|fim▁hole|> 'deleteSensors', ]<|fim▁end|>
__all__ = [ 'readSensors', 'updateSensors', 'createSensors',
<|file_name|>http.py<|end_file_name|><|fim▁begin|>""" Forwards events to a HTTP call. The configuration used by this notifier is as follows: url Full URL to contact with the event data. A POST request will be made to this URL with the contents of the events in the body. Eventually this should be enhanced to support authentication credentials as well. """ import base64 import httplib import logging import threading from pulp.server.compat import json, json_util TYPE_ID = 'http' _logger = logging.getLogger(__name__) def handle_event(notifier_config, event): # fire the actual http push function off in a separate thread to keep # pulp from blocking or deadlocking due to the tasking subsystem data = event.data() _logger.info(data) body = json.dumps(data, default=json_util.default) thread = threading.Thread(target=_send_post, args=[notifier_config, body]) thread.setDaemon(True) thread.start() def _send_post(notifier_config, body): <|fim▁hole|> # Parse the URL for the pieces we need if 'url' not in notifier_config or not notifier_config['url']: _logger.warn('HTTP notifier configured without a URL; cannot fire event') return url = notifier_config['url'] try: scheme, empty, server, path = url.split('/', 3) except ValueError: _logger.warn('Improperly configured post_sync_url: %(u)s' % {'u': url}) return connection = _create_connection(scheme, server) # Process authentication if 'username' in notifier_config and 'password' in notifier_config: raw = ':'.join((notifier_config['username'], notifier_config['password'])) encoded = base64.encodestring(raw)[:-1] headers['Authorization'] = 'Basic ' + encoded connection.request('POST', '/' + path, body=body, headers=headers) response = connection.getresponse() if response.status != httplib.OK: error_msg = response.read() _logger.warn('Error response from HTTP notifier: %(e)s' % {'e': error_msg}) connection.close() def _create_connection(scheme, server): if scheme.startswith('https'): connection = httplib.HTTPSConnection(server) else: connection = httplib.HTTPConnection(server) return connection<|fim▁end|>
# Basic headers headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
<|file_name|>enum_same_crate_empty_match.rs<|end_file_name|><|fim▁begin|>#![deny(unreachable_patterns)] #[non_exhaustive] pub enum NonExhaustiveEnum { Unit, //~^ not covered Tuple(u32), //~^ not covered Struct { field: u32 } //~^ not covered } pub enum NormalEnum { Unit, //~^ not covered Tuple(u32), //~^ not covered Struct { field: u32 } //~^ not covered } #[non_exhaustive] pub enum EmptyNonExhaustiveEnum {} fn empty_non_exhaustive(x: EmptyNonExhaustiveEnum) { match x {} match x { _ => {} //~ ERROR unreachable pattern }<|fim▁hole|> match NonExhaustiveEnum::Unit {} //~^ ERROR `Unit`, `Tuple(_)` and `Struct { .. }` not covered [E0004] match NormalEnum::Unit {} //~^ ERROR `Unit`, `Tuple(_)` and `Struct { .. }` not covered [E0004] }<|fim▁end|>
} fn main() {
<|file_name|>clipshape.py<|end_file_name|><|fim▁begin|>__author__ = "Laura Martinez Sanchez" __license__ = "GPL" __version__ = "1.0" __email__ = "[email protected]" from osgeo import gdal, gdalnumeric, ogr, osr import numpy as np from PIL import Image, ImageDraw from collections import defaultdict import pickle import time from texture_common import * #Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate def world2Pixel(geoMatrix, x, y): ulX = geoMatrix[0] ulY = geoMatrix[3] xDist = geoMatrix[1] yDist = geoMatrix[5] rtnX = geoMatrix[2] rtnY = geoMatrix[4] pixel = int((x - ulX) / xDist) line = int((y - ulY) / yDist) return (pixel, line) #Converts a Python Imaging Library array to a gdalnumeric image. def imageToArray(i): ''' Converts a Python Imaging Library (PIL) array to a gdalnumeric image. ''' a = gdalnumeric.fromstring(i.tobytes(), 'b') a.shape = i.im.size[1], i.im.size[0] return a def ReadClipArray(lrY, ulY, lrX, ulX, img): clip = np.empty((img.RasterCount, lrY - ulY, lrX - ulX)) #Read only the pixels needed for do the clip for band in range(img.RasterCount): band += 1 imgaux = img.GetRasterBand(band).ReadAsArray(ulX, ulY, lrX - ulX, lrY - ulY) clip[band - 1] = imgaux return clip #Does the clip of the shape def ObtainPixelsfromShape(field, rasterPath, shapePath, INX, *args): # field='zona' # open dataset, also load as a gdal image to get geotransform # INX can be false. If True, uses additional layers. print "Starting clip...." start = time.time() if args: texture_train_Path = args[0] print texture_train_Path img, textArrayShp = createTextureArray(texture_train_Path, rasterPath) else: #print"Indexes = False" img = gdal.Open(rasterPath) geoTrans = img.GetGeoTransform()<|fim▁hole|> proj = img.GetProjection() #open shapefile driver = ogr.GetDriverByName("ESRI Shapefile") dataSource = driver.Open(shapePath, 0) layer = dataSource.GetLayer() clipdic = defaultdict(list) count = 0 #Convert the layer extent to image pixel coordinates, we read only de pixels needed for feature in layer: minX, maxX, minY, maxY = feature.GetGeometryRef().GetEnvelope() geoTrans = img.GetGeoTransform() ulX, ulY = world2Pixel(geoTrans, minX, maxY) lrX, lrY = world2Pixel(geoTrans, maxX, minY) #print ulX,lrX,ulY,lrY # Calculate the pixel size of the new image pxWidth = int(lrX - ulX) pxHeight = int(lrY - ulY) clip = ReadClipArray(lrY, ulY, lrX, ulX, img) #EDIT: create pixel offset to pass to new image Projection info xoffset = ulX yoffset = ulY #print "Xoffset, Yoffset = ( %d, %d )" % ( xoffset, yoffset ) # Create a new geomatrix for the image geoTrans = list(geoTrans) geoTrans[0] = minX geoTrans[3] = maxY # Map points to pixels for drawing the boundary on a blank 8-bit, black and white, mask image. points = [] pixels = [] geom = feature.GetGeometryRef() pts = geom.GetGeometryRef(0) [points.append((pts.GetX(p), pts.GetY(p))) for p in range(pts.GetPointCount())] [pixels.append(world2Pixel(geoTrans, p[0], p[1])) for p in points] rasterPoly = Image.new("L", (pxWidth, pxHeight), 1) rasterize = ImageDraw.Draw(rasterPoly) rasterize.polygon(pixels, 0) mask = imageToArray(rasterPoly) #SHow the clips of the features # plt.imshow(mask) # plt.show() # Clip the image using the mask into a dict temp = gdalnumeric.choose(mask, (clip, np.nan)) # #SHow the clips of the image # plt.imshow(temp[4]) # plt.show() temp = np.concatenate(temp.T) temp = temp[~np.isnan(temp[:, 0])] #NaN #print temp.shape clipdic[str(feature.GetField(field))].append(temp) count += temp.shape[0] end = time.time() print "Time clipshape:" print (end - start) print "count", count return clipdic, count ##########################################################################<|fim▁end|>
geoTransaux = img.GetGeoTransform()
<|file_name|>http.src.js<|end_file_name|><|fim▁begin|>define(['jquery','xing'],function($,xing) { var $body = $('body'), $progress = $($body.data('progressDisplay')), $status = $($body.data('statusMessage')), curPath = window.location.pathname, baseDir = curPath.substring(0, curPath.lastIndexOf('/')), sitePath = '//'+window.location.host+baseDir, stackCount = 0, stackCall = function() { if( $progress.length > 0 ) { $progress.show(); stackCount++; } }, unstackCall = function() { if( --stackCount < 1 ) { stackCount = 0; $progress.hide(); } }, getErrorHandler = function( callback, doUnstack ) { return function( xhr ) { if( doUnstack ) { unstackCall(); } callback($.parseJSON(xhr.response)); }; } ; xing.http = { BasePath : baseDir, SitePath : sitePath, redirect : function( path ) { stackCall(); // show our processing loader when changing pages window.location.href = path.replace('~',this.BasePath); }, get : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('GET',path,data,callback,stopLoadingIcon); }, post : function( path, data, callback, stopLoadingIcon ) { <|fim▁hole|> put : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('PUT',path,data,callback,stopLoadingIcon); }, ajax : function( type, path, data, callback, stopLoadingIcon ) { stopLoadingIcon = stopLoadingIcon || false; $.ajax( { type : type, url : path.replace('~',this.BasePath), data : data, success : stopLoadingIcon ? callback : function(response) { unstackCall(); callback(response); }, error : getErrorHandler(callback, !stopLoadingIcon) } ); if( !stopLoadingIcon ) { stackCall(); } }, stackCall : stackCall, unstackCall : unstackCall, forceEndStack : function() { stackCount = 0; unstackCall(); }, message : function( msg, isError, timeoutSecs, callback ) { if( $status.length ) { $status.find('.content').html(msg); $status.toggleClass('error',!!isError).show('fast'); // force isError to boolean with !! setTimeout( function() { $status.hide('fast'); if( callback ) { callback(); } }, typeof timeoutSecs == 'undefined' ? 1400 : (timeoutSecs * 1000)); } } }; return xing.http; });<|fim▁end|>
xing.http.ajax('POST',path,data,callback,stopLoadingIcon); },
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- INSTR_PER_LINE = 8 <|fim▁hole|>class Output(object): def __init__(self): pass def output_text(self, tokens, outfile): fd = open(outfile, 'w') instr_counter = 0 for t in tokens: instr = "%02X%02X%02X%02X" % tuple(reversed(t)) instr_counter = instr_counter + 1 if (instr_counter >= INSTR_PER_LINE): instr_counter = 0 instr += "\n" else: instr += " " fd.write(instr) fd.close()<|fim▁end|>
<|file_name|>coherence_copy_like_err_tuple.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we are able to introduce a negative constraint that // `MyType: !MyTrait` along with other "fundamental" wrappers. // aux-build:coherence_copy_like_lib.rs extern crate coherence_copy_like_lib as lib; use std::marker::MarkerTrait; struct MyType { x: i32 } trait MyTrait : MarkerTrait { } impl<T: lib::MyCopy> MyTrait for T { } //~ ERROR E0119 // Tuples are not fundamental, therefore this would require that // // (MyType,): !MyTrait // // which we cannot approve. impl MyTrait for (MyType,) { } <|fim▁hole|><|fim▁end|>
fn main() { }
<|file_name|>gothon_app.py<|end_file_name|><|fim▁begin|>import web from gothonweb import map urls = ( '/game', 'GameEngine', '/', 'Index', ) app = web.application(urls, globals()) #little hack so that debug mode works with sessions if web.config.get('_session') is None: store = web.session.DiskStore('sessions') session = web.session.Session(app, store, initializer={'room':None}) web.config._session = session else: session = web.config._session <|fim▁hole|> class Index(object): def GET(self): # this is used to "setup" the session with starting values session.room = map.START web.seeother("/game") class GameEngine(object): def GET(self): if session.room: return render.show_room(room=session.room) # else: # # why is there here? do you need it? # return render.you_died() def POST(self): form = web.input(action=None) if session.room: session.room = session.room.go(form.action) web.seeother("/game") if __name__ == "__main__": app.run()<|fim▁end|>
render = web.template.render('templates/', base="layout")
<|file_name|>ConstPointer.cpp<|end_file_name|><|fim▁begin|>#include <iostream> using namespace std; void display(const int *xPos, const int *yPos); void move(int *xPos, int *yPos); int main(void) { int x = 10; int y = 20; display(&x, &y); move(&x, &y); display(&x, &y); return 0; }<|fim▁hole|> cout << "Current position [" << *xPos << ", " << *yPos << "]" << endl; } void move(int *xPos, int *yPos) { *xPos = *xPos + 1; *yPos = *yPos + 1; }<|fim▁end|>
void display(const int *xPos, const int *yPos) { // btw const not needed for this
<|file_name|>feedback.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import access import util @auth.requires_login() def index(): """Produces a list of the feedback obtained for a given venue, or for all venues.""" venue_id = request.args(0) if venue_id == 'all': q = (db.submission.user == get_user_email()) else: q = ((db.submission.user == get_user_email()) & (db.submission.venue_id == venue_id)) db.submission.id.represent = lambda x, r: A(T('View'), _class='btn', _href=URL('submission', 'view_own_submission', args=['v', r.id])) db.submission.id.label = T('Submission') db.submission.id.readable = True db.submission.venue_id.readable = True grid = SQLFORM.grid(q, fields=[db.submission.id, db.submission.venue_id, db.submission.date_created, db.submission.date_updated, ], csv=False, details=False, create=False, editable=False, deletable=False, args=request.args[:1], maxtextlength=24, ) return dict(grid=grid) @auth.requires_login() def view_feedback(): """Shows detailed feedback for a user in a venue. This controller accepts various types of arguments: * 's', submission_id * 'u', venue_id, username * 'v', venue_id (in which case, shows own submission to that venue) """ if len(request.args) == 0: redirect(URL('default', 'index')) if request.args(0) == 's': # submission_id n_args = 2 subm = db.submission(request.args(1)) or redirect(URL('default', 'index')) c = db.venue(subm.venue_id) or redirect(URL('default', 'index')) username = subm.user elif request.args(0) == 'v': # venue_id n_args = 2 c = db.venue(request.args(1)) or redirect(URL('default', 'index')) username = get_user_email() subm = db((db.submission.user == username) & (db.submission.venue_id == c.id)).select().first() else: # venue_id, username n_args = 3 c = db.venue(request.args(1)) or redirect(URL('default', 'index')) username = request.args(2) or redirect(URL('default', 'index')) subm = db((db.submission.user == username) & (db.submission.venue_id == c.id)).select().first() # Checks permissions. props = db(db.user_properties.user == get_user_email()).select().first() if props == None: session.flash = T('Not authorized.') redirect(URL('default', 'index')) is_author = (username == get_user_email()) can_view_feedback = access.can_view_feedback(c, props) or is_author if (not can_view_feedback): session.flash = T('Not authorized.') redirect(URL('default', 'index')) if not (access.can_view_feedback(c, props) or datetime.utcnow() > c.rate_close_date): session.flash = T('The ratings are not yet available.') redirect(URL('feedback', 'index', args=['all'])) # Produces the link to edit the feedback. edit_feedback_link = None if subm is not None and access.can_observe(c, props): edit_feedback_link = A(T('Edit feedback'), _class='btn', _href=URL('submission', 'edit_feedback', args=[subm.id])) # Produces the download link. download_link = None if subm is not None and c.allow_file_upload and subm.content is not None: if is_author: download_link = A(T('Download'), _class='btn', _href=URL('submission', 'download_author', args=[subm.id, subm.content])) else: download_link = A(T('Download'), _class='btn', _href=URL('submission', 'download_manager', args=[subm.id, subm.content])) venue_link = A(c.name, _href=URL('venues', 'view_venue', args=[c.id])) # Submission link. subm_link = None if subm is not None and c.allow_link_submission: subm_link = A(subm.link, _href=subm.link) # Submission content and feedback. subm_comment = None subm_feedback = None if subm is not None: raw_subm_comment = keystore_read(subm.comment) if raw_subm_comment is not None and len(raw_subm_comment) > 0: subm_comment = MARKMIN(keystore_read(subm.comment)) raw_feedback = keystore_read(subm.feedback) if raw_feedback is not None and len(raw_feedback) > 0: subm_feedback = MARKMIN(raw_feedback) # Display settings. db.submission.percentile.readable = True db.submission.comment.readable = True db.submission.feedback.readable = True if access.can_observe(c, props): db.submission.quality.readable = True db.submission.error.readable = True # Reads the grade information. submission_grade = submission_percentile = None review_grade = review_percentile = user_reputation = None final_grade = final_percentile = None assigned_grade = None if c.grades_released: grade_info = db((db.grades.user == username) & (db.grades.venue_id == c.id)).select().first() if grade_info is not None: submission_grade = represent_quality(grade_info.submission_grade, None) submission_percentile = represent_percentage(grade_info.submission_percentile, None) review_grade = represent_quality_10(grade_info.accuracy, None) review_percentile = represent_percentage(grade_info.accuracy_percentile, None) user_reputation = represent_01_as_percentage(grade_info.reputation, None) final_grade = represent_quality(grade_info.grade, None) final_percentile = represent_percentage(grade_info.percentile, None) assigned_grade = represent_quality(grade_info.assigned_grade, None) # Makes a grid of comments. db.task.submission_name.readable = False db.task.assigned_date.readable = False db.task.completed_date.readable = False db.task.rejected.readable = True db.task.helpfulness.readable = db.task.helpfulness.writable = True # Prevent editing the comments; the only thing editable should be the "is bogus" field. db.task.comments.writable = False<|fim▁hole|> if access.can_observe(c, props): db.task.user.readable = True db.task.completed_date.readable = True links = [ dict(header=T('Review details'), body= lambda r: A(T('View'), _class='btn', _href=URL('ranking', 'view_comparison', args=[r.id]))), ] details = False if subm is not None: ranking_link = A(T('details'), _href=URL('ranking', 'view_comparisons_given_submission', args=[subm.id])) reviews_link = A(T('details'), _href=URL('ranking', 'view_comparisons_given_user', args=[username, c.id])) db.task.user.represent = lambda v, r: A(v, _href=URL('ranking', 'view_comparisons_given_user', args=[v, c.id], user_signature=True)) else: user_reputation = None links = [ dict(header=T('Review feedback'), body = lambda r: A(T('Give feedback'), _class='btn', _href=URL('feedback', 'reply_to_review', args=[r.id], user_signature=True))), ] details = False ranking_link = None reviews_link = None if subm is not None: q = ((db.task.submission_id == subm.id) & (db.task.is_completed == True)) # q = (db.task.submission_id == subm.id) else: q = (db.task.id == -1) grid = SQLFORM.grid(q, fields=[db.task.id, db.task.user, db.task.rejected, db.task.comments, db.task.helpfulness, ], details = details, csv=False, create=False, editable=False, deletable=False, searchable=False, links=links, args=request.args[:n_args], maxtextlength=24, ) return dict(subm=subm, download_link=download_link, subm_link=subm_link, username=username, subm_comment=subm_comment, subm_feedback=subm_feedback, edit_feedback_link=edit_feedback_link, is_admin=is_user_admin(), submission_grade=submission_grade, submission_percentile=submission_percentile, review_grade=review_grade, review_percentile=review_percentile, user_reputation=user_reputation, final_grade=final_grade, final_percentile=final_percentile, assigned_grade=assigned_grade, venue_link=venue_link, grid=grid, ranking_link=ranking_link, reviews_link=reviews_link) @auth.requires_signature() def reply_to_review(): t = db.task(request.args(0)) or redirect(URL('default', 'index')) db.task.submission_name.readable = False db.task.assigned_date.readable = False db.task.completed_date.readable = False db.task.comments.readable = False db.task.helpfulness.readable = db.task.helpfulness.writable = True db.task.feedback.readable = db.task.feedback.writable = True form = SQLFORM(db.task, record=t) form.vars.feedback = keystore_read(t.feedback) if form.process(onvalidation=validate_review_feedback(t)).accepted: session.flash = T('Updated.') redirect(URL('feedback', 'view_feedback', args=['s', t.submission_id])) link_to_submission = A(T('View submission'), _href=URL('submission', 'view_own_submission', args=['v', t.submission_id])) review_comments = MARKMIN(keystore_read(t.comments)) return dict(form=form, link_to_submission=link_to_submission, review_comments=review_comments) def validate_review_feedback(t): def f(form): if not form.errors: feedback_id = keystore_update(t.feedback, form.vars.feedback) form.vars.feedback = feedback_id return f @auth.requires_login() def view_my_reviews(): """This controller displays the reviews a user has written for a venue, along with the feedback they received.""" c = db.venue(request.args(0)) or redirect(URL('rating', 'review_index')) link_to_venue = A(c.name, _href=URL('venues', 'view_venue', args=[c.id])) link_to_eval = A(T('My evaluation in this venue'), _class='btn', _href=URL('feedback', 'view_feedback', args=['v', c.id])) q = ((db.task.user == get_user_email()) & (db.task.venue_id == c.id)) db.task.rejected.readable = True db.task.helpfulness.readable = True db.task.comments.readable = True db.task.feedback.readable = True # To prevent chopping db.task.submission_name.represent = represent_text_field grid = SQLFORM.grid(q, fields=[db.task.submission_name, db.task.rejected, db.task.helpfulness], details=True, editable=False, deletable=False, create=False, searchable=False, csv=False, args=request.args[:1], maxtextlength=24, ) return dict(grid=grid, link_to_venue=link_to_venue, link_to_eval=link_to_eval)<|fim▁end|>
db.task.comments.readable = True ranking_link = None
<|file_name|>StylesMixin.py<|end_file_name|><|fim▁begin|># Python imports # Lib imports from PyInquirer import style_from_dict, Token # Application imports class StylesMixin: """ The StylesMixin has style methods that get called and return their respective objects. """ def default(self): return style_from_dict({ Token.Separator: '#6C6C6C', Token.QuestionMark: '#FF9D00 bold', # Token.Selected: '', # default<|fim▁hole|> Token.Pointer: '#FF9D00 bold', Token.Instruction: '', # default Token.Answer: '#5F819D bold', Token.Question: '', }) def orange(self): return style_from_dict({ Token.Pointer: '#6C6C6C bold', Token.QuestionMark: '#FF9D00 bold', Token.Separator: '#FF9D00', Token.Selected: '#FF9D00', Token.Instruction: '', # default Token.Answer: '#FF9D00 bold', Token.Question: '', # default }) def red(self): return style_from_dict({ Token.Pointer: '#c70e0e bold', Token.QuestionMark: '#c70e0e bold', Token.Separator: '#c70e0e', Token.Selected: '#c70e0e', Token.Instruction: '', # default Token.Answer: '#c70e0e bold', Token.Question: '', # default }) def purple(self): return style_from_dict({ Token.Pointer: '#673ab7 bold', Token.QuestionMark: '#673ab7 bold', Token.Selected: '#673ab7', Token.Separator: '#673ab7', Token.Instruction: '', # default Token.Answer: '#673ab7 bold', Token.Question: '', # default }) def green(self): return style_from_dict({ Token.Pointer: '#ffde00 bold', Token.QuestionMark: '#29a116 bold', Token.Selected: '#29a116', Token.Separator: '#29a116', Token.Instruction: '', # default Token.Answer: '#29a116 bold', Token.Question: '', # default })<|fim▁end|>
Token.Selected: '#5F819D',
<|file_name|>leader_scroll_dialog.cpp<|end_file_name|><|fim▁begin|>/* Copyright (C) 2003 - 2016 by David White <[email protected]> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * @file * Show screen with scrolling credits. */ #include "leader_scroll_dialog.hpp" #include "wml_separators.hpp" #include "map/map.hpp" //#include "construct_dialog.hpp" //#include "display.hpp" //#include "gettext.hpp" #include "marked-up_text.hpp" #include "resources.hpp" #include "units/unit.hpp" // //#include <boost/foreach.hpp> /** * @namespace about * Display credits %about all contributors. * * This module is used from the startup screen. \n * When show_about() is called, a list of contributors * to the game will be presented to the user. */ namespace gui { void status_table(display& gui, int selected) { std::stringstream heading; heading << HEADING_PREFIX << _("Leader") << COLUMN_SEPARATOR << ' ' << COLUMN_SEPARATOR << _("Team") << COLUMN_SEPARATOR << _("Gold") << COLUMN_SEPARATOR << _("Villages") << COLUMN_SEPARATOR << _("status^Units") << COLUMN_SEPARATOR << _("Upkeep") << COLUMN_SEPARATOR << _("Income"); gui::menu::basic_sorter sorter; sorter.set_redirect_sort(0,1).set_alpha_sort(1).set_alpha_sort(2).set_numeric_sort(3) .set_numeric_sort(4).set_numeric_sort(5).set_numeric_sort(6).set_numeric_sort(7); std::vector<std::string> items; std::vector<bool> leader_bools; items.push_back(heading.str()); const gamemap& map = gui.get_map(); const unit_map& units = gui.get_units(); assert(&gui.get_teams() == resources::teams); const std::vector<team>& teams = gui.get_teams(); const team& viewing_team = teams[gui.viewing_team()]; unsigned total_villages = 0; // a variable to check if there are any teams to show in the table bool status_table_empty = true; //if the player is under shroud or fog, they don't get //to see details about the other sides, only their own //side, allied sides and a ??? is shown to demonstrate //lack of information about the other sides But he see //all names with in colors for(size_t n = 0; n != teams.size(); ++n) { if(teams[n].hidden()) { continue; } status_table_empty=false; const bool known = viewing_team.knows_about_team(n, network::nconnections() > 0); const bool enemy = viewing_team.is_enemy(n+1); std::stringstream str; const team_data data = gui.get_disp_context().calculate_team_data(teams[n],n+1); unit_map::const_iterator leader = units.find_leader(n + 1); std::string leader_name; //output the number of the side first, and this will //cause it to be displayed in the correct color if(leader != units.end()) { const bool fogged = viewing_team.fogged(leader->get_location()); // Add leader image. If it's fogged // show only a random leader image. if (!fogged || known || game_config::debug) { str << IMAGE_PREFIX << leader->absolute_image(); leader_bools.push_back(true); leader_name = leader->name(); } else { str << IMAGE_PREFIX << std::string("units/unknown-unit.png"); leader_bools.push_back(false); leader_name = "Unknown"; } // if (gamestate_.classification().campaign_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER) // leader_name = teams[n].current_player(); #ifndef LOW_MEM str << leader->image_mods(); #endif } else { leader_bools.push_back(false); } str << COLUMN_SEPARATOR << team::get_side_highlight(n) << leader_name << COLUMN_SEPARATOR << (data.teamname.empty() ? teams[n].team_name() : data.teamname) << COLUMN_SEPARATOR; if(!known && !game_config::debug) { // We don't spare more info (only name) // so let's go on next side ... items.push_back(str.str()); continue; } if(game_config::debug) { str << utils::half_signed_value(data.gold) << COLUMN_SEPARATOR; } else if(enemy && viewing_team.uses_fog()) { str << ' ' << COLUMN_SEPARATOR; } else { str << utils::half_signed_value(data.gold) << COLUMN_SEPARATOR; } str << data.villages; if(!(viewing_team.uses_fog() || viewing_team.uses_shroud())) { str << "/" << map.villages().size(); } str << COLUMN_SEPARATOR << data.units << COLUMN_SEPARATOR << data.upkeep << COLUMN_SEPARATOR << (data.net_income < 0 ? font::BAD_TEXT : font::NULL_MARKUP) << utils::signed_value(data.net_income); total_villages += data.villages; items.push_back(str.str()); } if (total_villages > map.villages().size()) { //TODO // ERR_NG << "Logic error: map has " << map.villages().size() // << " villages but status table shows " << total_villages << " owned in total\n"; } if (status_table_empty) { // no sides to show - display empty table std::stringstream str; str << " "; for (int i=0;i<7;++i) str << COLUMN_SEPARATOR << " "; leader_bools.push_back(false); items.push_back(str.str()); } int result = 0; { leader_scroll_dialog slist(gui, _("Current Status"), leader_bools, selected, gui::DIALOG_FORWARD); slist.add_button(new gui::dialog_button(gui.video(), _("More >"), gui::button::TYPE_PRESS, gui::DIALOG_FORWARD), gui::dialog::BUTTON_EXTRA_LEFT); slist.set_menu(items, &sorter); slist.get_menu().move_selection(selected); result = slist.show(); selected = slist.get_menu().selection(); } // this will kill the dialog before scrolling if (result >= 0) { //TODO // gui.scroll_to_leader(units_, selected+1); } else if (result == gui::DIALOG_FORWARD) scenario_settings_table(gui, selected); } void scenario_settings_table(display& gui, int selected) { std::stringstream heading; heading << HEADING_PREFIX << _("scenario settings^Leader") << COLUMN_SEPARATOR << COLUMN_SEPARATOR << _("scenario settings^Side") << COLUMN_SEPARATOR << _("scenario settings^Start\nGold") << COLUMN_SEPARATOR << _("scenario settings^Base\nIncome") << COLUMN_SEPARATOR << _("scenario settings^Gold Per\nVillage") << COLUMN_SEPARATOR << _("scenario settings^Support Per\nVillage") << COLUMN_SEPARATOR << _("scenario settings^Fog") << COLUMN_SEPARATOR << _("scenario settings^Shroud"); gui::menu::basic_sorter sorter; sorter.set_redirect_sort(0,1).set_alpha_sort(1).set_numeric_sort(2) .set_numeric_sort(3).set_numeric_sort(4).set_numeric_sort(5) .set_numeric_sort(6).set_alpha_sort(7).set_alpha_sort(8); std::vector<std::string> items; std::vector<bool> leader_bools; items.push_back(heading.str()); //const gamemap& map = gui.get_map(); const unit_map& units = gui.get_units(); const std::vector<team>& teams = gui.get_teams(); const team& viewing_team = teams[gui.viewing_team()]; bool settings_table_empty = true; bool fogged; for(size_t n = 0; n != teams.size(); ++n) { if(teams[n].hidden()) { continue; } settings_table_empty = false; std::stringstream str; unit_map::const_iterator leader = units.find_leader(n + 1); if(leader != units.end()) { // Add leader image. If it's fogged // show only a random leader image. fogged=viewing_team.fogged(leader->get_location()); if (!fogged || viewing_team.knows_about_team(n, network::nconnections() > 0) || game_config::debug) { str << IMAGE_PREFIX << leader->absolute_image(); leader_bools.push_back(true); } else { str << IMAGE_PREFIX << std::string("units/unknown-unit.png"); leader_bools.push_back(false); } #ifndef LOW_MEM str << "~RC(" << leader->team_color() << '>' << team::get_side_color_index(n+1) << ")"; #endif } else { leader_bools.push_back(false); } str << COLUMN_SEPARATOR << team::get_side_highlight(n) << teams[n].side_name() << COLUMN_SEPARATOR << n + 1 << COLUMN_SEPARATOR << teams[n].start_gold() << COLUMN_SEPARATOR << teams[n].base_income() << COLUMN_SEPARATOR<|fim▁hole|> << teams[n].village_gold() << COLUMN_SEPARATOR << teams[n].village_support() << COLUMN_SEPARATOR << (teams[n].uses_fog() ? _("yes") : _("no")) << COLUMN_SEPARATOR << (teams[n].uses_shroud() ? _("yes") : _("no")) << COLUMN_SEPARATOR; items.push_back(str.str()); } if (settings_table_empty) { // no sides to show - display empty table std::stringstream str; for (int i=0;i<8;++i) str << " " << COLUMN_SEPARATOR; leader_bools.push_back(false); items.push_back(str.str()); } int result = 0; { leader_scroll_dialog slist(gui, _("Scenario Settings"), leader_bools, selected, gui::DIALOG_BACK); slist.set_menu(items, &sorter); slist.get_menu().move_selection(selected); slist.add_button(new gui::dialog_button(gui.video(), _(" < Back"), gui::button::TYPE_PRESS, gui::DIALOG_BACK), gui::dialog::BUTTON_EXTRA_LEFT); result = slist.show(); selected = slist.get_menu().selection(); } // this will kill the dialog before scrolling if (result >= 0) { //TODO //gui_->scroll_to_leader(units_, selected+1); } else if (result == gui::DIALOG_BACK) status_table(gui, selected); } } // end namespace about<|fim▁end|>
<|file_name|>version.go<|end_file_name|><|fim▁begin|>package eventgrid import "github.com/Azure/azure-sdk-for-go/version" // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { return "Azure-SDK-For-Go/" + Version() + " eventgrid/2019-02-01-preview" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { return version.Number<|fim▁hole|><|fim▁end|>
}
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![allow(non_camel_case_types)] extern crate libc; use self::libc::{int64_t, size_t, ssize_t, time_t, timeval, uint8_t, uint32_t, uint64_t}; pub type Enum_Unnamed1 = ::libc::c_uint; pub const LIBRADOS_OP_FLAG_EXCL: ::libc::c_uint = 1; pub const LIBRADOS_OP_FLAG_FAILOK: ::libc::c_uint = 2; pub const LIBRADOS_OP_FLAG_FADVISE_RANDOM: ::libc::c_uint = 4; pub const LIBRADOS_OP_FLAG_FADVISE_SEQUENTIAL: ::libc::c_uint = 8; pub const LIBRADOS_OP_FLAG_FADVISE_WILLNEED: ::libc::c_uint = 16; pub const LIBRADOS_OP_FLAG_FADVISE_DONTNEED: ::libc::c_uint = 32; pub const LIBRADOS_OP_FLAG_FADVISE_NOCACHE: ::libc::c_uint = 64; pub type Enum_Unnamed2 = ::libc::c_uint; pub const LIBRADOS_CMPXATTR_OP_EQ: ::libc::c_uint = 1; pub const LIBRADOS_CMPXATTR_OP_NE: ::libc::c_uint = 2; pub const LIBRADOS_CMPXATTR_OP_GT: ::libc::c_uint = 3; pub const LIBRADOS_CMPXATTR_OP_GTE: ::libc::c_uint = 4; pub const LIBRADOS_CMPXATTR_OP_LT: ::libc::c_uint = 5; pub const LIBRADOS_CMPXATTR_OP_LTE: ::libc::c_uint = 6; pub type Enum_Unnamed3 = ::libc::c_uint; pub const LIBRADOS_OPERATION_NOFLAG: ::libc::c_uint = 0; pub const LIBRADOS_OPERATION_BALANCE_READS: ::libc::c_uint = 1; pub const LIBRADOS_OPERATION_LOCALIZE_READS: ::libc::c_uint = 2; pub const LIBRADOS_OPERATION_ORDER_READS_WRITES: ::libc::c_uint = 4; pub const LIBRADOS_OPERATION_IGNORE_CACHE: ::libc::c_uint = 8; pub const LIBRADOS_OPERATION_SKIPRWLOCKS: ::libc::c_uint = 16; pub const LIBRADOS_OPERATION_IGNORE_OVERLAY: ::libc::c_uint = 32; pub type rados_t = *mut ::libc::c_void; pub type rados_config_t = *mut ::libc::c_void; pub type rados_ioctx_t = *mut ::libc::c_void; pub type rados_list_ctx_t = *mut ::libc::c_void; pub type rados_snap_t = uint64_t; pub type rados_xattrs_iter_t = *mut ::libc::c_void; pub type rados_omap_iter_t = *mut ::libc::c_void; #[repr(C)] #[derive(Copy)] pub struct Struct_rados_pool_stat_t { pub num_bytes: uint64_t, pub num_kb: uint64_t, pub num_objects: uint64_t, pub num_object_clones: uint64_t, pub num_object_copies: uint64_t, pub num_objects_missing_on_primary: uint64_t, pub num_objects_unfound: uint64_t, pub num_objects_degraded: uint64_t, pub num_rd: uint64_t, pub num_rd_kb: uint64_t, pub num_wr: uint64_t, pub num_wr_kb: uint64_t, } impl ::std::clone::Clone for Struct_rados_pool_stat_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rados_pool_stat_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_rados_cluster_stat_t { pub kb: uint64_t, pub kb_used: uint64_t, pub kb_avail: uint64_t, pub num_objects: uint64_t, } impl ::std::clone::Clone for Struct_rados_cluster_stat_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rados_cluster_stat_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type rados_write_op_t = *mut ::libc::c_void; pub type rados_read_op_t = *mut ::libc::c_void; pub type rados_completion_t = *mut ::libc::c_void; pub type rados_callback_t = ::std::option::Option<extern "C" fn(cb: rados_completion_t, arg: *mut ::libc::c_void) -> ()>; pub type rados_watchcb_t = ::std::option::Option<extern "C" fn(opcode: uint8_t, ver: uint64_t, arg: *mut ::libc::c_void) -> ()>; pub type rados_watchcb2_t = ::std::option::Option<extern "C" fn(arg: *mut ::libc::c_void, notify_id: uint64_t, handle: uint64_t, notifier_id: uint64_t, data: *mut ::libc::c_void, data_len: size_t) -> ()>; pub type rados_watcherrcb_t = ::std::option::Option<extern "C" fn(pre: *mut ::libc::c_void, cookie: uint64_t, err: ::libc::c_int) -> ()>; pub type rados_log_callback_t = ::std::option::Option<extern "C" fn(arg: *mut ::libc::c_void, line: *const ::libc::c_char, who: *const ::libc::c_char, sec: uint64_t, nsec: uint64_t, seq: uint64_t, level: *const ::libc::c_char, msg: *const ::libc::c_char) -> ()>; #[link(name = "rados")] extern "C" { pub fn rados_version(major: *mut ::libc::c_int, minor: *mut ::libc::c_int, extra: *mut ::libc::c_int) -> (); pub fn rados_create(cluster: *mut rados_t, id: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_create2(pcluster: *mut rados_t, clustername: *const ::libc::c_char, name: *const ::libc::c_char, flags: uint64_t) -> ::libc::c_int; pub fn rados_create_with_context(cluster: *mut rados_t, cct: rados_config_t) -> ::libc::c_int; pub fn rados_ping_monitor(cluster: rados_t, mon_id: *const ::libc::c_char, outstr: *mut *mut ::libc::c_char, outstrlen: *mut size_t) -> ::libc::c_int; pub fn rados_connect(cluster: rados_t) -> ::libc::c_int; pub fn rados_shutdown(cluster: rados_t) -> (); pub fn rados_conf_read_file(cluster: rados_t, path: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_conf_parse_argv(cluster: rados_t, argc: ::libc::c_int, argv: *mut *const ::libc::c_char) -> ::libc::c_int; pub fn rados_conf_parse_argv_remainder(cluster: rados_t, argc: ::libc::c_int, argv: *mut *const ::libc::c_char, remargv: *mut *const ::libc::c_char) -> ::libc::c_int; pub fn rados_conf_parse_env(cluster: rados_t, var: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_conf_set(cluster: rados_t, option: *const ::libc::c_char, value: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_conf_get(cluster: rados_t, option: *const ::libc::c_char, buf: *mut ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_cluster_stat(cluster: rados_t, result: *mut Struct_rados_cluster_stat_t) -> ::libc::c_int; pub fn rados_cluster_fsid(cluster: rados_t, buf: *mut ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_wait_for_latest_osdmap(cluster: rados_t) -> ::libc::c_int; pub fn rados_pool_list(cluster: rados_t, buf: *mut ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_cct(cluster: rados_t) -> rados_config_t; pub fn rados_get_instance_id(cluster: rados_t) -> uint64_t; pub fn rados_ioctx_create(cluster: rados_t, pool_name: *const ::libc::c_char, ioctx: *mut rados_ioctx_t) -> ::libc::c_int; pub fn rados_ioctx_create2(cluster: rados_t, pool_id: int64_t, ioctx: *mut rados_ioctx_t) -> ::libc::c_int; pub fn rados_ioctx_destroy(io: rados_ioctx_t) -> (); pub fn rados_ioctx_cct(io: rados_ioctx_t) -> rados_config_t; pub fn rados_ioctx_get_cluster(io: rados_ioctx_t) -> rados_t; pub fn rados_ioctx_pool_stat(io: rados_ioctx_t, stats: *mut Struct_rados_pool_stat_t) -> ::libc::c_int; pub fn rados_pool_lookup(cluster: rados_t, pool_name: *const ::libc::c_char) -> int64_t; pub fn rados_pool_reverse_lookup(cluster: rados_t, id: int64_t, buf: *mut ::libc::c_char, maxlen: size_t) -> ::libc::c_int; pub fn rados_pool_create(cluster: rados_t, pool_name: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_pool_create_with_auid(cluster: rados_t, pool_name: *const ::libc::c_char, auid: uint64_t) -> ::libc::c_int; pub fn rados_pool_create_with_crush_rule(cluster: rados_t, pool_name: *const ::libc::c_char, crush_rule_num: uint8_t) -> ::libc::c_int; pub fn rados_pool_create_with_all(cluster: rados_t, pool_name: *const ::libc::c_char, auid: uint64_t, crush_rule_num: uint8_t) -> ::libc::c_int; pub fn rados_pool_get_base_tier(cluster: rados_t, pool: int64_t, base_tier: *mut int64_t) -> ::libc::c_int; pub fn rados_pool_delete(cluster: rados_t, pool_name: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_ioctx_pool_set_auid(io: rados_ioctx_t, auid: uint64_t) -> ::libc::c_int; pub fn rados_ioctx_pool_get_auid(io: rados_ioctx_t, auid: *mut uint64_t) -> ::libc::c_int; pub fn rados_ioctx_pool_requires_alignment(io: rados_ioctx_t) -> ::libc::c_int; pub fn rados_ioctx_pool_required_alignment(io: rados_ioctx_t) -> uint64_t; pub fn rados_ioctx_get_id(io: rados_ioctx_t) -> int64_t; pub fn rados_ioctx_get_pool_name(io: rados_ioctx_t, buf: *mut ::libc::c_char, maxlen: ::libc::c_uint) -> ::libc::c_int; pub fn rados_ioctx_locator_set_key(io: rados_ioctx_t, key: *const ::libc::c_char) -> (); pub fn rados_ioctx_set_namespace(io: rados_ioctx_t, nspace: *const ::libc::c_char) -> (); pub fn rados_nobjects_list_open(io: rados_ioctx_t, ctx: *mut rados_list_ctx_t) -> ::libc::c_int; pub fn rados_nobjects_list_get_pg_hash_position(ctx: rados_list_ctx_t) -> uint32_t; pub fn rados_nobjects_list_seek(ctx: rados_list_ctx_t, pos: uint32_t) -> uint32_t; pub fn rados_nobjects_list_next(ctx: rados_list_ctx_t, entry: *mut *const ::libc::c_char, key: *mut *const ::libc::c_char, nspace: *mut *const ::libc::c_char) -> ::libc::c_int; pub fn rados_nobjects_list_close(ctx: rados_list_ctx_t) -> (); pub fn rados_objects_list_open(io: rados_ioctx_t, ctx: *mut rados_list_ctx_t) -> ::libc::c_int; pub fn rados_objects_list_get_pg_hash_position(ctx: rados_list_ctx_t) -> uint32_t; pub fn rados_objects_list_seek(ctx: rados_list_ctx_t, pos: uint32_t) -> uint32_t; pub fn rados_objects_list_next(ctx: rados_list_ctx_t, entry: *mut *const ::libc::c_char, key: *mut *const ::libc::c_char) -> ::libc::c_int; pub fn rados_objects_list_close(ctx: rados_list_ctx_t) -> (); pub fn rados_ioctx_snap_create(io: rados_ioctx_t, snapname: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_ioctx_snap_remove(io: rados_ioctx_t, snapname: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_ioctx_snap_rollback(io: rados_ioctx_t, oid: *const ::libc::c_char, snapname: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_rollback(io: rados_ioctx_t, oid: *const ::libc::c_char, snapname: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_ioctx_snap_set_read(io: rados_ioctx_t, snap: rados_snap_t) -> (); pub fn rados_ioctx_selfmanaged_snap_create(io: rados_ioctx_t, snapid: *mut rados_snap_t) -> ::libc::c_int; pub fn rados_ioctx_selfmanaged_snap_remove(io: rados_ioctx_t, snapid: rados_snap_t) -> ::libc::c_int; pub fn rados_ioctx_selfmanaged_snap_rollback(io: rados_ioctx_t, oid: *const ::libc::c_char, snapid: rados_snap_t) -> ::libc::c_int; pub fn rados_ioctx_selfmanaged_snap_set_write_ctx(io: rados_ioctx_t, seq: rados_snap_t, snaps: *mut rados_snap_t, num_snaps: ::libc::c_int) -> ::libc::c_int; pub fn rados_ioctx_snap_list(io: rados_ioctx_t, snaps: *mut rados_snap_t, maxlen: ::libc::c_int) -> ::libc::c_int; pub fn rados_ioctx_snap_lookup(io: rados_ioctx_t, name: *const ::libc::c_char, id: *mut rados_snap_t) -> ::libc::c_int; pub fn rados_ioctx_snap_get_name(io: rados_ioctx_t, id: rados_snap_t, name: *mut ::libc::c_char, maxlen: ::libc::c_int) -> ::libc::c_int; pub fn rados_ioctx_snap_get_stamp(io: rados_ioctx_t, id: rados_snap_t, t: *mut time_t) -> ::libc::c_int; pub fn rados_get_last_version(io: rados_ioctx_t) -> uint64_t; pub fn rados_write(io: rados_ioctx_t, oid: *const ::libc::c_char, buf: *const ::libc::c_char, len: size_t, off: uint64_t) -> ::libc::c_int; pub fn rados_write_full(io: rados_ioctx_t, oid: *const ::libc::c_char, buf: *const ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_clone_range(io: rados_ioctx_t, dst: *const ::libc::c_char, dst_off: uint64_t, src: *const ::libc::c_char, src_off: uint64_t, len: size_t) -> ::libc::c_int; pub fn rados_append(io: rados_ioctx_t, oid: *const ::libc::c_char, buf: *const ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_read(io: rados_ioctx_t, oid: *const ::libc::c_char, buf: *mut ::libc::c_char, len: size_t, off: uint64_t) -> ::libc::c_int; pub fn rados_remove(io: rados_ioctx_t, oid: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_trunc(io: rados_ioctx_t, oid: *const ::libc::c_char, size: uint64_t) -> ::libc::c_int; pub fn rados_getxattr(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char, buf: *mut ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_setxattr(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char, buf: *const ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_rmxattr(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_getxattrs(io: rados_ioctx_t, oid: *const ::libc::c_char, iter: *mut rados_xattrs_iter_t) -> ::libc::c_int; pub fn rados_getxattrs_next(iter: rados_xattrs_iter_t, name: *mut *const ::libc::c_char, val: *mut *const ::libc::c_char, len: *mut size_t) -> ::libc::c_int; pub fn rados_getxattrs_end(iter: rados_xattrs_iter_t) -> (); pub fn rados_omap_get_next(iter: rados_omap_iter_t, key: *mut *mut ::libc::c_char, val: *mut *mut ::libc::c_char, len: *mut size_t) -> ::libc::c_int; pub fn rados_omap_get_end(iter: rados_omap_iter_t) -> (); pub fn rados_stat(io: rados_ioctx_t, o: *const ::libc::c_char, psize: *mut uint64_t, pmtime: *mut time_t) -> ::libc::c_int; pub fn rados_tmap_update(io: rados_ioctx_t, o: *const ::libc::c_char, cmdbuf: *const ::libc::c_char, cmdbuflen: size_t) -> ::libc::c_int; pub fn rados_tmap_put(io: rados_ioctx_t, o: *const ::libc::c_char, buf: *const ::libc::c_char, buflen: size_t) -> ::libc::c_int; pub fn rados_tmap_get(io: rados_ioctx_t, o: *const ::libc::c_char, buf: *mut ::libc::c_char, buflen: size_t) -> ::libc::c_int; pub fn rados_exec(io: rados_ioctx_t, oid: *const ::libc::c_char, cls: *const ::libc::c_char, method: *const ::libc::c_char, in_buf: *const ::libc::c_char, in_len: size_t, buf: *mut ::libc::c_char, out_len: size_t) -> ::libc::c_int; pub fn rados_aio_create_completion(cb_arg: *mut ::libc::c_void, cb_complete: rados_callback_t, cb_safe: rados_callback_t, pc: *mut rados_completion_t) -> ::libc::c_int; pub fn rados_aio_wait_for_complete(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_wait_for_safe(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_is_complete(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_is_safe(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_wait_for_complete_and_cb(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_wait_for_safe_and_cb(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_is_complete_and_cb(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_is_safe_and_cb(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_get_return_value(c: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_release(c: rados_completion_t) -> (); pub fn rados_aio_write(io: rados_ioctx_t, oid: *const ::libc::c_char, completion: rados_completion_t, buf: *const ::libc::c_char, len: size_t, off: uint64_t) -> ::libc::c_int; pub fn rados_aio_append(io: rados_ioctx_t, oid: *const ::libc::c_char, completion: rados_completion_t, buf: *const ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_aio_write_full(io: rados_ioctx_t, oid: *const ::libc::c_char, completion: rados_completion_t, buf: *const ::libc::c_char, len: size_t) -> ::libc::c_int; pub fn rados_aio_remove(io: rados_ioctx_t, oid: *const ::libc::c_char, completion: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_read(io: rados_ioctx_t, oid: *const ::libc::c_char, completion: rados_completion_t, buf: *mut ::libc::c_char, len: size_t, off: uint64_t) -> ::libc::c_int; pub fn rados_aio_flush(io: rados_ioctx_t) -> ::libc::c_int; pub fn rados_aio_flush_async(io: rados_ioctx_t, completion: rados_completion_t) -> ::libc::c_int; pub fn rados_aio_stat(io: rados_ioctx_t, o: *const ::libc::c_char, completion: rados_completion_t, psize: *mut uint64_t, pmtime: *mut time_t) -> ::libc::c_int; pub fn rados_aio_cancel(io: rados_ioctx_t, completion: rados_completion_t) -> ::libc::c_int; pub fn rados_watch(io: rados_ioctx_t, o: *const ::libc::c_char, ver: uint64_t, cookie: *mut uint64_t, watchcb: rados_watchcb_t, arg: *mut ::libc::c_void) -> ::libc::c_int; pub fn rados_watch2(io: rados_ioctx_t, o: *const ::libc::c_char, cookie: *mut uint64_t, watchcb: rados_watchcb2_t, watcherrcb: rados_watcherrcb_t, arg: *mut ::libc::c_void) -> ::libc::c_int; pub fn rados_watch_check(io: rados_ioctx_t, cookie: uint64_t) -> ::libc::c_int; pub fn rados_unwatch(io: rados_ioctx_t, o: *const ::libc::c_char, cookie: uint64_t) -> ::libc::c_int; pub fn rados_unwatch2(io: rados_ioctx_t, cookie: uint64_t) -> ::libc::c_int; pub fn rados_notify(io: rados_ioctx_t, o: *const ::libc::c_char, ver: uint64_t, buf: *const ::libc::c_char, buf_len: ::libc::c_int) -> ::libc::c_int; pub fn rados_notify2(io: rados_ioctx_t, o: *const ::libc::c_char, buf: *const ::libc::c_char, buf_len: ::libc::c_int, timeout_ms: uint64_t, reply_buffer: *mut *mut ::libc::c_char, reply_buffer_len: *mut size_t) -> ::libc::c_int; pub fn rados_notify_ack(io: rados_ioctx_t, o: *const ::libc::c_char, notify_id: uint64_t, cookie: uint64_t, buf: *const ::libc::c_char, buf_len: ::libc::c_int) -> ::libc::c_int; pub fn rados_watch_flush(cluster: rados_t) -> ::libc::c_int; pub fn rados_set_alloc_hint(io: rados_ioctx_t, o: *const ::libc::c_char, expected_object_size: uint64_t, expected_write_size: uint64_t) -> ::libc::c_int; pub fn rados_create_write_op() -> rados_write_op_t; pub fn rados_release_write_op(write_op: rados_write_op_t) -> (); pub fn rados_write_op_set_flags(write_op: rados_write_op_t, flags: ::libc::c_int) -> (); pub fn rados_write_op_assert_exists(write_op: rados_write_op_t) -> (); pub fn rados_write_op_assert_version(write_op: rados_write_op_t, ver: uint64_t) -> (); pub fn rados_write_op_cmpxattr(write_op: rados_write_op_t, name: *const ::libc::c_char, comparison_operator: uint8_t, value: *const ::libc::c_char, value_len: size_t) -> (); pub fn rados_write_op_omap_cmp(write_op: rados_write_op_t, key: *const ::libc::c_char, comparison_operator: uint8_t, val: *const ::libc::c_char, val_len: size_t, prval: *mut ::libc::c_int) -> (); pub fn rados_write_op_setxattr(write_op: rados_write_op_t, name: *const ::libc::c_char, value: *const ::libc::c_char, value_len: size_t) -> (); pub fn rados_write_op_rmxattr(write_op: rados_write_op_t, name: *const ::libc::c_char) -> (); pub fn rados_write_op_create(write_op: rados_write_op_t, exclusive: ::libc::c_int, category: *const ::libc::c_char) -> (); pub fn rados_write_op_write(write_op: rados_write_op_t, buffer: *const ::libc::c_char, len: size_t, offset: uint64_t) -> (); pub fn rados_write_op_write_full(write_op: rados_write_op_t, buffer: *const ::libc::c_char, len: size_t) -> (); pub fn rados_write_op_append(write_op: rados_write_op_t, buffer: *const ::libc::c_char, len: size_t) -> (); pub fn rados_write_op_remove(write_op: rados_write_op_t) -> (); pub fn rados_write_op_truncate(write_op: rados_write_op_t, offset: uint64_t) -> (); pub fn rados_write_op_zero(write_op: rados_write_op_t, offset: uint64_t, len: uint64_t) -> (); pub fn rados_write_op_exec(write_op: rados_write_op_t, cls: *const ::libc::c_char, method: *const ::libc::c_char, in_buf: *const ::libc::c_char, in_len: size_t, prval: *mut ::libc::c_int) -> (); pub fn rados_write_op_omap_set(write_op: rados_write_op_t, keys: *const *const ::libc::c_char, vals: *const *const ::libc::c_char, lens: *const size_t, num: size_t) -> (); pub fn rados_write_op_omap_rm_keys(write_op: rados_write_op_t, keys: *const *const ::libc::c_char, keys_len: size_t) -> (); pub fn rados_write_op_omap_clear(write_op: rados_write_op_t) -> (); pub fn rados_write_op_set_alloc_hint(write_op: rados_write_op_t, expected_object_size: uint64_t, expected_write_size: uint64_t) -> (); pub fn rados_write_op_operate(write_op: rados_write_op_t, io: rados_ioctx_t,<|fim▁hole|> oid: *const ::libc::c_char, mtime: *mut time_t, flags: ::libc::c_int) -> ::libc::c_int; pub fn rados_aio_write_op_operate(write_op: rados_write_op_t, io: rados_ioctx_t, completion: rados_completion_t, oid: *const ::libc::c_char, mtime: *mut time_t, flags: ::libc::c_int) -> ::libc::c_int; pub fn rados_create_read_op() -> rados_read_op_t; pub fn rados_release_read_op(read_op: rados_read_op_t) -> (); pub fn rados_read_op_set_flags(read_op: rados_read_op_t, flags: ::libc::c_int) -> (); pub fn rados_read_op_assert_exists(read_op: rados_read_op_t) -> (); pub fn rados_read_op_assert_version(write_op: rados_read_op_t, ver: uint64_t) -> (); pub fn rados_read_op_cmpxattr(read_op: rados_read_op_t, name: *const ::libc::c_char, comparison_operator: uint8_t, value: *const ::libc::c_char, value_len: size_t) -> (); pub fn rados_read_op_getxattrs(read_op: rados_read_op_t, iter: *mut rados_xattrs_iter_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_omap_cmp(read_op: rados_read_op_t, key: *const ::libc::c_char, comparison_operator: uint8_t, val: *const ::libc::c_char, val_len: size_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_stat(read_op: rados_read_op_t, psize: *mut uint64_t, pmtime: *mut time_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_read(read_op: rados_read_op_t, offset: uint64_t, len: size_t, buf: *mut ::libc::c_char, bytes_read: *mut size_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_exec(read_op: rados_read_op_t, cls: *const ::libc::c_char, method: *const ::libc::c_char, in_buf: *const ::libc::c_char, in_len: size_t, out_buf: *mut *mut ::libc::c_char, out_len: *mut size_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_exec_user_buf(read_op: rados_read_op_t, cls: *const ::libc::c_char, method: *const ::libc::c_char, in_buf: *const ::libc::c_char, in_len: size_t, out_buf: *mut ::libc::c_char, out_len: size_t, used_len: *mut size_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_omap_get_vals(read_op: rados_read_op_t, start_after: *const ::libc::c_char, filter_prefix: *const ::libc::c_char, max_return: uint64_t, iter: *mut rados_omap_iter_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_omap_get_keys(read_op: rados_read_op_t, start_after: *const ::libc::c_char, max_return: uint64_t, iter: *mut rados_omap_iter_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_omap_get_vals_by_keys(read_op: rados_read_op_t, keys: *const *const ::libc::c_char, keys_len: size_t, iter: *mut rados_omap_iter_t, prval: *mut ::libc::c_int) -> (); pub fn rados_read_op_operate(read_op: rados_read_op_t, io: rados_ioctx_t, oid: *const ::libc::c_char, flags: ::libc::c_int) -> ::libc::c_int; pub fn rados_aio_read_op_operate(read_op: rados_read_op_t, io: rados_ioctx_t, completion: rados_completion_t, oid: *const ::libc::c_char, flags: ::libc::c_int) -> ::libc::c_int; pub fn rados_lock_exclusive(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char, cookie: *const ::libc::c_char, desc: *const ::libc::c_char, duration: *mut timeval, flags: uint8_t) -> ::libc::c_int; pub fn rados_lock_shared(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char, cookie: *const ::libc::c_char, tag: *const ::libc::c_char, desc: *const ::libc::c_char, duration: *mut timeval, flags: uint8_t) -> ::libc::c_int; pub fn rados_unlock(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char, cookie: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_list_lockers(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char, exclusive: *mut ::libc::c_int, tag: *mut ::libc::c_char, tag_len: *mut size_t, clients: *mut ::libc::c_char, clients_len: *mut size_t, cookies: *mut ::libc::c_char, cookies_len: *mut size_t, addrs: *mut ::libc::c_char, addrs_len: *mut size_t) -> ssize_t; pub fn rados_break_lock(io: rados_ioctx_t, o: *const ::libc::c_char, name: *const ::libc::c_char, client: *const ::libc::c_char, cookie: *const ::libc::c_char) -> ::libc::c_int; pub fn rados_blacklist_add(cluster: rados_t, client_address: *mut ::libc::c_char, expire_seconds: uint32_t) -> ::libc::c_int; pub fn rados_mon_command(cluster: rados_t, cmd: *mut *const ::libc::c_char, cmdlen: size_t, inbuf: *const ::libc::c_char, inbuflen: size_t, outbuf: *mut *mut ::libc::c_char, outbuflen: *mut size_t, outs: *mut *mut ::libc::c_char, outslen: *mut size_t) -> ::libc::c_int; pub fn rados_mon_command_target(cluster: rados_t, name: *const ::libc::c_char, cmd: *mut *const ::libc::c_char, cmdlen: size_t, inbuf: *const ::libc::c_char, inbuflen: size_t, outbuf: *mut *mut ::libc::c_char, outbuflen: *mut size_t, outs: *mut *mut ::libc::c_char, outslen: *mut size_t) -> ::libc::c_int; pub fn rados_buffer_free(buf: *mut ::libc::c_char) -> (); pub fn rados_osd_command(cluster: rados_t, osdid: ::libc::c_int, cmd: *mut *const ::libc::c_char, cmdlen: size_t, inbuf: *const ::libc::c_char, inbuflen: size_t, outbuf: *mut *mut ::libc::c_char, outbuflen: *mut size_t, outs: *mut *mut ::libc::c_char, outslen: *mut size_t) -> ::libc::c_int; pub fn rados_pg_command(cluster: rados_t, pgstr: *const ::libc::c_char, cmd: *mut *const ::libc::c_char, cmdlen: size_t, inbuf: *const ::libc::c_char, inbuflen: size_t, outbuf: *mut *mut ::libc::c_char, outbuflen: *mut size_t, outs: *mut *mut ::libc::c_char, outslen: *mut size_t) -> ::libc::c_int; pub fn rados_monitor_log(cluster: rados_t, level: *const ::libc::c_char, cb: rados_log_callback_t, arg: *mut ::libc::c_void) -> ::libc::c_int; }<|fim▁end|>
<|file_name|>1138_08_03-flood-fill.py<|end_file_name|><|fim▁begin|>""" Crawls a terrain raster from a starting point and "floods" everything at the same or lower elevation by producing a mask image of 1,0 values. """ import numpy as np from linecache import getline def floodFill(c,r,mask): """ Crawls a mask array containing only 1 and 0 values from the starting point (c=column, r=row - a.k.a. x,y) and returns an array with all 1 values connected to the starting cell. This algorithm performs a 4-way <|fim▁hole|> """ # cells already filled filled = set() # cells to fill fill = set() fill.add((c,r)) width = mask.shape[1]-1 height = mask.shape[0]-1 # Our output inundation array flood = np.zeros_like(mask, dtype=np.int8) # Loop through and modify the cells which # need to be checked. while fill: # Grab a cell x,y = fill.pop() if y == height or x == width or x < 0 or y < 0: # Don't fill continue if mask[y][x] == 1: # Do fill flood[y][x]=1 filled.add((x,y)) # Check neighbors for 1 values west =(x-1,y) east = (x+1,y) north = (x,y-1) south = (x,y+1) if not west in filled: fill.add(west) if not east in filled: fill.add(east) if not north in filled: fill.add(north) if not south in filled: fill.add(south) return flood source = "terrain.asc" target = "flood.asc" print "Opening image..." img = np.loadtxt(source, skiprows=6) print "Image opened" a = np.where(img<70, 1,0) print "Image masked" # Parse the headr using a loop and # the built-in linecache module hdr = [getline(source, i) for i in range(1,7)] values = [float(h.split(" ")[-1].strip()) for h in hdr] cols,rows,lx,ly,cell,nd = values xres = cell yres = cell * -1 # Starting point for the # flood inundation sx = 2582 sy = 2057 print "Beginning flood fill" fld = floodFill(sx,sy, a) print "Finished Flood fill" header="" for i in range(6): header += hdr[i] print "Saving grid" # Open the output file, add the hdr, save the array with open(target, "wb") as f: f.write(header) np.savetxt(f, fld, fmt="%1i") print "Done!"<|fim▁end|>
check non-recursively.
<|file_name|>invalidinstruction.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************<|fim▁hole|>** Copyright (C) 2016 Christian Gagneraud <[email protected]> ** All rights reserved. ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 3 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL3 included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 3 requirements will be met: ** https://www.gnu.org/licenses/lgpl-3.0.html. ** ****************************************************************************/ #include "invalidinstruction.h" #include "errorinstructionresult.h" InvalidInstruction::InvalidInstruction(const QString &instructionId, const QString &operationName): Instruction(instructionId), m_operationName(operationName) { } InstructionResult *InvalidInstruction::execute(InstructionExecutor *executor) const { Q_UNUSED(executor); return new ErrorInstructionResult(instructionId(), QString("%1: Invalid instruction").arg(m_operationName)); } QString InvalidInstruction::toString() const { return QString("%1: !INVALID_INSTRUCTION!") .arg(instructionId()); }<|fim▁end|>
**
<|file_name|>init-tslint.ts<|end_file_name|><|fim▁begin|>import * as oclif from '@oclif/command'; import * as path from 'path'; import {writeJsonFile} from '../utils'; export const commandName = path.basename(__filename, '.js'); // tslint:disable-next-line:no-default-export export default class InitTsLint extends oclif.Command { public static description = 'Creates a TSLint configuration file that extends this configuration preset.'; public static examples = [ `$ ts-config ${commandName}`, `$ ts-config ${commandName} --config='tslint.build.json' --force` ]; public static flags = { help: oclif.flags.help({char: 'h'}), config: oclif.flags.string({ char: 'c', default: 'tslint.json' }), force: oclif.flags.boolean({ char: 'f', description: 'overwrite an existing configuration file' }) }; public async run(): Promise<void> { const {flags} = this.parse(InitTsLint); writeJsonFile( flags.config as string, { extends: 'ts-config', linterOptions: {exclude: ['**/lib/**', '**/node_modules/**']} },<|fim▁hole|> return; } }<|fim▁end|>
flags.force );
<|file_name|>if28.py<|end_file_name|><|fim▁begin|>from polyphony import testbench def g(x): if x == 0: return 0 return 1 def h(x): if x == 0: pass def f(v, i, j, k): if i == 0: return v elif i == 1: return v<|fim▁hole|> elif i == 2: h(g(j) + g(k)) return v elif i == 3: for m in range(j): v += 2 return v else: for n in range(i): v += 1 return v def if28(code, r1, r2, r3, r4): if code == 0: return f(r1, r2, r3, r4) return 0 @testbench def test(): assert 1 == if28(0, 1, 1, 0, 0) assert 2 == if28(0, 2, 0, 0, 0) assert 3 == if28(0, 3, 1, 0, 0) assert 4 == if28(0, 4, 2, 0, 0) assert 5 == if28(0, 5, 2, 1, 1) assert 6 == if28(0, 6, 2, 2, 2) assert 7 == if28(0, 7, 3, 0, 0) assert 10 == if28(0, 8, 3, 1, 1) assert 13 == if28(0, 9, 3, 2, 2) assert 14 == if28(0, 10, 4, 0, 0) test()<|fim▁end|>
<|file_name|>equality_compare.cc<|end_file_name|><|fim▁begin|>#include "firestore/src/swig/equality_compare.h" namespace { template <typename T> bool EqualityCompareHelper(const T* lhs, const T* rhs) { return lhs == rhs || (lhs != nullptr && rhs != nullptr && *lhs == *rhs); } } // namespace namespace firebase { namespace firestore { namespace csharp { <|fim▁hole|> bool QuerySnapshotEquals(const QuerySnapshot* lhs, const QuerySnapshot* rhs) { return EqualityCompareHelper(lhs, rhs); } bool DocumentSnapshotEquals(const DocumentSnapshot* lhs, const DocumentSnapshot* rhs) { return EqualityCompareHelper(lhs, rhs); } bool DocumentChangeEquals(const DocumentChange* lhs, const DocumentChange* rhs) { return EqualityCompareHelper(lhs, rhs); } } // namespace csharp } // namespace firestore } // namespace firebase<|fim▁end|>
bool QueryEquals(const Query* lhs, const Query* rhs) { return EqualityCompareHelper(lhs, rhs); }
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding=utf-8 """ The full documentation is at https://python_hangman.readthedocs.org. """ try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest import sys errno = pytest.main(self.test_args) sys.exit(errno) with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = ['click', 'future'] test_requirements = ['pytest', 'mock'] setup( # :off name='python_hangman', version='2.2.2', description='Python Hangman TDD/MVC demonstration.', long_description='\n\n'.join([readme, history]), author='Manu Phatak', author_email='[email protected]', url='https://github.com/bionikspoon/python_hangman', packages=['hangman',], package_dir={'hangman':'hangman'},<|fim▁hole|> zip_safe=False, use_2to3=True, cmdclass={'test': PyTest}, keywords='python_hangman Manu Phatak', entry_points={'console_scripts': ['hangman = hangman.__main__:cli']}, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Puzzle Games', 'Topic :: Terminals', ], test_suite='tests', tests_require=test_requirements ) # :on<|fim▁end|>
include_package_data=True, install_requires=requirements, license='MIT',
<|file_name|>prelude.rs<|end_file_name|><|fim▁begin|>pub use crate::ansi::AnsiString; pub use crate::engine::{factory::*, fuzzy::FuzzyAlgorithm}; pub use crate::event::Event; pub use crate::helper::item_reader::{SkimItemReader, SkimItemReaderOption}; pub use crate::helper::selector::DefaultSkimSelector; pub use crate::options::{SkimOptions, SkimOptionsBuilder}; pub use crate::output::SkimOutput; pub use crate::*;<|fim▁hole|>pub use std::cell::RefCell; pub use std::rc::Rc; pub use std::sync::atomic::{AtomicUsize, Ordering}; pub use std::sync::Arc; pub use tuikit::event::Key;<|fim▁end|>
pub use crossbeam::channel::{bounded, unbounded, Receiver, Sender}; pub use std::borrow::Cow;
<|file_name|>ReportSynthesisKeyPartnershipPmu.java<|end_file_name|><|fim▁begin|>package org.cgiar.ccafs.marlo.data.model; // Generated Jun 20, 2018 1:50:25 PM by Hibernate Tools 3.4.0.CR1 import org.cgiar.ccafs.marlo.data.IAuditLog; import com.google.gson.annotations.Expose; /** * ReportSynthesisMeliaStudy generated by hbm2java */ public class ReportSynthesisKeyPartnershipPmu extends MarloAuditableEntity implements java.io.Serializable, IAuditLog { private static final long serialVersionUID = 5761871053421733437L; @Expose private ReportSynthesisKeyPartnership reportSynthesisKeyPartnership; @Expose private ReportSynthesisKeyPartnershipExternal reportSynthesisKeyPartnershipExternal; public ReportSynthesisKeyPartnershipPmu() { } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } ReportSynthesisKeyPartnershipPmu other = (ReportSynthesisKeyPartnershipPmu) obj; if (this.getReportSynthesisKeyPartnershipExternal() == null) { if (other.getReportSynthesisKeyPartnershipExternal() != null) { return false; } } else if (!this.getReportSynthesisKeyPartnershipExternal() .equals(other.getReportSynthesisKeyPartnershipExternal())) { return false; } if (this.getReportSynthesisKeyPartnership() == null) { if (other.getReportSynthesisKeyPartnership() != null) { return false; } } else if (!this.getReportSynthesisKeyPartnership().getId() .equals(other.getReportSynthesisKeyPartnership().getId())) { return false; } return true; } @Override public String getLogDeatil() { StringBuilder sb = new StringBuilder(); sb.append("Id : ").append(this.getId()); return sb.toString(); } public ReportSynthesisKeyPartnership getReportSynthesisKeyPartnership() { return reportSynthesisKeyPartnership; } public ReportSynthesisKeyPartnershipExternal getReportSynthesisKeyPartnershipExternal() { return reportSynthesisKeyPartnershipExternal; <|fim▁hole|> this.reportSynthesisKeyPartnership = reportSynthesisKeyPartnership; } public void setReportSynthesisKeyPartnershipExternal( ReportSynthesisKeyPartnershipExternal reportSynthesisKeyPartnershipExternal) { this.reportSynthesisKeyPartnershipExternal = reportSynthesisKeyPartnershipExternal; } }<|fim▁end|>
} public void setReportSynthesisKeyPartnership(ReportSynthesisKeyPartnership reportSynthesisKeyPartnership) {
<|file_name|>Question.go<|end_file_name|><|fim▁begin|>package lib import ( "log" "strings" ) type ( Question struct { RelatesTo struct { Answers []string `json:"answers"` Save bool `json:"save"` SaveTag string `json:"saveTag"` } `json:"relatesTo"` Context []string `json:"context"` QuestionText string `json:"question"` PossibleAnswers []string `json:"answers"` } Questions []*Question ) func (this Questions) First() *Question { if len(this) > 0 { return this[0] } return nil } func (this Questions) next(prevAnswer string) (*Question, bool) {<|fim▁hole|> } } } return nil, false } func (this Questions) nextFrom(prevAnswers ...string) (*Question, bool) { for i := range prevAnswers { if nxt, sv := this.next(prevAnswers[i]); nxt != nil { log.Println("got it from sticker ...") return nxt, sv } } return nil, false } func (this *Question) makeKeyboard() Keyboard { keyboard := Keyboard{} for i := range this.PossibleAnswers { keyboard = append(keyboard, []string{this.PossibleAnswers[i]}) } return keyboard }<|fim▁end|>
for i := range this { for a := range this[i].RelatesTo.Answers { if strings.EqualFold(this[i].RelatesTo.Answers[a], prevAnswer) { return this[i], this[i].RelatesTo.Save
<|file_name|>psd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import math, logging, threading, concurrent.futures import numpy import simplespectral from soapypower import threadpool logger = logging.getLogger(__name__) class PSD: """Compute averaged power spectral density using Welch's method""" def __init__(self, bins, sample_rate, fft_window='hann', fft_overlap=0.5, crop_factor=0, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, max_threads=0, max_queue_size=0): self._bins = bins self._sample_rate = sample_rate self._fft_window = fft_window self._fft_overlap = fft_overlap self._fft_overlap_bins = math.floor(self._bins * self._fft_overlap) self._crop_factor = crop_factor self._log_scale = log_scale self._remove_dc = remove_dc self._detrend = detrend self._lnb_lo = lnb_lo self._executor = threadpool.ThreadPoolExecutor( max_workers=max_threads, max_queue_size=max_queue_size, thread_name_prefix='PSD_thread' ) self._base_freq_array = numpy.fft.fftfreq(self._bins, 1 / self._sample_rate) def set_center_freq(self, center_freq): """Set center frequency and clear averaged PSD data""" psd_state = { 'repeats': 0, 'freq_array': self._base_freq_array + self._lnb_lo + center_freq, 'pwr_array': None, 'update_lock': threading.Lock(), 'futures': [], } return psd_state def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_array = numpy.fft.fftshift(psd_state['pwr_array']) if self._crop_factor: crop_bins_half = round((self._crop_factor * self._bins) / 2) freq_array = freq_array[crop_bins_half:-crop_bins_half] pwr_array = pwr_array[crop_bins_half:-crop_bins_half] if psd_state['repeats'] > 1: pwr_array = pwr_array / psd_state['repeats'] if self._log_scale: pwr_array = 10 * numpy.log10(pwr_array) return (freq_array, pwr_array) def wait_for_result(self, psd_state): """Wait for all PSD threads to finish and return result""" if len(psd_state['futures']) > 1: concurrent.futures.wait(psd_state['futures']) elif psd_state['futures']: psd_state['futures'][0].result() return self.result(psd_state) def result_async(self, psd_state):<|fim▁hole|> """Return freqs and averaged PSD for given center frequency (asynchronously in another thread)""" return self._executor.submit(self.wait_for_result, psd_state) def _release_future_memory(self, future): """Remove result from future to release memory""" future._result = None def update(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency""" freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins, window=self._fft_window, noverlap=self._fft_overlap_bins, detrend=self._detrend) if self._remove_dc: pwr_array[0] = (pwr_array[1] + pwr_array[-1]) / 2 with psd_state['update_lock']: psd_state['repeats'] += 1 if psd_state['pwr_array'] is None: psd_state['pwr_array'] = pwr_array else: psd_state['pwr_array'] += pwr_array def update_async(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency (asynchronously in another thread)""" future = self._executor.submit(self.update, psd_state, samples_array) future.add_done_callback(self._release_future_memory) psd_state['futures'].append(future) return future<|fim▁end|>
<|file_name|>font.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Generic types for font stuff. use app_units::Au; use byteorder::{BigEndian, ReadBytesExt}; use cssparser::Parser; use num_traits::One; use parser::{Parse, ParserContext}; use std::fmt::{self, Write}; use std::io::Cursor; use style_traits::{CssWriter, KeywordsCollectFn, ParseError}; use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FeatureTagValue<Integer> { /// A four-character tag, packed into a u32 (one byte per character). pub tag: FontTag, /// The actual value. pub value: Integer, } impl<Integer> ToCss for FeatureTagValue<Integer> where Integer: One + ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.tag.to_css(dest)?; // Don't serialize the default value. if self.value != Integer::one() { dest.write_char(' ')?; self.value.to_css(dest)?; } Ok(()) } } /// Variation setting for a single feature, see: /// /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def #[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct VariationValue<Number> { /// A four-character tag, packed into a u32 (one byte per character). #[animation(constant)] pub tag: FontTag, /// The actual value. pub value: Number, } impl<Number> ComputeSquaredDistance for VariationValue<Number> where Number: ComputeSquaredDistance, { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.tag != other.tag { return Err(()); } self.value.compute_squared_distance(&other.value) } } /// A value both for font-variation-settings and font-feature-settings. #[css(comma)] #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct FontSettings<T>(#[css(if_empty = "normal", iterable)] pub Box<[T]>); impl<T> FontSettings<T> { /// Default value of font settings as `normal`. #[inline] pub fn normal() -> Self { FontSettings(vec![].into_boxed_slice()) } } impl<T: Parse> Parse for FontSettings<T> { /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if input.try(|i| i.expect_ident_matching("normal")).is_ok() { return Ok(Self::normal()); } Ok(FontSettings( input .parse_comma_separated(|i| T::parse(context, i))? .into_boxed_slice(), )) } } /// A font four-character tag, represented as a u32 for convenience. /// /// See: /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FontTag(pub u32); impl ToCss for FontTag { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { use byteorder::{BigEndian, ByteOrder}; use std::str; let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, self.0); str::from_utf8(&raw).unwrap_or_default().to_css(dest) } } impl Parse for FontTag { fn parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let location = input.current_source_location(); let tag = input.expect_string()?; // allowed strings of length 4 containing chars: <U+20, U+7E> if tag.len() != 4 || tag.as_bytes().iter().any(|c| *c < b' ' || *c > b'~') { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut raw = Cursor::new(tag.as_bytes()); Ok(FontTag(raw.read_u32::<BigEndian>().unwrap())) } } #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToCss)] /// Additional information for keyword-derived font sizes. pub struct KeywordInfo<Length> {<|fim▁hole|> #[css(skip)] pub factor: f32, /// An additional Au offset to add to the kw*factor in the case of calcs #[css(skip)] pub offset: Length, } impl<L> KeywordInfo<L> where Au: Into<L>, { /// KeywordInfo value for font-size: medium pub fn medium() -> Self { KeywordSize::Medium.into() } } impl<L> From<KeywordSize> for KeywordInfo<L> where Au: Into<L>, { fn from(x: KeywordSize) -> Self { KeywordInfo { kw: x, factor: 1., offset: Au(0).into(), } } } impl<L> SpecifiedValueInfo for KeywordInfo<L> { fn collect_completion_keywords(f: KeywordsCollectFn) { <KeywordSize as SpecifiedValueInfo>::collect_completion_keywords(f); } } /// CSS font keywords #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] #[allow(missing_docs)] pub enum KeywordSize { #[css(keyword = "xx-small")] XXSmall, XSmall, Small, Medium, Large, XLarge, #[css(keyword = "xx-large")] XXLarge, // This is not a real font keyword and will not parse // HTML font-size 7 corresponds to this value #[css(skip)] XXXLarge, } impl KeywordSize { /// Convert to an HTML <font size> value #[inline] pub fn html_size(self) -> u8 { self as u8 } } impl Default for KeywordSize { fn default() -> Self { KeywordSize::Medium } } /// A generic value for the `font-style` property. /// /// https://drafts.csswg.org/css-fonts-4/#font-style-prop #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero)] pub enum FontStyle<Angle> { #[animation(error)] Normal, #[animation(error)] Italic, #[value_info(starts_with_keyword)] Oblique(Angle), }<|fim▁end|>
/// The keyword used pub kw: KeywordSize, /// A factor to be multiplied by the computed size of the keyword
<|file_name|>RestQuery.js<|end_file_name|><|fim▁begin|>// An object that encapsulates everything we need to run a 'find' // operation, encoded in the REST API format. var Parse = require('parse/node').Parse; import { default as FilesController } from './Controllers/FilesController'; // restOptions can include: // skip // limit // order // count // include // keys // redirectClassNameForKey function RestQuery(config, auth, className, restWhere = {}, restOptions = {}) { this.config = config; this.auth = auth; this.className = className; this.restWhere = restWhere; this.response = null; this.findOptions = {}; if (!this.auth.isMaster) { this.findOptions.acl = this.auth.user ? [this.auth.user.id] : null; if (this.className == '_Session') { if (!this.findOptions.acl) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'This session token is invalid.'); } this.restWhere = { '$and': [this.restWhere, { 'user': { __type: 'Pointer', className: '_User', objectId: this.auth.user.id } }] }; } } this.doCount = false; // The format for this.include is not the same as the format for the // include option - it's the paths we should include, in order, // stored as arrays, taking into account that we need to include foo // before including foo.bar. Also it should dedupe. // For example, passing an arg of include=foo.bar,foo.baz could lead to // this.include = [['foo'], ['foo', 'baz'], ['foo', 'bar']] this.include = []; for (var option in restOptions) { switch(option) { case 'keys': this.keys = new Set(restOptions.keys.split(',')); this.keys.add('objectId'); this.keys.add('createdAt'); this.keys.add('updatedAt'); break; case 'count': this.doCount = true; break; case 'skip': case 'limit': this.findOptions[option] = restOptions[option]; break; case 'order': var fields = restOptions.order.split(','); var sortMap = {}; for (var field of fields) { if (field[0] == '-') { sortMap[field.slice(1)] = -1; } else { sortMap[field] = 1; } } this.findOptions.sort = sortMap; break; case 'include': var paths = restOptions.include.split(','); var pathSet = {}; for (var path of paths) { // Add all prefixes with a .-split to pathSet var parts = path.split('.'); for (var len = 1; len <= parts.length; len++) { pathSet[parts.slice(0, len).join('.')] = true; } } this.include = Object.keys(pathSet).sort((a, b) => { return a.length - b.length; }).map((s) => { return s.split('.'); }); break; case 'redirectClassNameForKey': this.redirectKey = restOptions.redirectClassNameForKey; this.redirectClassName = null; break; default: throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad option: ' + option); } } } // A convenient method to perform all the steps of processing a query // in order. // Returns a promise for the response - an object with optional keys // 'results' and 'count'. // TODO: consolidate the replaceX functions RestQuery.prototype.execute = function() { return Promise.resolve().then(() => { return this.buildRestWhere(); }).then(() => { return this.runFind(); }).then(() => { return this.runCount(); }).then(() => { return this.handleInclude(); }).then(() => { return this.response; }); }; RestQuery.prototype.buildRestWhere = function() { return Promise.resolve().then(() => { return this.getUserAndRoleACL(); }).then(() => { return this.redirectClassNameForKey(); }).then(() => { return this.validateClientClassCreation(); }).then(() => { return this.replaceSelect(); }).then(() => { return this.replaceDontSelect(); }).then(() => { return this.replaceInQuery(); }).then(() => { return this.replaceNotInQuery(); }); } // Uses the Auth object to get the list of roles, adds the user id RestQuery.prototype.getUserAndRoleACL = function() { if (this.auth.isMaster || !this.auth.user) { return Promise.resolve(); } return this.auth.getUserRoles().then((roles) => { roles.push(this.auth.user.id); this.findOptions.acl = roles; return Promise.resolve(); }); }; // Changes the className if redirectClassNameForKey is set. // Returns a promise. RestQuery.prototype.redirectClassNameForKey = function() { if (!this.redirectKey) { return Promise.resolve(); } // We need to change the class name based on the schema return this.config.database.redirectClassNameForKey( this.className, this.redirectKey).then((newClassName) => { this.className = newClassName; this.redirectClassName = newClassName; }); }; // Validates this operation against the allowClientClassCreation config. RestQuery.prototype.validateClientClassCreation = function() { let sysClass = ['_User', '_Installation', '_Role', '_Session', '_Product']; if (this.config.allowClientClassCreation === false && !this.auth.isMaster && sysClass.indexOf(this.className) === -1) { return this.config.database.collectionExists(this.className).then((hasClass) => { if (hasClass === true) { return Promise.resolve(); } throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'This user is not allowed to access ' + 'non-existent class: ' + this.className); }); } else { return Promise.resolve(); } }; // Replaces a $inQuery clause by running the subquery, if there is an // $inQuery clause. // The $inQuery clause turns into an $in with values that are just // pointers to the objects returned in the subquery. RestQuery.prototype.replaceInQuery = function() { var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery'); if (!inQueryObject) { return; } // The inQuery value must have precisely two keys - where and className var inQueryValue = inQueryObject['$inQuery']; if (!inQueryValue.where || !inQueryValue.className) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $inQuery'); } var subquery = new RestQuery( this.config, this.auth, inQueryValue.className, inQueryValue.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push({ __type: 'Pointer', className: inQueryValue.className, objectId: result.objectId }); } delete inQueryObject['$inQuery']; if (Array.isArray(inQueryObject['$in'])) { inQueryObject['$in'] = inQueryObject['$in'].concat(values); } else { inQueryObject['$in'] = values; } // Recurse to repeat return this.replaceInQuery(); }); }; // Replaces a $notInQuery clause by running the subquery, if there is an // $notInQuery clause. // The $notInQuery clause turns into a $nin with values that are just // pointers to the objects returned in the subquery. RestQuery.prototype.replaceNotInQuery = function() { var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery'); if (!notInQueryObject) { return; } // The notInQuery value must have precisely two keys - where and className var notInQueryValue = notInQueryObject['$notInQuery']; if (!notInQueryValue.where || !notInQueryValue.className) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $notInQuery'); } var subquery = new RestQuery( this.config, this.auth, notInQueryValue.className, notInQueryValue.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push({ __type: 'Pointer', className: notInQueryValue.className, objectId: result.objectId }); } delete notInQueryObject['$notInQuery']; if (Array.isArray(notInQueryObject['$nin'])) { notInQueryObject['$nin'] = notInQueryObject['$nin'].concat(values); } else { notInQueryObject['$nin'] = values; } // Recurse to repeat return this.replaceNotInQuery(); }); }; // Replaces a $select clause by running the subquery, if there is a // $select clause. // The $select clause turns into an $in with values selected out of // the subquery. // Returns a possible-promise. RestQuery.prototype.replaceSelect = function() { var selectObject = findObjectWithKey(this.restWhere, '$select'); if (!selectObject) { return; } // The select value must have precisely two keys - query and key var selectValue = selectObject['$select']; // iOS SDK don't send where if not set, let it pass if (!selectValue.query || !selectValue.key || typeof selectValue.query !== 'object' || !selectValue.query.className || Object.keys(selectValue).length !== 2) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $select'); } var subquery = new RestQuery( this.config, this.auth, selectValue.query.className, selectValue.query.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push(result[selectValue.key]); } delete selectObject['$select']; if (Array.isArray(selectObject['$in'])) { selectObject['$in'] = selectObject['$in'].concat(values); } else { selectObject['$in'] = values; }<|fim▁hole|> }) }; // Replaces a $dontSelect clause by running the subquery, if there is a // $dontSelect clause. // The $dontSelect clause turns into an $nin with values selected out of // the subquery. // Returns a possible-promise. RestQuery.prototype.replaceDontSelect = function() { var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect'); if (!dontSelectObject) { return; } // The dontSelect value must have precisely two keys - query and key var dontSelectValue = dontSelectObject['$dontSelect']; if (!dontSelectValue.query || !dontSelectValue.key || typeof dontSelectValue.query !== 'object' || !dontSelectValue.query.className || Object.keys(dontSelectValue).length !== 2) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $dontSelect'); } var subquery = new RestQuery( this.config, this.auth, dontSelectValue.query.className, dontSelectValue.query.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push(result[dontSelectValue.key]); } delete dontSelectObject['$dontSelect']; if (Array.isArray(dontSelectObject['$nin'])) { dontSelectObject['$nin'] = dontSelectObject['$nin'].concat(values); } else { dontSelectObject['$nin'] = values; } // Keep replacing $dontSelect clauses return this.replaceDontSelect(); }) }; // Returns a promise for whether it was successful. // Populates this.response with an object that only has 'results'. RestQuery.prototype.runFind = function() { return this.config.database.find( this.className, this.restWhere, this.findOptions).then((results) => { if (this.className == '_User') { for (var result of results) { delete result.password; } } this.config.filesController.expandFilesInObject(this.config, results); if (this.keys) { var keySet = this.keys; results = results.map((object) => { var newObject = {}; for (var key in object) { if (keySet.has(key)) { newObject[key] = object[key]; } } return newObject; }); } if (this.redirectClassName) { for (var r of results) { r.className = this.redirectClassName; } } this.response = {results: results}; }); }; // Returns a promise for whether it was successful. // Populates this.response.count with the count RestQuery.prototype.runCount = function() { if (!this.doCount) { return; } this.findOptions.count = true; delete this.findOptions.skip; delete this.findOptions.limit; return this.config.database.find( this.className, this.restWhere, this.findOptions).then((c) => { this.response.count = c; }); }; // Augments this.response with data at the paths provided in this.include. RestQuery.prototype.handleInclude = function() { if (this.include.length == 0) { return; } var pathResponse = includePath(this.config, this.auth, this.response, this.include[0]); if (pathResponse.then) { return pathResponse.then((newResponse) => { this.response = newResponse; this.include = this.include.slice(1); return this.handleInclude(); }); } else if (this.include.length > 0) { this.include = this.include.slice(1); return this.handleInclude(); } return pathResponse; }; // Adds included values to the response. // Path is a list of field names. // Returns a promise for an augmented response. function includePath(config, auth, response, path) { var pointers = findPointers(response.results, path); if (pointers.length == 0) { return response; } var className = null; var objectIds = {}; for (var pointer of pointers) { if (className === null) { className = pointer.className; } else { if (className != pointer.className) { throw new Parse.Error(Parse.Error.INVALID_JSON, 'inconsistent type data for include'); } } objectIds[pointer.objectId] = true; } if (!className) { throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad pointers'); } // Get the objects for all these object ids var where = {'objectId': {'$in': Object.keys(objectIds)}}; var query = new RestQuery(config, auth, className, where); return query.execute().then((includeResponse) => { var replace = {}; for (var obj of includeResponse.results) { obj.__type = 'Object'; obj.className = className; if(className == "_User"){ delete obj.sessionToken; } replace[obj.objectId] = obj; } var resp = { results: replacePointers(response.results, path, replace) }; if (response.count) { resp.count = response.count; } return resp; }); } // Object may be a list of REST-format object to find pointers in, or // it may be a single object. // If the path yields things that aren't pointers, this throws an error. // Path is a list of fields to search into. // Returns a list of pointers in REST format. function findPointers(object, path) { if (object instanceof Array) { var answer = []; for (var x of object) { answer = answer.concat(findPointers(x, path)); } return answer; } if (typeof object !== 'object') { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'can only include pointer fields'); } if (path.length == 0) { if (object.__type == 'Pointer') { return [object]; } throw new Parse.Error(Parse.Error.INVALID_QUERY, 'can only include pointer fields'); } var subobject = object[path[0]]; if (!subobject) { return []; } return findPointers(subobject, path.slice(1)); } // Object may be a list of REST-format objects to replace pointers // in, or it may be a single object. // Path is a list of fields to search into. // replace is a map from object id -> object. // Returns something analogous to object, but with the appropriate // pointers inflated. function replacePointers(object, path, replace) { if (object instanceof Array) { return object.map((obj) => replacePointers(obj, path, replace)); } if (typeof object !== 'object') { return object; } if (path.length == 0) { if (object.__type == 'Pointer') { return replace[object.objectId]; } return object; } var subobject = object[path[0]]; if (!subobject) { return object; } var newsub = replacePointers(subobject, path.slice(1), replace); var answer = {}; for (var key in object) { if (key == path[0]) { answer[key] = newsub; } else { answer[key] = object[key]; } } return answer; } // Finds a subobject that has the given key, if there is one. // Returns undefined otherwise. function findObjectWithKey(root, key) { if (typeof root !== 'object') { return; } if (root instanceof Array) { for (var item of root) { var answer = findObjectWithKey(item, key); if (answer) { return answer; } } } if (root && root[key]) { return root; } for (var subkey in root) { var answer = findObjectWithKey(root[subkey], key); if (answer) { return answer; } } } module.exports = RestQuery;<|fim▁end|>
// Keep replacing $select clauses return this.replaceSelect();
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate clap; extern crate yaml_rust; extern crate lxd; use std::env; use std::fs::File; use std::io::Read; use clap::{App, Arg, ArgMatches, SubCommand}; use yaml_rust::YamlLoader; use lxd::{Container,LxdServer}; fn create_dividing_line(widths: &Vec<usize>) -> String { let mut dividing_line = String::new(); dividing_line.push_str("+"); for width in widths { dividing_line.push_str(&format!("{:-^1$}", "", width + 2)); dividing_line.push_str("+"); } dividing_line.push_str("\n"); dividing_line } fn create_header_line(headers: &Vec<&str>, widths: &Vec<usize>) -> String { let mut header_line = String::new(); header_line.push_str("|"); for (n, header) in headers.iter().enumerate() { header_line.push_str(&format!("{:^1$}", &header, widths[n] + 2)); header_line.push_str("|"); } header_line.push_str("\n"); header_line } fn create_content_line(item: &Vec<String>, widths: &Vec<usize>) -> String { let mut content_line = String::new(); content_line.push_str("|"); for (n, column_content) in item.iter().enumerate() { content_line.push_str(" "); content_line.push_str(&format!("{:1$}", &column_content, widths[n] + 1)); content_line.push_str("|"); } content_line.push_str("\n"); content_line } fn format_output(headers: &Vec<&str>, items: &Vec<Vec<String>>) -> String { let mut widths = Vec::new(); for header in headers { widths.push(header.len()); } for item in items { for (n, column) in item.iter().enumerate() { if column.len() > widths[n] { widths[n] = column.len(); }<|fim▁hole|> } let dividing_line = create_dividing_line(&widths); let mut output_string = String::new(); output_string.push_str(&dividing_line); output_string.push_str(&create_header_line(headers, &widths)); output_string.push_str(&dividing_line); for item in items { output_string.push_str(&create_content_line(item, &widths)); } output_string.push_str(&dividing_line); output_string } fn prepare_container_line(c: &Container) -> Vec<String> { let mut ipv4_address = String::new(); let mut ipv6_address = String::new(); for ip in &c.status.ips { if ip.protocol == "IPV4" && ip.address != "127.0.0.1" { ipv4_address = ip.address.clone(); } if ip.protocol == "IPV6" && ip.address != "::1" { ipv6_address = ip.address.clone(); } } let ephemeral = if c.ephemeral { "YES" } else { "NO" }; vec![c.name.clone(), c.status.status.clone().to_uppercase(), ipv4_address.to_string(), ipv6_address.to_string(), ephemeral.to_string(), c.snapshot_urls.len().to_string()] } fn list(matches: &ArgMatches) { let home_dir = env::var("HOME").unwrap(); let mut config_file = File::open(home_dir.clone() + "/.config/lxc/config.yml").unwrap(); let mut file_contents = String::new(); config_file.read_to_string(&mut file_contents).unwrap(); let lxd_config = YamlLoader::load_from_str(&file_contents).unwrap(); let default_remote = lxd_config[0]["default-remote"].as_str().unwrap(); let remote = matches.value_of("resource").unwrap_or(default_remote); let lxd_server = match lxd_config[0]["remotes"][remote]["addr"].as_str() { Some(remote_addr) => remote_addr, None => panic!("No remote named {} configured", remote) }; let server = LxdServer::new( lxd_server, &(home_dir.clone() + "/.config/lxc/client.crt"), &(home_dir.clone() + "/.config/lxc/client.key") ); let headers = vec!["NAME", "STATE", "IPV4", "IPV6", "EPHEMERAL", "SNAPSHOTS"]; let container_items = server.list_containers().iter().map(prepare_container_line).collect(); print!("{}", format_output(&headers, &container_items)); } fn main() { let matches = App::new("lxd") .subcommand(SubCommand::with_name("list") .arg(Arg::with_name("resource") .help("the resource to use") .required(true) .index(1))) .get_matches(); match matches.subcommand_name() { Some("list") => list(matches.subcommand_matches("list").unwrap()), _ => println!("{}", matches.usage()), } }<|fim▁end|>
}
<|file_name|>get_instance_console_output.go<|end_file_name|><|fim▁begin|>package ecs //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // GetInstanceConsoleOutput invokes the ecs.GetInstanceConsoleOutput API synchronously func (client *Client) GetInstanceConsoleOutput(request *GetInstanceConsoleOutputRequest) (response *GetInstanceConsoleOutputResponse, err error) { response = CreateGetInstanceConsoleOutputResponse() err = client.DoAction(request, response) return } // GetInstanceConsoleOutputWithChan invokes the ecs.GetInstanceConsoleOutput API asynchronously func (client *Client) GetInstanceConsoleOutputWithChan(request *GetInstanceConsoleOutputRequest) (<-chan *GetInstanceConsoleOutputResponse, <-chan error) { responseChan := make(chan *GetInstanceConsoleOutputResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.GetInstanceConsoleOutput(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // GetInstanceConsoleOutputWithCallback invokes the ecs.GetInstanceConsoleOutput API asynchronously func (client *Client) GetInstanceConsoleOutputWithCallback(request *GetInstanceConsoleOutputRequest, callback func(response *GetInstanceConsoleOutputResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *GetInstanceConsoleOutputResponse var err error defer close(result)<|fim▁hole|> callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // GetInstanceConsoleOutputRequest is the request struct for api GetInstanceConsoleOutput type GetInstanceConsoleOutputRequest struct { *requests.RpcRequest ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` RemoveSymbols requests.Boolean `position:"Query" name:"RemoveSymbols"` ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` OwnerAccount string `position:"Query" name:"OwnerAccount"` OwnerId requests.Integer `position:"Query" name:"OwnerId"` InstanceId string `position:"Query" name:"InstanceId"` } // GetInstanceConsoleOutputResponse is the response struct for api GetInstanceConsoleOutput type GetInstanceConsoleOutputResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` InstanceId string `json:"InstanceId" xml:"InstanceId"` ConsoleOutput string `json:"ConsoleOutput" xml:"ConsoleOutput"` LastUpdateTime string `json:"LastUpdateTime" xml:"LastUpdateTime"` } // CreateGetInstanceConsoleOutputRequest creates a request to invoke GetInstanceConsoleOutput API func CreateGetInstanceConsoleOutputRequest() (request *GetInstanceConsoleOutputRequest) { request = &GetInstanceConsoleOutputRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Ecs", "2014-05-26", "GetInstanceConsoleOutput", "ecs", "openAPI") request.Method = requests.POST return } // CreateGetInstanceConsoleOutputResponse creates a response to parse from GetInstanceConsoleOutput response func CreateGetInstanceConsoleOutputResponse() (response *GetInstanceConsoleOutputResponse) { response = &GetInstanceConsoleOutputResponse{ BaseResponse: &responses.BaseResponse{}, } return }<|fim▁end|>
response, err = client.GetInstanceConsoleOutput(request)
<|file_name|>termsSpec.js<|end_file_name|><|fim▁begin|>/* global girderTest, describe, it, expect, runs, waitsFor, girder, beforeEach */ girderTest.importPlugin('terms'); girderTest.startApp(); describe('Create and log in to a user for testing', function () { it('create an admin user', girderTest.createUser('rocky', '[email protected]', 'Robert', 'Balboa', 'adrian')); it('allow all users to create collections', function () { var settingSaved; runs(function () { settingSaved = false; girder.rest.restRequest({ url: 'system/setting', method: 'PUT', data: { key: 'core.collection_create_policy', value: JSON.stringify({ groups: [], open: true, users: [] }) } }) .done(function () { settingSaved = true; }); }); waitsFor(function () { return settingSaved; }); }); it('logout', girderTest.logout()); it('create a collection admin user', girderTest.createUser('creed', '[email protected]', 'Apollo', 'Creed', 'the1best')); }); describe('Ensure that basic collections still work', function () { it('go to collections page', function () { runs(function () { $('a.g-nav-link[g-target="collections"]').trigger('click'); }); waitsFor(function () { return $('.g-collection-create-button:visible').length > 0; }); runs(function () { expect($('.g-collection-list-entry').length).toBe(0); }); }); it('create a basic collection', girderTest.createCollection('Basic Collection', 'Some description.', 'Basic Folder')); }); describe('Navigate to a non-collection folder and item', function () { it('navigate to user folders page', function () { runs(function () { $('a.g-my-folders').trigger('click'); }); waitsFor(function () { return $('.g-user-header').length > 0 && $('.g-folder-list-entry').length > 0; }); }); it('navigate to the Public folder', function () { runs(function () { var folderLink = $('.g-folder-list-link:contains("Public")'); expect(folderLink.length).toBe(1); folderLink.trigger('click'); }); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); girderTest.waitForLoad(); runs(function () { expect($('.g-hierarchy-breadcrumb-bar>.breadcrumb>.active').text()).toBe('Public');<|fim▁hole|> // after setting a window location, waitForLoad is insufficient, as the // page hasn't yet started making requests and it looks similar to // before the location change. Wait for the user header to be hidden, // and then wait for load. waitsFor(function () { return $('.g-user-header').length === 0; }, 'the user header to go away'); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); }); it('create an item', function () { runs(function () { $('.g-create-item').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.modal-body input#g-name').length > 0; }); runs(function () { $('#g-name').val('User Item'); $('.g-save-item').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-list-link').length > 0; }); }); it('navigate to the new item', function () { runs(function () { var itemLink = $('.g-item-list-link:contains("User Item")'); expect(itemLink.length).toBe(1); itemLink.trigger('click'); }); waitsFor(function () { return $('.g-item-header').length > 0; }); runs(function () { expect($('.g-item-header .g-item-name').text()).toBe('User Item'); termsItemId = window.location.hash.split('/')[1]; expect(termsItemId).toMatch(/[0-9a-f]{24}/); }); }); }); var termsCollectionId, termsFolderId, termsItemId; describe('Create a collection with terms', function () { it('go to collections page', function () { runs(function () { $('a.g-nav-link[g-target="collections"]').trigger('click'); }); waitsFor(function () { return $('.g-collection-create-button:visible').length > 0; }); }); it('open the create collection dialog', function () { waitsFor(function () { return $('.g-collection-create-button').is(':enabled'); }); runs(function () { $('.g-collection-create-button').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('#collection-terms-write .g-markdown-text').is(':visible'); }); }); it('fill and submit the create collection dialog', function () { runs(function () { $('#g-name').val('Terms Collection'); $('#collection-description-write .g-markdown-text').val('Some other description.'); $('#collection-terms-write .g-markdown-text').val('# Sample Terms of Use\n\n**\u00af\\\\\\_(\u30c4)\\_/\u00af**'); $('.g-save-collection').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-collection-header').length > 0; }); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); termsCollectionId = window.location.hash.split('/')[1]; expect(termsCollectionId).toMatch(/[0-9a-f]{24}/); }); }); it('make the collection public', function () { runs(function () { $('.g-edit-access').trigger('click'); }); girderTest.waitForDialog(); runs(function () { $('#g-access-public').trigger('click'); $('.g-save-access-list').trigger('click'); }); girderTest.waitForLoad(); }); it('check the collection info dialog', function () { runs(function () { $('.g-collection-info-button').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.g-terms-info').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); }); runs(function () { $('.modal-header .close').trigger('click'); }); girderTest.waitForLoad(); }); it('create a folder', function () { runs(function () { return $('.g-create-subfolder').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.modal-body input#g-name').length > 0; }); runs(function () { $('#g-name').val('Terms Folder'); $('.g-save-folder').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-folder-list-link').length > 0; }); }); it('navigate to the new folder', function () { runs(function () { var folderLink = $('.g-folder-list-link:contains("Terms Folder")'); expect(folderLink.length).toBe(1); folderLink.trigger('click'); }); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); runs(function () { expect($('.g-hierarchy-breadcrumb-bar>.breadcrumb>.active').text()).toBe('Terms Folder'); termsFolderId = window.location.hash.split('/')[3]; expect(termsFolderId).toMatch(/[0-9a-f]{24}/); }); }); it('create an item', function () { runs(function () { return $('.g-create-item').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.modal-body input#g-name').length > 0; }); runs(function () { $('#g-name').val('Terms Item'); $('.g-save-item').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-list-link').length > 0; }); }); it('navigate to the new item', function () { runs(function () { var itemLink = $('.g-item-list-link:contains("Terms Item")'); expect(itemLink.length).toBe(1); itemLink.trigger('click'); }); waitsFor(function () { return $('.g-item-header').length > 0; }); runs(function () { expect($('.g-item-header .g-item-name').text()).toBe('Terms Item'); termsItemId = window.location.hash.split('/')[1]; expect(termsItemId).toMatch(/[0-9a-f]{24}/); }); }); }); // TODO: rerun this whole suite while logged in describe('Ensure that anonymous users are presented with terms', function () { beforeEach(function () { window.localStorage.clear(); }); it('logout', girderTest.logout()); it('navigate to the collection page, rejecting terms', function () { runs(function () { window.location.assign('#collection/' + termsCollectionId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-reject').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-frontpage-header').length > 0; }); }); it('navigate to the collection page', function () { runs(function () { window.location.assign('#collection/' + termsCollectionId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-collection-header').length > 0; }); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); }); }); it('navigate to the folder page', function () { runs(function () { window.location.assign('#folder/' + termsFolderId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); runs(function () { expect($('.g-hierarchy-breadcrumb-bar>.breadcrumb>.active').text()).toBe('Terms Folder'); }); }); it('navigate to the item page', function () { runs(function () { window.location.assign('#item/' + termsItemId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-header').length > 0; }); runs(function () { expect($('.g-item-header .g-item-name').text()).toBe('Terms Item'); }); }); }); // TODO: edit the collection with WRITE permissions only describe('Change the terms', function () { it('login as collection admin', girderTest.login('creed', 'Apollo', 'Creed', 'the1best')); it('navigate to the terms collection', function () { runs(function () { $('a.g-nav-link[g-target="collections"]').trigger('click'); }); waitsFor(function () { return $('.g-collection-list-entry').length > 0; }); girderTest.waitForLoad(); runs(function () { $('.g-collection-link:contains("Terms Collection")').trigger('click'); }); waitsFor(function () { return $('.g-collection-header').length > 0; }); girderTest.waitForLoad(); }); it('edit the collection terms', function () { runs(function () { $('.g-edit-folder').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('#collection-terms-write .g-markdown-text').is(':visible'); }); runs(function () { $('#collection-terms-write .g-markdown-text').val('# New Terms of Use\n\nThese have changed.'); $('.g-save-collection').trigger('click'); }); girderTest.waitForLoad(); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); }); }); }); describe('Ensure that anonymous users need to re-accept the updated terms', function () { it('logout', girderTest.logout()); it('ensure that the old terms acceptance is still stored', function () { expect(window.localStorage.length).toBe(1); }); it('navigate to the collection page', function () { runs(function () { window.location.assign('#collection/' + termsCollectionId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('New Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-collection-header').length > 0; }); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); }); }); });<|fim▁end|>
var folderId = window.location.hash.split('/')[3]; expect(folderId).toMatch(/[0-9a-f]{24}/); window.location.assign('#folder/' + folderId); });
<|file_name|>manager.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Low-Level manager for loading and unloading plugins. These functions //! should generally not be called directly by most consumers, who should //! be using the high level interfaces found in the config, manager, and //! miner modules. These functions are meant for internal cuckoo-miner crates, //! and will not be exposed to other projects including the cuckoo-miner crate. //! //! Note that plugins are shared libraries, not objects. You can have multiple //! instances of a PluginLibrary, but all of them will reference the same //! loaded code. Plugins aren't threadsafe, so only one thread should ever //! be calling a particular plugin at a time. use std::sync::Mutex; use libloading; use libc::*; use error::error::CuckooMinerError; // PRIVATE MEMBERS // Type definitions corresponding to each function that the plugin implements type CuckooInit = unsafe extern "C" fn(); type CuckooCall = unsafe extern "C" fn(*const c_uchar, uint32_t, *mut uint32_t, *mut uint32_t) -> uint32_t; type CuckooParameterList = unsafe extern "C" fn(*mut c_uchar, *mut uint32_t) -> uint32_t; type CuckooSetParameter = unsafe extern "C" fn(*const c_uchar, uint32_t, uint32_t, uint32_t) -> uint32_t; type CuckooGetParameter = unsafe extern "C" fn(*const c_uchar, uint32_t, uint32_t, *mut uint32_t) -> uint32_t; type CuckooIsQueueUnderLimit = unsafe extern "C" fn() -> uint32_t; type CuckooPushToInputQueue = unsafe extern "C" fn(uint32_t, *const c_uchar, uint32_t, *const c_uchar) -> uint32_t; type CuckooReadFromOutputQueue = unsafe extern "C" fn(*mut uint32_t, *mut uint32_t, *mut uint32_t, *mut c_uchar) -> uint32_t; type CuckooClearQueues = unsafe extern "C" fn(); type CuckooStartProcessing = unsafe extern "C" fn() -> uint32_t; type CuckooStopProcessing = unsafe extern "C" fn() -> uint32_t; type CuckooResetProcessing = unsafe extern "C" fn() -> uint32_t; type CuckooHasProcessingStopped = unsafe extern "C" fn() -> uint32_t; type CuckooGetStats = unsafe extern "C" fn(*mut c_uchar, *mut uint32_t) -> uint32_t; /// Struct to hold instances of loaded plugins pub struct PluginLibrary { ///The full file path to the plugin loaded by this instance pub lib_full_path: String, loaded_library: Mutex<libloading::Library>, cuckoo_init: Mutex<CuckooInit>, cuckoo_call: Mutex<CuckooCall>, cuckoo_parameter_list: Mutex<CuckooParameterList>, cuckoo_get_parameter: Mutex<CuckooGetParameter>, cuckoo_set_parameter: Mutex<CuckooSetParameter>, cuckoo_is_queue_under_limit: Mutex<CuckooIsQueueUnderLimit>, cuckoo_clear_queues: Mutex<CuckooClearQueues>, cuckoo_push_to_input_queue: Mutex<CuckooPushToInputQueue>, cuckoo_read_from_output_queue: Mutex<CuckooReadFromOutputQueue>, cuckoo_start_processing: Mutex<CuckooStartProcessing>, cuckoo_stop_processing: Mutex<CuckooStopProcessing>, cuckoo_reset_processing: Mutex<CuckooResetProcessing>, cuckoo_has_processing_stopped: Mutex<CuckooHasProcessingStopped>, cuckoo_get_stats: Mutex<CuckooGetStats>, } impl PluginLibrary { //Loads the library at the specified path /// #Description /// /// Loads the specified library, readying it for use /// via the exposed wrapper functions. A plugin can be /// loaded into multiple PluginLibrary instances, however /// they will all reference the same loaded library. One /// should only exist per library in a given thread. /// /// #Arguments /// /// * `lib_full_path` The full path to the library that is /// to be loaded. /// /// #Returns /// /// * `Ok()` is the library was successfully loaded. /// * a [CuckooMinerError](enum.CuckooMinerError.html) /// with specific detail if an error was encountered. /// /// #Example /// /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// pl.call_cuckoo_init(); /// ``` /// pub fn new(lib_full_path: &str) -> Result<PluginLibrary, CuckooMinerError> { debug!("Loading miner plugin: {}", &lib_full_path); let result = libloading::Library::new(lib_full_path); if let Err(e) = result { return Err(CuckooMinerError::PluginNotFoundError( String::from(format!("{} - {:?}", lib_full_path, e)), )); } let loaded_library = result.unwrap(); PluginLibrary::load_symbols(loaded_library, lib_full_path) } fn load_symbols( loaded_library: libloading::Library, path: &str ) -> Result<PluginLibrary, CuckooMinerError> { unsafe { let ret_val = PluginLibrary { lib_full_path: String::from(path), cuckoo_init: { let cuckoo_init: libloading::Symbol<CuckooInit> = loaded_library.get(b"cuckoo_init\0").unwrap(); Mutex::new(*cuckoo_init.into_raw()) }, cuckoo_call: { let cuckoo_call: libloading::Symbol<CuckooCall> = loaded_library.get(b"cuckoo_call\0").unwrap(); Mutex::new(*cuckoo_call.into_raw()) }, cuckoo_parameter_list: { let cuckoo_parameter_list:libloading::Symbol<CuckooParameterList> = loaded_library.get(b"cuckoo_parameter_list\0").unwrap(); Mutex::new(*cuckoo_parameter_list.into_raw()) }, cuckoo_get_parameter: { let cuckoo_get_parameter:libloading::Symbol<CuckooGetParameter> = loaded_library.get(b"cuckoo_get_parameter\0").unwrap(); Mutex::new(*cuckoo_get_parameter.into_raw()) }, cuckoo_set_parameter: { let cuckoo_set_parameter:libloading::Symbol<CuckooSetParameter> = loaded_library.get(b"cuckoo_set_parameter\0").unwrap(); Mutex::new(*cuckoo_set_parameter.into_raw()) }, cuckoo_is_queue_under_limit: { let cuckoo_is_queue_under_limit:libloading::Symbol<CuckooIsQueueUnderLimit> = loaded_library.get(b"cuckoo_is_queue_under_limit\0").unwrap(); Mutex::new(*cuckoo_is_queue_under_limit.into_raw()) }, cuckoo_clear_queues: { let cuckoo_clear_queues:libloading::Symbol<CuckooClearQueues> = loaded_library.get(b"cuckoo_clear_queues\0").unwrap(); Mutex::new(*cuckoo_clear_queues.into_raw()) }, cuckoo_push_to_input_queue: { let cuckoo_push_to_input_queue:libloading::Symbol<CuckooPushToInputQueue> = loaded_library.get(b"cuckoo_push_to_input_queue\0").unwrap(); Mutex::new(*cuckoo_push_to_input_queue.into_raw()) }, cuckoo_read_from_output_queue: { let cuckoo_read_from_output_queue:libloading::Symbol<CuckooReadFromOutputQueue> = loaded_library.get(b"cuckoo_read_from_output_queue\0").unwrap(); Mutex::new(*cuckoo_read_from_output_queue.into_raw()) }, cuckoo_start_processing: { let cuckoo_start_processing:libloading::Symbol<CuckooStartProcessing> = loaded_library.get(b"cuckoo_start_processing\0").unwrap(); Mutex::new(*cuckoo_start_processing.into_raw()) }, cuckoo_stop_processing: { let cuckoo_stop_processing:libloading::Symbol<CuckooStopProcessing> = loaded_library.get(b"cuckoo_stop_processing\0").unwrap(); Mutex::new(*cuckoo_stop_processing.into_raw()) }, cuckoo_reset_processing: { let cuckoo_reset_processing:libloading::Symbol<CuckooResetProcessing> = loaded_library.get(b"cuckoo_reset_processing\0").unwrap(); Mutex::new(*cuckoo_reset_processing.into_raw()) }, cuckoo_has_processing_stopped: { let cuckoo_has_processing_stopped:libloading::Symbol<CuckooHasProcessingStopped> = loaded_library.get(b"cuckoo_has_processing_stopped\0").unwrap(); Mutex::new(*cuckoo_has_processing_stopped.into_raw()) }, cuckoo_get_stats: { let cuckoo_get_stats: libloading::Symbol<CuckooGetStats> = loaded_library.get(b"cuckoo_get_stats\0").unwrap(); Mutex::new(*cuckoo_get_stats.into_raw()) }, loaded_library: Mutex::new(loaded_library), }; ret_val.call_cuckoo_init(); return Ok(ret_val); } } /// #Description /// /// Unloads the currently loaded plugin and all symbols. /// /// #Arguments /// /// None /// /// #Returns /// /// Nothing /// pub fn unload(&self) { let cuckoo_get_parameter_ref = self.cuckoo_get_parameter.lock().unwrap(); drop(cuckoo_get_parameter_ref); let cuckoo_set_parameter_ref = self.cuckoo_set_parameter.lock().unwrap(); drop(cuckoo_set_parameter_ref); let cuckoo_parameter_list_ref = self.cuckoo_parameter_list.lock().unwrap(); drop(cuckoo_parameter_list_ref); let cuckoo_call_ref = self.cuckoo_call.lock().unwrap(); drop(cuckoo_call_ref); let cuckoo_is_queue_under_limit_ref = self.cuckoo_is_queue_under_limit.lock().unwrap(); drop(cuckoo_is_queue_under_limit_ref); let cuckoo_clear_queues_ref = self.cuckoo_clear_queues.lock().unwrap(); drop(cuckoo_clear_queues_ref); let cuckoo_push_to_input_queue_ref = self.cuckoo_push_to_input_queue.lock().unwrap(); drop(cuckoo_push_to_input_queue_ref); let cuckoo_read_from_output_queue_ref = self.cuckoo_read_from_output_queue.lock().unwrap(); drop(cuckoo_read_from_output_queue_ref); let cuckoo_start_processing_ref = self.cuckoo_start_processing.lock().unwrap(); drop(cuckoo_start_processing_ref); let cuckoo_stop_processing_ref = self.cuckoo_stop_processing.lock().unwrap(); drop(cuckoo_stop_processing_ref); let cuckoo_reset_processing_ref = self.cuckoo_reset_processing.lock().unwrap(); drop(cuckoo_reset_processing_ref); let cuckoo_has_processing_stopped_ref = self.cuckoo_has_processing_stopped.lock().unwrap(); drop(cuckoo_has_processing_stopped_ref); let cuckoo_get_stats_ref = self.cuckoo_get_stats.lock().unwrap(); drop(cuckoo_get_stats_ref); let loaded_library_ref = self.loaded_library.lock().unwrap(); drop(loaded_library_ref); } /// #Description /// /// Initialises the cuckoo plugin, mostly allowing it to write a list of /// its accepted parameters. This should be called just after the plugin /// is loaded, and before anything else is called. /// /// #Arguments /// /// * None /// /// #Returns /// /// * Nothing /// /// #Example /// /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// pl.call_cuckoo_init(); /// ``` /// pub fn call_cuckoo_init(&self) { let cuckoo_init_ref = self.cuckoo_init.lock().unwrap(); unsafe { cuckoo_init_ref(); }; } /// #Description /// /// Call to the cuckoo_call function of the currently loaded plugin, which /// will perform a Cuckoo Cycle on the given seed, returning the first /// solution (a length 42 cycle) that is found. The implementation details /// are dependent on particular loaded plugin. /// /// #Arguments /// /// * `header` (IN) A reference to a block of [u8] bytes to use for the /// seed to the internal SIPHASH function which generates edge locations /// in the graph. In practice, this is a Grin blockheader, /// but from the plugin's perspective this can be anything. /// /// * `solutions` (OUT) A caller-allocated array of 42 unsigned bytes. This /// currently must be of size 42, corresponding to a conventional /// cuckoo-cycle solution length. If a solution is found, the solution /// nonces will be stored in this array, otherwise, they will be left /// untouched. /// /// #Returns /// /// 1 if a solution is found, with the 42 solution nonces contained /// within `sol_nonces`. 0 if no solution is found and `sol_nonces` /// remains untouched. /// /// #Example /// /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env;<|fim▁hole|> /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl = PluginLibrary::new(plugin_path).unwrap(); /// let header:[u8;40] = [0;40]; /// let mut solution:[u32; 42] = [0;42]; /// let mut cuckoo_size = 0; /// let result=pl.call_cuckoo(&header, &mut cuckoo_size, &mut solution); /// if result==0 { /// println!("Solution Found!"); /// } else { /// println!("No Solution Found"); /// } /// /// ``` /// pub fn call_cuckoo(&self, header: &[u8], cuckoo_size: &mut u32, solutions: &mut [u32; 42]) -> u32 { let cuckoo_call_ref = self.cuckoo_call.lock().unwrap(); unsafe { cuckoo_call_ref(header.as_ptr(), header.len() as u32, cuckoo_size, solutions.as_mut_ptr()) } } /// #Description /// /// Call to the cuckoo_call_parameter_list function of the currently loaded /// plugin, which will provide an informative JSON array of the parameters that the /// plugin supports, as well as their descriptions and range of values. /// /// #Arguments /// /// * `param_list_bytes` (OUT) A reference to a block of [u8] bytes to fill /// with the JSON result array /// /// * `param_list_len` (IN-OUT) When called, this should contain the /// maximum number of bytes the plugin should write to `param_list_bytes`. /// Upon return, this is filled with the number of bytes that were written to /// `param_list_bytes`. /// /// #Returns /// /// 0 if okay, with the result is stored in `param_list_bytes` /// 3 if the provided array is too short /// /// #Example /// /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// pl.call_cuckoo_init(); /// let mut param_list_bytes:[u8;1024]=[0;1024]; /// let mut param_list_len=param_list_bytes.len() as u32; /// //get a list of json parameters /// let parameter_list=pl.call_cuckoo_parameter_list(&mut param_list_bytes, /// &mut param_list_len); /// ``` /// pub fn call_cuckoo_parameter_list( &self, param_list_bytes: &mut [u8], param_list_len: &mut u32, ) -> u32 { let cuckoo_parameter_list_ref = self.cuckoo_parameter_list.lock().unwrap(); unsafe { cuckoo_parameter_list_ref(param_list_bytes.as_mut_ptr(), param_list_len) } } /// #Description /// /// Retrieves the value of a parameter from the currently loaded plugin /// /// #Arguments /// /// * `name_bytes` (IN) A reference to a block of [u8] bytes storing the /// parameter name /// /// * `device_id` (IN) The device ID to which the parameter applies (if applicable) /// * `value` (OUT) A reference where the parameter value will be stored /// /// #Returns /// /// 0 if the parameter was retrived, and the result is stored in `value` /// 1 if the parameter does not exist /// 4 if the provided parameter name was too long /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// pl.call_cuckoo_init(); /// let name = "NUM_THREADS"; /// let mut num_threads:u32 = 0; /// let ret_val = pl.call_cuckoo_get_parameter(name.as_bytes(), 0, &mut num_threads); /// ``` /// pub fn call_cuckoo_get_parameter(&self, name_bytes: &[u8], device_id: u32, value: &mut u32) -> u32 { let cuckoo_get_parameter_ref = self.cuckoo_get_parameter.lock().unwrap(); unsafe { cuckoo_get_parameter_ref(name_bytes.as_ptr(), name_bytes.len() as u32, device_id, value) } } /// Sets the value of a parameter in the currently loaded plugin /// /// #Arguments /// /// * `name_bytes` (IN) A reference to a block of [u8] bytes storing the /// parameter name /// /// * `device_id` (IN) The deviceID to which the parameter applies (if applicable) /// * `value` (IN) The value to which to set the parameter /// /// #Returns /// /// 0 if the parameter was retrieved, and the result is stored in `value` /// 1 if the parameter does not exist /// 2 if the parameter exists, but the provided value is outside the /// allowed range determined by the plugin /// 4 if the provided parameter name is too long /// /// #Example /// /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// let name = "NUM_THREADS"; /// let return_code = pl.call_cuckoo_set_parameter(name.as_bytes(), 0, 8); /// ``` /// pub fn call_cuckoo_set_parameter(&self, name_bytes: &[u8], device_id: u32, value: u32) -> u32 { let cuckoo_set_parameter_ref = self.cuckoo_set_parameter.lock().unwrap(); unsafe { cuckoo_set_parameter_ref(name_bytes.as_ptr(), name_bytes.len() as u32, device_id, value) } } /// #Description /// /// For Async/Queued mode, check whether the plugin is ready /// to accept more headers. /// /// #Arguments /// /// * None /// /// #Returns /// /// * 1 if the queue can accept more hashes, 0 otherwise /// pub fn call_cuckoo_is_queue_under_limit(&self) -> u32 { let cuckoo_is_queue_under_limit_ref = self.cuckoo_is_queue_under_limit.lock().unwrap(); unsafe { cuckoo_is_queue_under_limit_ref() } } /// #Description /// /// Pushes header data to the loaded plugin for later processing in /// asyncronous/queued mode. /// /// #Arguments /// /// * `data` (IN) A block of bytes to use for the seed to the internal /// SIPHASH function which generates edge locations in the graph. In /// practice, this is a Grin blockheader, but from the /// plugin's perspective this can be anything. /// /// * `nonce` (IN) The nonce that was used to generate this data, for /// identification purposes in the solution queue /// /// #Returns /// /// 0 if the hash was successfully added to the queue /// 1 if the queue is full /// 2 if the length of the data is greater than the plugin allows /// 4 if the plugin has been told to shutdown /// /// #Unsafe /// /// Provided values are copied within the plugin, and will not be /// modified /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// //Processing started after call to cuckoo_start_processing() /// //a test hash of zeroes /// let hash:[u8;32]=[0;32]; /// //test nonce (u64, basically) should be unique /// let nonce:[u8;8]=[0;8]; /// let result=pl.call_cuckoo_push_to_input_queue(&hash, &nonce); /// ``` /// pub fn call_cuckoo_push_to_input_queue(&self, id: u32, data: &[u8], nonce: &[u8;8]) -> u32 { let cuckoo_push_to_input_queue_ref = self.cuckoo_push_to_input_queue.lock().unwrap(); unsafe { cuckoo_push_to_input_queue_ref(id, data.as_ptr(), data.len() as u32, nonce.as_ptr()) } } /// #Description /// /// Clears internal queues of all data /// /// #Arguments /// /// * None /// /// #Returns /// /// * Nothing /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// //Processing started after call to cuckoo_start_processing() /// //a test hash of zeroes /// let hash:[u8;32]=[0;32]; /// //test nonce (u64, basically) should be unique /// let nonce:[u8;8]=[0;8]; /// let result=pl.call_cuckoo_push_to_input_queue(&hash, &nonce); /// //clear queues /// pl.call_cuckoo_clear_queues(); /// ``` /// pub fn call_cuckoo_clear_queues(&self) { let cuckoo_clear_queues_ref = self.cuckoo_clear_queues.lock().unwrap(); unsafe { cuckoo_clear_queues_ref() } } /// #Description /// /// Reads the next solution from the output queue, if one exists. Only /// solutions which meet the target difficulty specified in the preceeding /// call to 'notify' will be placed in the output queue. Read solutions /// are popped from the queue. Does not block, and intended to be called /// continually as part of a mining loop. /// /// #Arguments /// /// * `sol_nonces` (OUT) A block of 42 u32s in which the solution nonces /// will be stored, if any exist. /// /// * `nonce` (OUT) A block of 8 u8s representing a Big-Endian u64, used /// for identification purposes so the caller can reconstruct the header /// used to generate the solution. /// /// #Returns /// /// 1 if a solution was popped from the queue /// 0 if a solution is not available /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// //Processing started after call to cuckoo_start_processing() /// //a test hash of zeroes /// let hash:[u8;32]=[0;32]; /// //test nonce (u64, basically) should be unique /// let nonce:[u8;8]=[0;8]; /// let result=pl.call_cuckoo_push_to_input_queue(&hash, &nonce); /// /// //within loop /// let mut sols:[u32; 42] = [0; 42]; /// let mut nonce: [u8; 8] = [0;8]; /// let mut cuckoo_size = 0; /// let found = pl.call_cuckoo_read_from_output_queue(&mut sols, &mut cuckoo_size, &mut nonce); /// ``` /// pub fn call_cuckoo_read_from_output_queue( &self, id: &mut u32, solutions: &mut [u32; 42], cuckoo_size: &mut u32, nonce: &mut [u8; 8], ) -> u32 { let cuckoo_read_from_output_queue_ref = self.cuckoo_read_from_output_queue.lock().unwrap(); let ret = unsafe { cuckoo_read_from_output_queue_ref(id, solutions.as_mut_ptr(), cuckoo_size, nonce.as_mut_ptr()) }; ret } /// #Description /// /// Starts asyncronous processing. The plugin will start reading hashes /// from the input queue, delegate them internally as it sees fit, and /// put solutions into the output queue. It is up to the plugin /// implementation to manage how the workload is spread across /// devices/threads. Once processing is started, communication with /// the started process happens via reading and writing from the /// input and output queues. /// /// #Arguments /// /// * None /// /// #Returns /// /// * 1 if processing was successfully started /// * Another value if procesing failed to start (return codes TBD) /// /// #Unsafe /// /// The caller is reponsible for calling call_cuckoo_stop_processing() /// before exiting its thread, which will signal the internally detached /// thread to stop processing, clean up, and exit. /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// let ret_val=pl.call_cuckoo_start_processing(); /// ``` pub fn call_cuckoo_start_processing(&self) -> u32 { let cuckoo_start_processing_ref = self.cuckoo_start_processing.lock().unwrap(); unsafe { cuckoo_start_processing_ref() } } /// #Description /// /// Stops asyncronous processing. The plugin should signal to shut down /// processing, as quickly as possible, clean up all threads/devices/memory /// it may have allocated, and clear its queues. Note this merely sets /// a flag indicating that the threads started by 'cuckoo_start_processing' /// should shut down, and will return instantly. Use 'cuckoo_has_processing_stopped' /// to check on the shutdown status. /// /// #Arguments /// /// * None /// /// #Returns /// /// * 1 in all cases, indicating the stop flag was set.. /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// let mut ret_val=pl.call_cuckoo_start_processing(); /// //Send data into queue, read results, etc /// ret_val=pl.call_cuckoo_stop_processing(); /// while pl.call_cuckoo_has_processing_stopped() == 0 { /// //don't continue/exit thread until plugin is stopped /// } /// ``` pub fn call_cuckoo_stop_processing(&self) -> u32 { let cuckoo_stop_processing_ref = self.cuckoo_stop_processing.lock().unwrap(); unsafe { cuckoo_stop_processing_ref() } } /// #Description /// /// Resets the internal processing flag so that processing may begin again. /// /// #Arguments /// /// * None /// /// #Returns /// /// * 1 in all cases, indicating the stop flag was reset /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// let mut ret_val=pl.call_cuckoo_start_processing(); /// //Send data into queue, read results, etc /// ret_val=pl.call_cuckoo_stop_processing(); /// while pl.call_cuckoo_has_processing_stopped() == 0 { /// //don't continue/exit thread until plugin is stopped /// } /// // later on /// pl.call_cuckoo_reset_processing(); /// //restart /// ``` pub fn call_cuckoo_reset_processing(&self) -> u32 { let cuckoo_reset_processing_ref = self.cuckoo_reset_processing.lock().unwrap(); unsafe { cuckoo_reset_processing_ref() } } /// #Description /// /// Returns whether all internal processing within the plugin has stopped, /// meaning it's safe to exit the calling thread after a call to /// cuckoo_stop_processing() /// /// #Arguments /// /// * None /// /// #Returns /// /// 1 if all internal processing has been stopped. /// 0 if processing activity is still in progress /// /// #Example /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// let ret_val=pl.call_cuckoo_start_processing(); /// //Things happen in between, within a loop /// pl.call_cuckoo_stop_processing(); /// while pl.call_cuckoo_has_processing_stopped() == 0 { /// //don't continue/exit thread until plugin is stopped /// } /// ``` pub fn call_cuckoo_has_processing_stopped(&self) -> u32 { let cuckoo_has_processing_stopped_ref = self.cuckoo_has_processing_stopped.lock().unwrap(); unsafe { cuckoo_has_processing_stopped_ref() } } /// #Description /// /// Retrieves a JSON list of the plugin's current stats for all running /// devices. In the case of a plugin running GPUs in parallel, it should /// be a list of running devices. In the case of a CPU plugin, it will /// most likely be a single CPU. e.g: /// /// ```text /// [{ /// device_id:"0", /// device_name:"NVIDIA GTX 1080", /// last_start_time: "23928329382", /// last_end_time: "23928359382", /// last_solution_time: "3382", /// }, /// { /// device_id:"1", /// device_name:"NVIDIA GTX 1080ti", /// last_start_time: "23928329382", /// last_end_time: "23928359382", /// last_solution_time: "3382", /// }] /// ``` /// #Arguments /// /// * `stat_bytes` (OUT) A reference to a block of [u8] bytes to fill with /// the JSON result array /// /// * `stat_bytes_len` (IN-OUT) When called, this should contain the /// maximum number of bytes the plugin should write to `stat_bytes`. Upon return, /// this is filled with the number of bytes that were written to `stat_bytes`. /// /// #Returns /// /// 0 if okay, with the result is stored in `stat_bytes` /// 3 if the provided array is too short /// /// #Example /// /// ``` /// # use cuckoo_miner::PluginLibrary; /// # use std::env; /// # use std::path::PathBuf; /// # static DLL_SUFFIX: &str = ".cuckooplugin"; /// # let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// # d.push(format!("./target/debug/plugins/lean_cpu_16{}", DLL_SUFFIX).as_str()); /// # let plugin_path = d.to_str().unwrap(); /// let pl=PluginLibrary::new(plugin_path).unwrap(); /// pl.call_cuckoo_init(); /// ///start plugin+processing, and then within the loop: /// let mut stat_bytes:[u8;1024]=[0;1024]; /// let mut stat_len=stat_bytes.len() as u32; /// //get a list of json parameters /// let parameter_list=pl.call_cuckoo_get_stats(&mut stat_bytes, /// &mut stat_len); /// ``` /// pub fn call_cuckoo_get_stats(&self, stat_bytes: &mut [u8], stat_bytes_len: &mut u32) -> u32 { let cuckoo_get_stats_ref = self.cuckoo_get_stats.lock().unwrap(); unsafe { cuckoo_get_stats_ref(stat_bytes.as_mut_ptr(), stat_bytes_len) } } }<|fim▁end|>
/// # use std::path::PathBuf;
<|file_name|>harfbuzz.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern mod harfbuzz; use font::{Font, FontHandleMethods, FontTableMethods, FontTableTag}; use servo_util::geometry::Au; use platform::font::FontTable; use text::glyph::{GlyphStore, GlyphIndex, GlyphData}; use text::shaping::ShaperMethods; use servo_util::range::Range; use text::util::{float_to_fixed, fixed_to_float, fixed_to_rounded_int}; use std::cast::transmute; use std::char; use std::libc::{c_uint, c_int, c_void, c_char}; use std::ptr; use std::ptr::null; use std::uint; use std::util::ignore; use std::vec; use geom::Point2D; use harfbuzz::{hb_blob_create, hb_face_create_for_tables}; use harfbuzz::{hb_buffer_add_utf8}; use harfbuzz::{hb_buffer_get_glyph_positions}; use harfbuzz::{hb_buffer_set_direction}; use harfbuzz::{hb_buffer_destroy}; use harfbuzz::{hb_face_destroy}; use harfbuzz::{hb_font_create}; use harfbuzz::{hb_font_destroy, hb_buffer_create}; use harfbuzz::{hb_font_funcs_create}; use harfbuzz::{hb_font_funcs_destroy}; use harfbuzz::{hb_font_funcs_set_glyph_func}; use harfbuzz::{hb_font_funcs_set_glyph_h_advance_func}; use harfbuzz::{hb_font_set_funcs}; use harfbuzz::{hb_font_set_ppem}; use harfbuzz::{hb_font_set_scale}; use harfbuzz::{hb_shape, hb_buffer_get_glyph_infos}; use harfbuzz::{HB_MEMORY_MODE_READONLY, HB_DIRECTION_LTR}; use harfbuzz::{hb_blob_t}; use harfbuzz::{hb_bool_t}; use harfbuzz::{hb_face_t, hb_font_t}; use harfbuzz::{hb_font_funcs_t, hb_buffer_t, hb_codepoint_t}; use harfbuzz::{hb_glyph_info_t}; use harfbuzz::{hb_glyph_position_t}; use harfbuzz::{hb_position_t, hb_tag_t}; static NO_GLYPH: i32 = -1; static CONTINUATION_BYTE: i32 = -2; pub struct ShapedGlyphData { count: uint, glyph_infos: *hb_glyph_info_t, pos_infos: *hb_glyph_position_t, } pub struct ShapedGlyphEntry { cluster: uint, codepoint: GlyphIndex, advance: Au, offset: Option<Point2D<Au>>, } impl ShapedGlyphData { #[fixed_stack_segment] pub fn new(buffer: *hb_buffer_t) -> ShapedGlyphData { unsafe { let glyph_count = 0; let glyph_infos = hb_buffer_get_glyph_infos(buffer, &glyph_count); let glyph_count = glyph_count as uint; assert!(glyph_infos.is_not_null()); let pos_count = 0; let pos_infos = hb_buffer_get_glyph_positions(buffer, &pos_count); assert!(pos_infos.is_not_null()); assert!(glyph_count == pos_count as uint); ShapedGlyphData { count: glyph_count, glyph_infos: glyph_infos, pos_infos: pos_infos, } } } #[inline(always)] fn byte_offset_of_glyph(&self, i: uint) -> uint { assert!(i < self.count); unsafe { let glyph_info_i = ptr::offset(self.glyph_infos, i as int); (*glyph_info_i).cluster as uint } } pub fn len(&self) -> uint { self.count } /// Returns shaped glyph data for one glyph, and updates the y-position of the pen. pub fn get_entry_for_glyph(&self, i: uint, y_pos: &mut Au) -> ShapedGlyphEntry { assert!(i < self.count); unsafe { let glyph_info_i = ptr::offset(self.glyph_infos, i as int); let pos_info_i = ptr::offset(self.pos_infos, i as int); let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset); let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset); let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance); let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance); let x_offset = Au::from_frac_px(x_offset); let y_offset = Au::from_frac_px(y_offset); let x_advance = Au::from_frac_px(x_advance); let y_advance = Au::from_frac_px(y_advance); let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) { None } else { // adjust the pen.. if y_advance > Au(0) { *y_pos = *y_pos - y_advance; } Some(Point2D(x_offset, *y_pos - y_offset)) }; ShapedGlyphEntry { cluster: (*glyph_info_i).cluster as uint, codepoint: (*glyph_info_i).codepoint as GlyphIndex, advance: x_advance, offset: offset, } } } } pub struct Shaper { font: @mut Font, priv hb_face: *hb_face_t, priv hb_font: *hb_font_t, priv hb_funcs: *hb_font_funcs_t, } #[unsafe_destructor] impl Drop for Shaper { #[fixed_stack_segment] fn drop(&mut self) { unsafe { assert!(self.hb_face.is_not_null()); hb_face_destroy(self.hb_face); assert!(self.hb_font.is_not_null()); hb_font_destroy(self.hb_font); assert!(self.hb_funcs.is_not_null()); hb_font_funcs_destroy(self.hb_funcs); } } } impl Shaper { #[fixed_stack_segment] pub fn new(font: @mut Font) -> Shaper { unsafe { // Indirection for Rust Issue #6248, dynamic freeze scope artifically extended let font_ptr = { let borrowed_font= &mut *font; borrowed_font as *mut Font }; let hb_face: *hb_face_t = hb_face_create_for_tables(get_font_table_func, font_ptr as *c_void, None); let hb_font: *hb_font_t = hb_font_create(hb_face); // Set points-per-em. if zero, performs no hinting in that direction. let pt_size = font.style.pt_size; hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint); // Set scaling. Note that this takes 16.16 fixed point. hb_font_set_scale(hb_font, Shaper::float_to_fixed(pt_size) as c_int, Shaper::float_to_fixed(pt_size) as c_int); // configure static function callbacks. // NB. This funcs structure could be reused globally, as it never changes. let hb_funcs: *hb_font_funcs_t = hb_font_funcs_create(); hb_font_funcs_set_glyph_func(hb_funcs, glyph_func, null(), None); hb_font_funcs_set_glyph_h_advance_func(hb_funcs, glyph_h_advance_func, null(), None); hb_font_set_funcs(hb_font, hb_funcs, font_ptr as *c_void, None); Shaper { font: font, hb_face: hb_face, hb_font: hb_font, hb_funcs: hb_funcs, } } } fn float_to_fixed(f: f64) -> i32 { float_to_fixed(16, f) } fn fixed_to_float(i: hb_position_t) -> f64 { fixed_to_float(16, i) } fn fixed_to_rounded_int(f: hb_position_t) -> int { fixed_to_rounded_int(16, f) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when rendered in a specific /// font. #[fixed_stack_segment] fn shape_text(&self, text: &str, glyphs: &mut GlyphStore) { unsafe { let hb_buffer: *hb_buffer_t = hb_buffer_create(); hb_buffer_set_direction(hb_buffer, HB_DIRECTION_LTR); // Using as_imm_buf because it never does a copy - we don't need the trailing null do text.as_imm_buf |ctext: *u8, _: uint| { hb_buffer_add_utf8(hb_buffer, ctext as *c_char, text.len() as c_int, 0, text.len() as c_int); } hb_shape(self.hb_font, hb_buffer, null(), 0); self.save_glyph_results(text, glyphs, hb_buffer); hb_buffer_destroy(hb_buffer); } } } impl Shaper { fn save_glyph_results(&self, text: &str, glyphs: &mut GlyphStore, buffer: *hb_buffer_t) { let glyph_data = ShapedGlyphData::new(buffer); let glyph_count = glyph_data.len(); let byte_max = text.len(); let char_max = text.char_len(); // GlyphStore records are indexed by character, not byte offset. // so, we must be careful to increment this when saving glyph entries. let mut char_idx = 0; assert!(glyph_count <= char_max); debug!("Shaped text[char count={:u}], got back {:u} glyph info records.", char_max, glyph_count); if char_max != glyph_count { debug!("NOTE: Since these are not equal, we probably have been given some complex \ glyphs."); } // make map of what chars have glyphs let mut byteToGlyph: ~[i32]; // fast path: all chars are single-byte. if byte_max == char_max {<|fim▁hole|> byteToGlyph = vec::from_elem(byte_max, NO_GLYPH); } else { byteToGlyph = vec::from_elem(byte_max, CONTINUATION_BYTE); for (i, _) in text.char_offset_iter() { byteToGlyph[i] = NO_GLYPH; } } debug!("(glyph idx) -> (text byte offset)"); for i in range(0, glyph_data.len()) { // loc refers to a *byte* offset within the utf8 string. let loc = glyph_data.byte_offset_of_glyph(i); if loc < byte_max { assert!(byteToGlyph[loc] != CONTINUATION_BYTE); byteToGlyph[loc] = i as i32; } else { debug!("ERROR: tried to set out of range byteToGlyph: idx={:u}, glyph idx={:u}", loc, i); } debug!("{:u} -> {:u}", i, loc); } debug!("text: {:s}", text); debug!("(char idx): char->(glyph index):"); for (i, ch) in text.char_offset_iter() { debug!("{:u}: {} --> {:d}", i, ch, byteToGlyph[i] as int); } // some helpers let mut glyph_span: Range = Range::empty(); // this span contains first byte of first char, to last byte of last char in range. // so, end() points to first byte of last+1 char, if it's less than byte_max. let mut char_byte_span: Range = Range::empty(); let mut y_pos = Au(0); // main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars. // in cases with complex glyph-character assocations, 2+ glyphs and 1+ chars can be // processed. while glyph_span.begin() < glyph_count { // start by looking at just one glyph. glyph_span.extend_by(1); debug!("Processing glyph at idx={:u}", glyph_span.begin()); let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin()); char_byte_span.reset(char_byte_start, 0); // find a range of chars corresponding to this glyph, plus // any trailing chars that do not have associated glyphs. while char_byte_span.end() < byte_max { let range = text.char_range_at(char_byte_span.end()); ignore(range.ch); char_byte_span.extend_to(range.next); debug!("Processing char byte span: off={:u}, len={:u} for glyph idx={:u}", char_byte_span.begin(), char_byte_span.length(), glyph_span.begin()); while char_byte_span.end() != byte_max && byteToGlyph[char_byte_span.end()] == NO_GLYPH { debug!("Extending char byte span to include byte offset={:u} with no associated \ glyph", char_byte_span.end()); let range = text.char_range_at(char_byte_span.end()); ignore(range.ch); char_byte_span.extend_to(range.next); } // extend glyph range to max glyph index covered by char_span, // in cases where one char made several glyphs and left some unassociated chars. let mut max_glyph_idx = glyph_span.end(); for i in char_byte_span.eachi() { if byteToGlyph[i] > NO_GLYPH { max_glyph_idx = uint::max(byteToGlyph[i] as uint, max_glyph_idx); } } if max_glyph_idx > glyph_span.end() { glyph_span.extend_to(max_glyph_idx); debug!("Extended glyph span (off={:u}, len={:u}) to cover char byte span's max \ glyph index", glyph_span.begin(), glyph_span.length()); } // if there's just one glyph, then we don't need further checks. if glyph_span.length() == 1 { break; } // if no glyphs were found yet, extend the char byte range more. if glyph_span.length() == 0 { continue; } debug!("Complex (multi-glyph to multi-char) association found. This case \ probably doesn't work."); let mut all_glyphs_are_within_cluster: bool = true; for j in glyph_span.eachi() { let loc = glyph_data.byte_offset_of_glyph(j); if !char_byte_span.contains(loc) { all_glyphs_are_within_cluster = false; break } } debug!("All glyphs within char_byte_span cluster?: {}", all_glyphs_are_within_cluster); // found a valid range; stop extending char_span. if all_glyphs_are_within_cluster { break } } // character/glyph clump must contain characters. assert!(char_byte_span.length() > 0); // character/glyph clump must contain glyphs. assert!(glyph_span.length() > 0); // now char_span is a ligature clump, formed by the glyphs in glyph_span. // we need to find the chars that correspond to actual glyphs (char_extended_span), //and set glyph info for those and empty infos for the chars that are continuations. // a simple example: // chars: 'f' 't' 't' // glyphs: 'ftt' '' '' // cgmap: t f f // gspan: [-] // cspan: [-] // covsp: [---------------] let mut covered_byte_span = char_byte_span.clone(); // extend, clipping at end of text range. while covered_byte_span.end() < byte_max && byteToGlyph[covered_byte_span.end()] == NO_GLYPH { let range = text.char_range_at(covered_byte_span.end()); ignore(range.ch); covered_byte_span.extend_to(range.next); } if covered_byte_span.begin() >= byte_max { // oops, out of range. clip and forget this clump. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end(); // FIXME: borrow checker workaround char_byte_span.reset(end, 0); } // clamp to end of text. (I don't think this will be necessary, but..) let end = covered_byte_span.end(); // FIXME: borrow checker workaround covered_byte_span.extend_to(uint::min(end, byte_max)); // fast path: 1-to-1 mapping of single char and single glyph. if glyph_span.length() == 1 { // TODO(Issue #214): cluster ranges need to be computed before // shaping, and then consulted here. // for now, just pretend that every character is a cluster start. // (i.e., pretend there are no combining character sequences). // 1-to-1 mapping of character to glyph also treated as ligature start. let shape = glyph_data.get_entry_for_glyph(glyph_span.begin(), &mut y_pos); let data = GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, true, true); glyphs.add_glyph_for_char_index(char_idx, &data); } else { // collect all glyphs to be assigned to the first character. let mut datas = ~[]; for glyph_i in glyph_span.eachi() { let shape = glyph_data.get_entry_for_glyph(glyph_i, &mut y_pos); datas.push(GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, // not missing true, // treat as cluster start glyph_i > glyph_span.begin())); // all but first are ligature continuations } // now add the detailed glyph entry. glyphs.add_glyphs_for_char_index(char_idx, datas); // set the other chars, who have no glyphs let mut i = covered_byte_span.begin(); loop { let range = text.char_range_at(i); ignore(range.ch); i = range.next; if i >= covered_byte_span.end() { break; } char_idx += 1; glyphs.add_nonglyph_for_char_index(char_idx, false, false); } } // shift up our working spans past things we just handled. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end();; // FIXME: borrow checker workaround char_byte_span.reset(end, 0); char_idx += 1; } // this must be called after adding all glyph data; it sorts the // lookup table for finding detailed glyphs by associated char index. glyphs.finalize_changes(); } } /// Callbacks from Harfbuzz when font map and glyph advance lookup needed. extern fn glyph_func(_: *hb_font_t, font_data: *c_void, unicode: hb_codepoint_t, _: hb_codepoint_t, glyph: *mut hb_codepoint_t, _: *c_void) -> hb_bool_t { let font: *Font = font_data as *Font; assert!(font.is_not_null()); unsafe { match (*font).glyph_index(char::from_u32(unicode).unwrap()) { Some(g) => { *glyph = g as hb_codepoint_t; true as hb_bool_t } None => false as hb_bool_t } } } extern fn glyph_h_advance_func(_: *hb_font_t, font_data: *c_void, glyph: hb_codepoint_t, _: *c_void) -> hb_position_t { let font: *mut Font = font_data as *mut Font; assert!(font.is_not_null()); unsafe { let advance = (*font).glyph_h_advance(glyph as GlyphIndex); Shaper::float_to_fixed(advance) } } // Callback to get a font table out of a font. extern fn get_font_table_func(_: *hb_face_t, tag: hb_tag_t, user_data: *c_void) -> *hb_blob_t { unsafe { let font: *Font = user_data as *Font; assert!(font.is_not_null()); // TODO(Issue #197): reuse font table data, which will change the unsound trickery here. match (*font).get_table_for_tag(tag as FontTableTag) { None => null(), Some(ref font_table) => { let skinny_font_table_ptr: *FontTable = font_table; // private context let mut blob: *hb_blob_t = null(); do (*skinny_font_table_ptr).with_buffer |buf: *u8, len: uint| { // HarfBuzz calls `destroy_blob_func` when the buffer is no longer needed. blob = hb_blob_create(buf as *c_char, len as c_uint, HB_MEMORY_MODE_READONLY, transmute(skinny_font_table_ptr), destroy_blob_func); } assert!(blob.is_not_null()); blob } } } } // TODO(Issue #197): reuse font table data, which will change the unsound trickery here. // In particular, we'll need to cast to a boxed, rather than owned, FontTable. // even better, should cache the harfbuzz blobs directly instead of recreating a lot. extern fn destroy_blob_func(_: *c_void) { // TODO: Previous code here was broken. Rewrite. }<|fim▁end|>
<|file_name|>CreateFileCommand.java<|end_file_name|><|fim▁begin|>package fs.command; import fs.App; import fs.Disk; import fs.util.FileUtils; import java.util.Arrays; /** * * @author José Andrés García Sáenz <[email protected]><|fim▁hole|>public class CreateFileCommand extends Command { public final static String COMMAND = "mkfile"; @Override public void execute(String[] args) { if (args.length != 2 && args.length != 3) { reportSyntaxError(); return; } String path = args[1]; String content = String.join(" ", Arrays.copyOfRange(args, 2, args.length)); App app = App.getInstance(); Disk disk = app.getDisk(); if (disk.exists(path) && !FileUtils.promptForVirtualOverride(path)) { return; } try { disk.createFile(path, content); } catch (Exception ex) { reportError(ex); } } @Override protected String getName() { return CreateFileCommand.COMMAND; } @Override protected String getDescription() { return "Create a file and set its content."; } @Override protected String getSyntax() { return getName() + " FILENAME \"<CONTENT>\""; } }<|fim▁end|>
*/
<|file_name|>cvar.cc<|end_file_name|><|fim▁begin|>// This file is part of the :(){ :|:& };:'s project // Licensing information can be found in the LICENSE file // (C) 2014 :(){ :|:& };:. All rights reserved. #include "sys/common.h" CVar * CVar::root = NULL; // ----------------------------------------------------------------------------- void CVar::Init(const std::string& name, int flags, const std::string& val, float min, float max, const char ** pool, const std::string& desc) { this->name = name; this->min = min; this->max = max; this->pool = pool; this->desc = desc; this->valueString = ""; this->next = root; root = this; this->flags = flags & ~CVAR_READONLY; SetString(val); this->flags = flags & ~CVAR_MODIFIED; } // ----------------------------------------------------------------------------- void CVar::SetBool(bool b) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'"; } valueBool = b; valueInt = b ? 1 : 0; valueFloat = b ? 1.0f : 0.0f; valueString = b ? "true" : "false"; return; } // ----------------------------------------------------------------------------- void CVar::SetInt(int i) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'"; } valueBool = i ? true : false; valueInt = i; valueFloat = (float)valueInt; if (flags & CVAR_BOOL) { valueString = valueBool ? "true" : "false"; } else if (flags & CVAR_INT || flags & CVAR_STRING) { valueString.resize(20); sprintf(&valueString[0], "%d", valueInt); } else if (flags & CVAR_FLOAT) { valueString.resize(20); sprintf(&valueString[0], "%ff", valueFloat); } } // ----------------------------------------------------------------------------- void CVar::SetFloat(float f) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'";; } valueFloat = f; valueBool = abs(valueFloat) <= 1e-5 ? false : true; valueInt = (int)valueFloat; if (flags & CVAR_BOOL) { valueString = strdup(valueBool ? "true" : "false"); } else if (flags & CVAR_INT) { valueString.resize(20); sprintf(&valueString[0], "%d", valueInt); } else if (flags & CVAR_FLOAT || flags & CVAR_STRING) { valueString.resize(20); sprintf(&valueString[0], "%ff", valueFloat); } } // ----------------------------------------------------------------------------- void CVar::SetString(const std::string& str) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'"; } if (pool) { valueBool = false; valueInt = 0; valueFloat = 0.0f; valueString = ""; for (int i = 0; pool[i]; ++i) { if (str == pool[i]) { valueBool = true; valueInt = i; valueFloat = (float)i; valueString = str; } } return; } if (flags & CVAR_BOOL) { valueBool = str == "true"; valueInt = valueBool ? 1 : 0; valueFloat = valueBool ? 1.0f : 0.0f; valueString = valueBool ? "true" : "false"; return; } else if (flags & CVAR_INT) { valueInt = atoi(str.c_str()); valueBool = valueInt ? true : false; valueFloat = (float)valueInt; valueString.resize(20); sprintf(&valueString[0], "%d", valueInt); return; } else if (flags & CVAR_FLOAT) { valueFloat = (float)atof(str.c_str()); valueBool = abs(valueFloat) <= 1e-5 ? false : true; valueInt = (int)valueFloat; valueString.resize(20); sprintf(&valueString[0], "%ff", valueFloat); return; } else if (flags & CVAR_STRING) { valueBool = !str.empty(); valueInt = !str.empty(); valueFloat = str.empty() ? 0.0f : 1.0f;<|fim▁hole|> } }<|fim▁end|>
valueString = str; return;
<|file_name|>generate_executions.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Machine Description Interface C API # # This software is delivered under the terms of the MIT License # # Copyright (c) 2016 STMicroelectronics # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell<|fim▁hole|># The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # from __future__ import print_function import sys class ENUM: instructions_list = [] def __init__(self, ID, mnemonic, properties, parsing, encoding, short_desc, execution, description): self.ID = ID self.mnemonic = mnemonic self.properties = properties self.parsing = parsing self.encoding = encoding self.short_desc = short_desc self.execution = execution self.description = description self.instructions_list.append(self) @staticmethod def emit_execution(out): with open(out, "w") as outf: print("/* BEGIN: Generated executions */", file=outf) ENUM._emit_executions(outf) print("/* END: Generated executions */", file=outf) @staticmethod def _emit_executions(out): idx = 0; print("#define P(idx) EXE_OPS(_operands,idx)", file=out) print("#define NEXT_PC() (RR(PC,0) + _op_size)", file=out) print("#define RR(rf,idx) EXE_CPU_RR((*_cpu_prev),rf,idx)", file=out) print("#define RS(rf,idx) EXE_CPU_RS(_cpu,rf,idx)", file=out) print("#define MR32(idx) EXE_MEM_FETCH32(_mem,idx)", file=out) print("#define MS32(idx) EXE_MEM_SLICE32(_mem,idx)", file=out) for inst in ENUM.instructions_list: print("", file=out) print("static int32_t _execution_%i /* %s */ (EXE_CTX_T _context, EXE_OPS_T _operands, size_t _op_size)" % (idx, inst.ID), file=out) print("{", file=out) print(" CPU_T _cpu, *_cpu_prev = EXE_CTX_CPU(_context);", file=out) print(" MEM_T _mem, *_mem_prev = EXE_CTX_MEM(_context);", file=out) print(" EXE_CPU_CLONE(_cpu, _cpu_prev);", file=out) print(" EXE_MEM_CLONE(_mem, _mem_prev);", file=out) print(" RS(PC,0) = NEXT_PC();", file=out) print(" %s;" % inst.execution, file=out) print(" EXE_CPU_UPDATE(*_cpu_prev, &_cpu);", file=out); print(" EXE_CPU_UPDATE(*_mem_prev, &_mem);", file=out); print(" return 0;", file=out) print("}", file=out); idx += 1 print("#undef RF", file=out) print("#undef MEM", file=out) print("typedef int32_t (*EXE_FUNC_T)(EXE_CTX_T _context, EXE_OPS_T _operands, size_t _op_size);", file=out); print("static const EXE_FUNC_T _executions[] = {", file=out) idx = 0 for inst in ENUM.instructions_list: print(" _execution_%i /* %s */," % (idx, inst.ID), file=out) idx += 1 print("};", file=out) execfile(sys.argv[1]) ENUM.emit_execution(sys.argv[2])<|fim▁end|>
# copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: #
<|file_name|>import.component.ts<|end_file_name|><|fim▁begin|>import {Component} from 'angular2/core'; import {FORM_DIRECTIVES, NgFor} from 'angular2/common'; import {Http} from 'angular2/http'; import {RuneService} from '../../services/rune/rune.service'; import {MasteryService} from '../../services/mastery/mastery.service'; @Component({ selector: 'import-component', directives: [FORM_DIRECTIVES, NgFor], template: ` <form class="form-inline" (ngSubmit)="onSubmit()" #form="ngForm"> <div class="form-group"> <input class="form-control" type="text" placeholder="Summoner name" [(ngModel)]="summoner.name" ng-control="name" #name="ngForm" required> </div> <div class="form-group"> <select class="form-control" [(ngModel)]="summoner.server" ng-control="server" #server="ngForm" required> <option *ngFor="#server of servers" [value]="server">{{ server | uppercase }}</option> </select> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Load" [disabled]="!form.form.valid"> </div> </form> ` }) export class ImportComponent { public summoner: Summoner = new Summoner(); public servers: string[] = [ 'br', 'eune', 'euw', 'kr', 'lan', 'las', 'na', 'oce', 'ru', 'tr' ]; constructor( public http: Http, public runeService: RuneService, public masteryService: MasteryService ) { } onSubmit() { this.http.get(`../${this.summoner.server}/${this.summoner.name}`) .subscribe( (res) => { const data = res.json(); // Because future patches may break the application, loaders // are encapsulated within try catch block. try { // This block may produce error. this.runeService.loadRunes(data.runes); this.masteryService.loadMasteries(data.masteries); // Hey, everything is loaded and ready! alert('Data loaded!'); } catch(error) { // Ouch! Something gone terribly wrong! // Reset application to original state. this.runeService.pages = []; this.runeService.addPage(); this.masteryService.pages = []; this.masteryService.addPage(); // Inform user about error.<|fim▁hole|> alert('Error during loading. Data did not load. Please contact author or create issue on github.'); } }, (error) => { const err = error.json(); alert(`${err.statusCode}: ${err.message}`); } ); // Reset form. this.summoner.reset(); } } class Summoner { constructor( public server: string = '', public name: string = '' ) { } reset(): void { this.server = this.name = ''; } }<|fim▁end|>
<|file_name|>whenMessageEndsWith.test.ts<|end_file_name|><|fim▁begin|>import { MessageHandler } from "../src"; import { MessageMock } from "./__mocks__/message-mock"; describe("MessageHandler.whenMessageEndsWith test", () => { test("whenMessageEndsWith should fire", () => { // Given const handler = new MessageHandler(); const callback = jest.fn()<|fim▁hole|> const message = new MessageMock("lorem ipsum foo"); handler.handleMessage(message); // Then expect(callback).toHaveBeenCalled(); }); test("whenMessageEndsWith should not fire", () => { // Given const handler = new MessageHandler(); const callback = jest.fn() handler.whenMessageEndsWith("foo").do(callback) // When const message = new MessageMock("lorem foo ipsum"); handler.handleMessage(message); // Then expect(callback).toBeCalledTimes(0); }); });<|fim▁end|>
handler.whenMessageEndsWith("foo").do(callback) // When
<|file_name|>nav.js<|end_file_name|><|fim▁begin|>/* globals $ */ const modals = window.modals; const footer = window.footer; const notifier = window.notifier; const admin = window.admin; ((scope) => { const modalLogin = modals.get("login"); const modalRegister = modals.get("register"); const helperFuncs = { loginUser(userToLogin) { const url = window.baseUrl + "login"; // loader.show(); // $("#loader .loader-title").html("Creating"); Promise.all([http.postJSON(url, userToLogin), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result.success) { res = resp.result; let html = templateFunc({ res }); $("#nav-wrap").html(html); notifier.success(`Welcome ${userToLogin.username}!`); } else { res = resp.result.success; notifier.error("Wrong username or password!"); } // loader.hide(); modalLogin.hide(); $("#content-wrap").addClass(res.role); }) .then(() => { console.log($("#content-wrap").hasClass("admin")); if ($("#content-wrap").hasClass("admin")) { content.init("admin-content"); admin.init(); } if ($("#content-wrap").hasClass("standart")) { content.init("user-content"); users.init(); } }) .catch((err) => { // loader.hide(); notifier.error(`${userToLogin.username} not created! ${err}`); console.log(JSON.stringify(err)); }); }, registerUser(userToRegister) { const url = window.baseUrl + "register"; // loader.show(); // $("#loader .loader-title").html("Creating Book"); Promise.all([http.postJSON(url, userToRegister), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result.success) { res = false; } else { res = resp.result; console.log(resp); // let html = templateFunc({ // res // }); // $("#nav-wrap").html(html); } // loader.hide(); modalRegister.hide(); }) .catch((err) => { // loader.hide(); notifier.error(`${userToLogin.username} not created! ${err}`); console.log(JSON.stringify(err)); }); }, loginFormEvents() { const $form = $("#form-login"); $form.on("submit", function() { const user = { username: $("#tb-username").val(), password: $("#tb-password").val() }; console.log(user); helperFuncs.loginUser(user); return false; }); }, registerFormEvents() { const $form = $("#form-register"); $form.on("submit", function() { const user = { firstName: $("#tb-firstname").val(), lastName: $("#tb-lastname").val(), username: $("#tb-username").val(), password: $("#tb-password").val() }; helperFuncs.registerUser(user); return false; }); }, menuCollaps() { let pull = $("#pull"); menu = $("nav ul"); link = $("#subMenu"); signUp = $("#signUp"); submenu = $("nav li ul"); console.log(link); menuHeight = menu.height(); $(pull).on("click", function(ev) { ev.preventDefault(); menu.slideToggle(); submenu.hide(); }); $(link).on("click", function(ev) { ev.preventDefault(); signUp.next().hide(); link.next().slideToggle(); }); $(signUp).on("click", function(ev) { ev.preventDefault(); link.next().hide(); signUp.next().slideToggle(); }); $(window).resize(function() { let win = $(window).width(); if (win > 760 && menu.is(":hidden")) { menu.removeAttr("style"); } }); } }; const initial = () => { const url = window.baseUrl + "users"; Promise .all([http.get(url), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result === "unauthorized!") { res = false; } else { res = resp.result; } let html = templateFunc({ res }); $("#nav-wrap").html(html); $(".btn-login-modal").on("click", () => { modalLogin.show() .then(() => { helperFuncs.loginFormEvents(); }); }); $("#btn-register-modal").on("click", () => { modalRegister.show() .then(() => { helperFuncs.registerFormEvents(); }); }); }) .then(footer.init()) .then(() => { content.init("no-user-content"); }) .then(() => { helperFuncs.menuCollaps();<|fim▁hole|> Handlebars.registerHelper("ifEq", (v1, v2, options) => { if (v1 === v2) { return options.fn(this); } return options.inverse(this); }); Handlebars.registerHelper("mod3", (index, options) => { if ((index + 1) % 3 === 0) { return options.fn(this); } return options.inverse(this); }); }; scope.nav = { initial }; })(window.controllers = window.controllers || {});<|fim▁end|>
});
<|file_name|>AuthService.spec.ts<|end_file_name|><|fim▁begin|>import {addProviders} from '@angular/core/testing' import {Response, ResponseOptions, RequestMethod} from '@angular/http' import {injectService, defaultProviders} from '../../../testing/Utils' import {Environment} from '../../Environment' import {AuthService} from './AuthService' <|fim▁hole|> let testProviders: Array<any> = []; describe('AuthServicet', () => { let authService: AuthService let http, mockBackend beforeEach(() => addProviders(defaultProviders.concat(testProviders))); beforeEach(injectService(AuthService, (Instance, Mock, Http) => { authService = Instance; mockBackend = Mock; http = Http; })); describe('.authenticate()', () => { it('calls localhost', () => { mockBackend.connections.subscribe(c => { expect(c.request.url).toEqual(createUrl('/api/auth/login')) let body = JSON.parse(c.request._body) expect(body.email).toEqual('foo') expect(body.password).toEqual('bar') }) authService.authenticate('foo', 'bar') }) it('should invoke success function if request succeeded', (done) => { let response = new Response(new ResponseOptions({ body: '{}' })) mockBackend.connections.subscribe(c => { c.mockRespond(response) }) authService.authenticate('', '').subscribe(() => { done(); }) }) xit('should invoke error function if request fails', (done) => { let response = new Response(new ResponseOptions({ body: '{}' })) mockBackend.connections.subscribe(c => { c.mockError(response) }) authService.authenticate('', '').subscribe(() => { }, () => { done(); }) }) }) describe('inviteContacts()', () => { it('should call invite endpoint', (done) => { let emails = ['foo', 'bar', 'baz'] mockBackend.connections.subscribe(c => { expect(c.request.method).toEqual(RequestMethod.Post) expect(c.request.url).toEqual(createUrl('/api/user/invite')) let body = JSON.parse(c.request._body) expect(body.emails).toEqual(JSON.stringify(emails)) done() }) authService.inviteContacts(emails) }) }) describe('.recoverPassword()', () => { it('calls localhost', (done) => { mockBackend.connections.subscribe(c => { expect(c.request.url).toEqual(createUrl('/api/auth/recover')) let body = JSON.parse(c.request._body) expect(body.email).toEqual('foo') done() }) authService.recoverPassword('foo') }) it('should invoke success function if request succeeded', (done) => { let response = new Response(new ResponseOptions({ body: '{}' })) mockBackend.connections.subscribe(c => { c.mockRespond(response) }) authService.recoverPassword('').subscribe(() => { done(); }) }) xit('should invoke error function if request fails', (done) => { let response = new Response(new ResponseOptions({ body: '{}' })) mockBackend.connections.subscribe(c => { c.mockError(response) }) authService.recoverPassword('').subscribe(() => { }, () => { done(); }) }) }) })<|fim▁end|>
function createUrl(endpoint: string) { return Environment.HOST + endpoint }
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import include, url from . import views<|fim▁hole|> url(r'^hello', views.hello), ]<|fim▁end|>
urlpatterns = [ url(r'^$', views.channel_list), url(r'^play', views.play_channel),
<|file_name|>binary_manager.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function from __future__ import absolute_import import contextlib import logging import os import py_utils from py_utils import binary_manager from py_utils import cloud_storage from py_utils import dependency_util import dependency_manager from dependency_manager import base_config from devil import devil_env from telemetry.core import exceptions from telemetry.core import util TELEMETRY_PROJECT_CONFIG = os.path.join( util.GetTelemetryDir(), 'telemetry', 'binary_dependencies.json') CHROME_BINARY_CONFIG = os.path.join(util.GetCatapultDir(), 'common', 'py_utils', 'py_utils', 'chrome_binaries.json') SUPPORTED_DEP_PLATFORMS = ( 'linux_aarch64', 'linux_x86_64', 'linux_armv7l', 'linux_mips', 'mac_x86_64', 'mac_arm64', 'win_x86', 'win_AMD64', 'android_arm64-v8a', 'android_armeabi-v7a', 'android_arm', 'android_x64', 'android_x86' ) PLATFORMS_TO_DOWNLOAD_FOLDER_MAP = { 'linux_aarch64': 'bin/linux/aarch64', 'linux_x86_64': 'bin/linux/x86_64', 'linux_armv7l': 'bin/linux/armv7l', 'linux_mips': 'bin/linux/mips', 'mac_x86_64': 'bin/mac/x86_64', 'mac_arm64': 'bin/mac/arm64', 'win_x86': 'bin/win/x86', 'win_AMD64': 'bin/win/AMD64', 'android_arm64-v8a': 'bin/android/arm64-v8a', 'android_armeabi-v7a': 'bin/android/armeabi-v7a', 'android_arm': 'bin/android/arm', 'android_x64': 'bin/android/x64', 'android_x86': 'bin/android/x86', } NoPathFoundError = dependency_manager.NoPathFoundError CloudStorageError = dependency_manager.CloudStorageError _binary_manager = None _installed_helpers = set() TELEMETRY_BINARY_BASE_CS_FOLDER = 'binary_dependencies' TELEMETRY_BINARY_CS_BUCKET = cloud_storage.PUBLIC_BUCKET def NeedsInit(): return not _binary_manager def InitDependencyManager(client_configs): if GetBinaryManager(): raise exceptions.InitializationError( 'Trying to re-initialize the binary manager with config %s' % client_configs) configs = [] if client_configs: configs += client_configs configs += [TELEMETRY_PROJECT_CONFIG, CHROME_BINARY_CONFIG] SetBinaryManager(binary_manager.BinaryManager(configs)) devil_env.config.Initialize() @contextlib.contextmanager def TemporarilyReplaceBinaryManager(manager): old_manager = GetBinaryManager() try: SetBinaryManager(manager) yield finally: SetBinaryManager(old_manager) def GetBinaryManager(): return _binary_manager def SetBinaryManager(manager): global _binary_manager # pylint: disable=global-statement _binary_manager = manager def _IsChromeOSLocalMode(os_name): """Determines if we're running telemetry on a Chrome OS device. Used to differentiate local mode (telemetry running on the CrOS DUT) from remote mode (running telemetry on another platform that communicates with the CrOS DUT over SSH). """ return os_name == 'chromeos' and py_utils.GetHostOsName() == 'chromeos' def FetchPath(binary_name, os_name, arch, os_version=None): """ Return a path to the appropriate executable for <binary_name>, downloading from cloud storage if needed, or None if it cannot be found. """ if GetBinaryManager() is None: raise exceptions.InitializationError( 'Called FetchPath with uninitialized binary manager.') return GetBinaryManager().FetchPath( binary_name, 'linux' if _IsChromeOSLocalMode(os_name) else os_name, arch, os_version) def LocalPath(binary_name, os_name, arch, os_version=None): """ Return a local path to the given binary name, or None if an executable cannot be found. Will not download the executable. """ if GetBinaryManager() is None: raise exceptions.InitializationError( 'Called LocalPath with uninitialized binary manager.') return GetBinaryManager().LocalPath(binary_name, os_name, arch, os_version) def FetchBinaryDependencies( platform, client_configs, fetch_reference_chrome_binary): """ Fetch all binary dependenencies for the given |platform|. Note: we don't fetch browser binaries by default because the size of the binary is about 2Gb, and it requires cloud storage permission to chrome-telemetry bucket. Args: platform: an instance of telemetry.core.platform client_configs: A list of paths (string) to dependencies json files. fetch_reference_chrome_binary: whether to fetch reference chrome binary for the given platform. """ configs = [ dependency_manager.BaseConfig(TELEMETRY_PROJECT_CONFIG), ] dep_manager = dependency_manager.DependencyManager(configs) os_name = platform.GetOSName() # If we're running directly on a Chrome OS device, fetch the binaries for # linux instead, which should be compatible with CrOS. Otherwise, if we're # running remotely on CrOS, fetch the binaries for the host platform like # we do with android below. if _IsChromeOSLocalMode(os_name): os_name = 'linux' target_platform = '%s_%s' % (os_name, platform.GetArchName()) dep_manager.PrefetchPaths(target_platform) host_platform = None fetch_devil_deps = False if os_name in ('android', 'chromeos'): host_platform = '%s_%s' % ( py_utils.GetHostOsName(), py_utils.GetHostArchName()) dep_manager.PrefetchPaths(host_platform) if os_name == 'android': if host_platform == 'linux_x86_64': fetch_devil_deps = True else: logging.error('Devil only supports 64 bit linux as a host platform. ' 'Android tests may fail.') if fetch_reference_chrome_binary: _FetchReferenceBrowserBinary(platform) # For now, handle client config separately because the BUILD.gn & .isolate of # telemetry tests in chromium src failed to include the files specified in its # client config. # (https://github.com/catapult-project/catapult/issues/2192) # For now this is ok because the client configs usually don't include cloud # storage infos. # TODO(crbug.com/1111556): remove the logic of swallowing exception once the # issue is fixed on Chromium side. if client_configs: manager = dependency_manager.DependencyManager( list(dependency_manager.BaseConfig(c) for c in client_configs)) try: manager.PrefetchPaths(target_platform) if host_platform is not None: manager.PrefetchPaths(host_platform) except dependency_manager.NoPathFoundError as e: logging.error('Error when trying to prefetch paths for %s: %s', target_platform, e) if fetch_devil_deps: devil_env.config.Initialize() devil_env.config.PrefetchPaths(arch=platform.GetArchName()) devil_env.config.PrefetchPaths() def ReinstallAndroidHelperIfNeeded(binary_name, install_path, device): """ Install a binary helper to a specific location. Args: binary_name: (str) The name of the binary from binary_dependencies.json install_path: (str) The path to install the binary at device: (device_utils.DeviceUtils) a device to install the helper to Raises: Exception: When the binary could not be fetched or could not be pushed to the device. """ if (device.serial, install_path) in _installed_helpers: return host_path = FetchPath(binary_name, 'android', device.GetABI()) if not host_path: raise Exception( '%s binary could not be fetched as %s', binary_name, host_path) device.PushChangedFiles([(host_path, install_path)]) device.RunShellCommand(['chmod', '777', install_path], check_return=True) _installed_helpers.add((device.serial, install_path)) def _FetchReferenceBrowserBinary(platform): os_name = platform.GetOSName() if _IsChromeOSLocalMode(os_name): os_name = 'linux' arch_name = platform.GetArchName() manager = binary_manager.BinaryManager( [CHROME_BINARY_CONFIG]) if os_name == 'android': os_version = dependency_util.GetChromeApkOsVersion( platform.GetOSVersionName()) manager.FetchPath( 'chrome_stable', os_name, arch_name, os_version) else: manager.FetchPath( 'chrome_stable', os_name, arch_name) def UpdateDependency(dependency, dep_local_path, version, os_name=None, arch_name=None): config = os.path.join( util.GetTelemetryDir(), 'telemetry', 'binary_dependencies.json') if not os_name: assert not arch_name, 'arch_name is specified but not os_name' os_name = py_utils.GetHostOsName() arch_name = py_utils.GetHostArchName() else: assert arch_name, 'os_name is specified but not arch_name' <|fim▁hole|> try: old_version = c.GetVersion(dependency, dep_platform) print('Updating from version: {}'.format(old_version)) except ValueError: raise RuntimeError( ('binary_dependencies.json entry for %s missing or invalid; please add ' 'it first! (need download_path and path_within_archive)') % dep_platform) if dep_local_path: c.AddCloudStorageDependencyUpdateJob( dependency, dep_platform, dep_local_path, version=version, execute_job=True)<|fim▁end|>
dep_platform = '%s_%s' % (os_name, arch_name) c = base_config.BaseConfig(config, writable=True)
<|file_name|>UrlInputHistory.ts<|end_file_name|><|fim▁begin|>/** * Copyright (c) Tiny Technologies, Inc. All rights reserved.<|fim▁hole|> * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ */ import { Arr, Type, Obj } from '@ephox/katamari'; import { console, localStorage } from '@ephox/dom-globals'; const STORAGE_KEY = 'tinymce-url-history'; const HISTORY_LENGTH = 5; // validation functions const isHttpUrl = (url: any): boolean => { return Type.isString(url) && /^https?/.test(url); }; const isArrayOfUrl = (a: any): boolean => { return Type.isArray(a) && a.length <= HISTORY_LENGTH && Arr.forall(a, isHttpUrl); }; const isRecordOfUrlArray = (r: any): boolean => { return Type.isObject(r) && Obj.find(r, (value) => !isArrayOfUrl(value)).isNone(); }; const getAllHistory = function (): Record<string, string[]> { const unparsedHistory = localStorage.getItem(STORAGE_KEY); if (unparsedHistory === null) { return {}; } // parse history let history; try { history = JSON.parse(unparsedHistory); } catch (e) { if (e instanceof SyntaxError) { // tslint:disable-next-line:no-console console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e); return {}; } throw e; } // validate the parsed value if (!isRecordOfUrlArray(history)) { // tslint:disable-next-line:no-console console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history); return {}; } return history; }; const setAllHistory = function (history: Record<string, string[]>) { if (!isRecordOfUrlArray(history)) { throw new Error('Bad format for history:\n' + JSON.stringify(history)); } localStorage.setItem(STORAGE_KEY, JSON.stringify(history)); }; const getHistory = function (fileType: string): string[] { const history = getAllHistory(); return Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : []; }; const addToHistory = function (url: string, fileType: string) { if (!isHttpUrl(url)) { return; } const history = getAllHistory(); const items = Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : []; const itemsWithoutUrl = Arr.filter(items, (item) => item !== url); history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH); setAllHistory(history); }; const clearHistory = function () { localStorage.removeItem(STORAGE_KEY); }; export { getHistory, addToHistory, clearHistory };<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") <|fim▁hole|>testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBefore(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["always-single-line"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a { background-size: 0 ,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0 ,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\n}", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\r\n}", description: "CRLF", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never-single-line"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a { background-size: 0,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0 ,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0 ,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\n}", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\r\n}", description: "CRLF", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, } ], })<|fim▁end|>
const rule = rules[ruleName]
<|file_name|>CompiledOperation.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.query.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.cache.EntryDestroyedException; import org.apache.geode.cache.Region; import org.apache.geode.cache.query.AmbiguousNameException; import org.apache.geode.cache.query.FunctionDomainException; import org.apache.geode.cache.query.NameResolutionException; import org.apache.geode.cache.query.QueryInvocationTargetException; import org.apache.geode.cache.query.QueryService; import org.apache.geode.cache.query.TypeMismatchException; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.pdx.PdxInstance; import org.apache.geode.pdx.PdxSerializationException; import org.apache.geode.pdx.internal.InternalPdxInstance; import org.apache.geode.pdx.internal.PdxString; /** * Class Description * * @version $Revision: 1.1 $ */ public class CompiledOperation extends AbstractCompiledValue { private final CompiledValue receiver; // may be null if implicit to scope private final String methodName; private final List args; @MakeNotStatic private static final ConcurrentMap cache = new ConcurrentHashMap(); // receiver is an ID or PATH that contains the operation name public CompiledOperation(CompiledValue receiver, String methodName, List args) { this.receiver = receiver; this.methodName = methodName; this.args = args; } @Override public List getChildren() { List list = new ArrayList(); if (this.receiver != null) { list.add(this.receiver); } list.addAll(this.args); return list; } public String getMethodName() { return this.methodName; } public List getArguments() { return this.args; } @Override public int getType() { return METHOD_INV; } public CompiledValue getReceiver(ExecutionContext cxt) { // receiver may be cached in execution context if (this.receiver == null && cxt != null) { return (CompiledValue) cxt.cacheGet(this); } return this.receiver; } @Override public boolean hasIdentifierAtLeafNode() { if (this.receiver.getType() == Identifier) { return true; } else { return this.receiver.hasIdentifierAtLeafNode(); } } @Override public CompiledValue getReceiver() { return this.getReceiver(null); } @Override public Object evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException { CompiledValue rcvr = getReceiver(context); Object result; Object evalRcvr; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); evalRcvr = rcvrItr.evaluate(context); /* * // evaluate on current iteration of collection if (rcvrItr != null) { result = * eval0(rcvrItr.evaluate(context), rcvrItr.getElementType().resolveClass(), context); } * * // function call: no functions implemented except keywords in the grammar throw new * TypeMismatchException("Could not resolve method named 'xyz'") */ } else { // if not null, then explicit receiver evalRcvr = rcvr.evaluate(context); } // short circuit null immediately if (evalRcvr == null) { return QueryService.UNDEFINED; } if (context.isCqQueryContext() && evalRcvr instanceof Region.Entry) { Region.Entry re = (Region.Entry) evalRcvr; if (re.isDestroyed()) { return QueryService.UNDEFINED; } try { evalRcvr = re.getValue(); } catch (EntryDestroyedException ede) { // Even though isDestory() check is made, the entry could // throw EntryDestroyedException if the value becomes null. return QueryService.UNDEFINED; } }<|fim▁hole|> // than the runtime type of the receiver Class resolveClass = null; // commented out because we currently always resolve the method // on the runtime types // CompiledValue rcvrVal = rcvrPath.getReceiver(); // if (rcvrVal.getType() == ID) // { // CompiledValue resolvedID = context.resolve(((CompiledID)rcvrVal).getId()); // if (resolvedID.getType() == ITERATOR) // { // resolveClass = ((RuntimeIterator)resolvedID).getBaseCollection().getConstraint(); // } // } // if (resolveClass == null) if (evalRcvr instanceof PdxInstance) { String className = ((PdxInstance) evalRcvr).getClassName(); try { resolveClass = InternalDataSerializer.getCachedClass(className); } catch (ClassNotFoundException cnfe) { throw new QueryInvocationTargetException(cnfe); } } else if (evalRcvr instanceof PdxString) { resolveClass = String.class; } else { resolveClass = evalRcvr.getClass(); } result = eval0(evalRcvr, resolveClass, context); // } // check for PR substitution // check for BucketRegion substitution PartitionedRegion pr = context.getPartitionedRegion(); if (pr != null && (result instanceof Region)) { if (pr.getFullPath().equals(((Region) result).getFullPath())) { result = context.getBucketRegion(); } } return result; } @Override public Set computeDependencies(ExecutionContext context) throws TypeMismatchException, AmbiguousNameException, NameResolutionException { List args = this.args; Iterator i = args.iterator(); while (i.hasNext()) { context.addDependencies(this, ((CompiledValue) i.next()).computeDependencies(context)); } CompiledValue rcvr = getReceiver(context); if (rcvr == null) // implicit iterator operation { // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); if (rcvrItr == null) { // no receiver resolved // function call: no functions implemented except keywords in the grammar throw new TypeMismatchException( String.format("Could not resolve method named ' %s '", this.methodName)); } // cache the receiver so we don't have to resolve it again context.cachePut(this, rcvrItr); return context.addDependency(this, rcvrItr); } // receiver is explicit return context.addDependencies(this, rcvr.computeDependencies(context)); } @edu.umd.cs.findbugs.annotations.SuppressWarnings( value = "RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED", justification = "Does not matter if the methodDispatch that isn't stored in the map is used") private Object eval0(Object receiver, Class resolutionType, ExecutionContext context) throws TypeMismatchException, FunctionDomainException, NameResolutionException, QueryInvocationTargetException { if (receiver == null || receiver == QueryService.UNDEFINED) return QueryService.UNDEFINED; List args = new ArrayList(); List argTypes = new ArrayList(); Iterator i = this.args.iterator(); while (i.hasNext()) { CompiledValue arg = (CompiledValue) i.next(); Object o = arg.evaluate(context); // undefined arg produces undefines method result if (o == QueryService.UNDEFINED) return QueryService.UNDEFINED; args.add(o); // pass in null for the type if the runtime value is null if (o == null) argTypes.add(null); // commented out because we currently always use the runtime type for args // else if (arg.getType() == Identifier) // { // CompiledValue resolved = context.resolve(((CompiledID)arg).getId()); // if (resolved != null && resolved.getType() == ITERATOR) // argTypes.add(((RuntimeIterator)resolved).getBaseCollection().getConstraint()); // else // argTypes.add(o.getClass()); // } else argTypes.add(o.getClass()); // otherwise use the runtime type } // see if in cache MethodDispatch methodDispatch; List key = Arrays.asList(new Object[] {resolutionType, this.methodName, argTypes}); methodDispatch = (MethodDispatch) CompiledOperation.cache.get(key); if (methodDispatch == null) { try { methodDispatch = new MethodDispatch(context.getCache().getQueryService().getMethodInvocationAuthorizer(), resolutionType, this.methodName, argTypes); } catch (NameResolutionException nre) { if (!org.apache.geode.cache.query.Struct.class.isAssignableFrom(resolutionType) && (DefaultQueryService.QUERY_HETEROGENEOUS_OBJECTS || DefaultQueryService.TEST_QUERY_HETEROGENEOUS_OBJECTS)) { return QueryService.UNDEFINED; } else { throw nre; } } // cache CompiledOperation.cache.putIfAbsent(key, methodDispatch); } if (receiver instanceof InternalPdxInstance) { try { receiver = ((InternalPdxInstance) receiver).getCachedObject(); } catch (PdxSerializationException ex) { throw new QueryInvocationTargetException(ex); } } else if (receiver instanceof PdxString) { receiver = ((PdxString) receiver).toString(); } return methodDispatch.invoke(receiver, args); } // Asif :Function for generating from clause @Override public void generateCanonicalizedExpression(StringBuilder clauseBuffer, ExecutionContext context) throws AmbiguousNameException, TypeMismatchException, NameResolutionException { // Asif: if the method name starts with getABC & argument list is empty // then canonicalize it to aBC int len; if (this.methodName.startsWith("get") && (len = this.methodName.length()) > 3 && (this.args == null || this.args.isEmpty())) { clauseBuffer.insert(0, len > 4 ? this.methodName.substring(4) : ""); clauseBuffer.insert(0, Character.toLowerCase(this.methodName.charAt(3))); } else if (this.args == null || this.args.isEmpty()) { clauseBuffer.insert(0, "()").insert(0, this.methodName); } else { // The method contains arguments which need to be canonicalized clauseBuffer.insert(0, ')'); CompiledValue cv = null; for (int j = this.args.size(); j > 0;) { cv = (CompiledValue) this.args.get(--j); cv.generateCanonicalizedExpression(clauseBuffer, context); clauseBuffer.insert(0, ','); } clauseBuffer.deleteCharAt(0).insert(0, '(').insert(0, this.methodName); } clauseBuffer.insert(0, '.'); CompiledValue rcvr = this.receiver; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name. The receiver will now be RuntimeIterator rcvr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); } rcvr.generateCanonicalizedExpression(clauseBuffer, context); } }<|fim▁end|>
// check if the receiver is the iterator, in which // case we resolve the method on the constraint rather
<|file_name|>test-utils.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*- import base64 import hashlib import io import nose import requests import aliyunauth.utils import aliyunauth.consts<|fim▁hole|>def test_cal_b64md5(): s_data = b"foo" l_data = b"bar" * aliyunauth.consts.MD5_CHUNK_SIZE # normal data, None nose.tools.eq_(aliyunauth.utils.cal_b64md5(None), None) def b64md5(data): return base64.b64encode(hashlib.md5(data).digest()).decode("utf8") # normal data, small size, bytes nose.tools.eq_(aliyunauth.utils.cal_b64md5(s_data), b64md5(s_data)) # normal data, small size, bytes nose.tools.eq_( aliyunauth.utils.cal_b64md5(s_data.decode("utf8")), b64md5(s_data) ) # io-like, big size, bytes nose.tools.eq_( aliyunauth.utils.cal_b64md5(io.BytesIO(l_data)), b64md5(l_data) ) # io-like, big size, str nose.tools.eq_( aliyunauth.utils.cal_b64md5(io.StringIO(l_data.decode("utf8"))), b64md5(l_data) ) def test_to_bytes(): nose.tools.ok_(isinstance( aliyunauth.utils.to_bytes(u"foo"), requests.compat.bytes )) nose.tools.ok_(isinstance( aliyunauth.utils.to_bytes(b"foo"), requests.compat.bytes )) nose.tools.eq_(aliyunauth.utils.to_bytes(u"福", "gb2312"), b'\xb8\xa3') def test_to_str(): nose.tools.ok_(isinstance( aliyunauth.utils.to_str(u"bar"), requests.compat.str ), "unicode to str failed") nose.tools.ok_(isinstance( aliyunauth.utils.to_str(b"bar"), requests.compat.str ), "bytes to str failed") nose.tools.eq_(aliyunauth.utils.to_str(b"\xb0\xf4", "gb2312"), u"棒") def test_percent_quote(): nose.tools.eq_( aliyunauth.utils.percent_quote(u"福棒 &?/*~=+foo\""), "%E7%A6%8F%E6%A3%92%20%26%3F%2F%2A~%3D%2Bfoo%22" ) def test_percent_encode(): nose.tools.eq_( aliyunauth.utils.percent_encode([("福 棒", "foo+bar"), ("none", None)]), "%E7%A6%8F%20%E6%A3%92=foo%2Bbar" ) nose.tools.eq_( aliyunauth.utils.percent_encode([("foo", "福"), ("bar", "棒")], True), "bar=%E6%A3%92&foo=%E7%A6%8F" )<|fim▁end|>
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""The Minecraft Server sensor platform.""" from __future__ import annotations from typing import Any from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import TIME_MILLISECONDS from homeassistant.core import HomeAssistant from . import MinecraftServer, MinecraftServerEntity from .const import ( ATTR_PLAYERS_LIST, DOMAIN, ICON_LATENCY_TIME, ICON_PLAYERS_MAX, ICON_PLAYERS_ONLINE, ICON_PROTOCOL_VERSION, ICON_VERSION, NAME_LATENCY_TIME, NAME_PLAYERS_MAX, NAME_PLAYERS_ONLINE, NAME_PROTOCOL_VERSION, NAME_VERSION, UNIT_PLAYERS_MAX, UNIT_PLAYERS_ONLINE, UNIT_PROTOCOL_VERSION, UNIT_VERSION, ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the Minecraft Server sensor platform.""" server = hass.data[DOMAIN][config_entry.unique_id] # Create entities list. entities = [ MinecraftServerVersionSensor(server), MinecraftServerProtocolVersionSensor(server), MinecraftServerLatencyTimeSensor(server), MinecraftServerPlayersOnlineSensor(server), MinecraftServerPlayersMaxSensor(server), ] # Add sensor entities. async_add_entities(entities, True) class MinecraftServerSensorEntity(MinecraftServerEntity, SensorEntity): """Representation of a Minecraft Server sensor base entity.""" def __init__( self, server: MinecraftServer, type_name: str, icon: str = None, unit: str = None, device_class: str = None, ) -> None: """Initialize sensor base entity.""" super().__init__(server, type_name, icon, device_class) self._state = None self._unit = unit @property def available(self) -> bool: """Return sensor availability.""" return self._server.online @property def state(self) -> Any: """Return sensor state.""" return self._state @property def unit_of_measurement(self) -> str: """Return sensor measurement unit.""" return self._unit class MinecraftServerVersionSensor(MinecraftServerSensorEntity): """Representation of a Minecraft Server version sensor.""" def __init__(self, server: MinecraftServer) -> None: """Initialize version sensor.""" super().__init__( server=server, type_name=NAME_VERSION, icon=ICON_VERSION, unit=UNIT_VERSION ) async def async_update(self) -> None: """Update version.""" self._state = self._server.version class MinecraftServerProtocolVersionSensor(MinecraftServerSensorEntity): """Representation of a Minecraft Server protocol version sensor.""" def __init__(self, server: MinecraftServer) -> None: """Initialize protocol version sensor.""" super().__init__( server=server, type_name=NAME_PROTOCOL_VERSION, icon=ICON_PROTOCOL_VERSION, unit=UNIT_PROTOCOL_VERSION, ) async def async_update(self) -> None: """Update protocol version.""" self._state = self._server.protocol_version class MinecraftServerLatencyTimeSensor(MinecraftServerSensorEntity): """Representation of a Minecraft Server latency time sensor.""" def __init__(self, server: MinecraftServer) -> None: """Initialize latency time sensor.""" super().__init__( server=server, type_name=NAME_LATENCY_TIME, icon=ICON_LATENCY_TIME, unit=TIME_MILLISECONDS, )<|fim▁hole|> async def async_update(self) -> None: """Update latency time.""" self._state = self._server.latency_time class MinecraftServerPlayersOnlineSensor(MinecraftServerSensorEntity): """Representation of a Minecraft Server online players sensor.""" def __init__(self, server: MinecraftServer) -> None: """Initialize online players sensor.""" super().__init__( server=server, type_name=NAME_PLAYERS_ONLINE, icon=ICON_PLAYERS_ONLINE, unit=UNIT_PLAYERS_ONLINE, ) async def async_update(self) -> None: """Update online players state and device state attributes.""" self._state = self._server.players_online extra_state_attributes = None players_list = self._server.players_list if players_list is not None and len(players_list) != 0: extra_state_attributes = {ATTR_PLAYERS_LIST: self._server.players_list} self._extra_state_attributes = extra_state_attributes @property def extra_state_attributes(self) -> dict[str, Any]: """Return players list in device state attributes.""" return self._extra_state_attributes class MinecraftServerPlayersMaxSensor(MinecraftServerSensorEntity): """Representation of a Minecraft Server maximum number of players sensor.""" def __init__(self, server: MinecraftServer) -> None: """Initialize maximum number of players sensor.""" super().__init__( server=server, type_name=NAME_PLAYERS_MAX, icon=ICON_PLAYERS_MAX, unit=UNIT_PLAYERS_MAX, ) async def async_update(self) -> None: """Update maximum number of players.""" self._state = self._server.players_max<|fim▁end|>
<|file_name|>BlockingRpcResponse.java<|end_file_name|><|fim▁begin|>package io.teknek.nibiru.transport.rpc; import io.teknek.nibiru.transport.BaseResponse; public class BlockingRpcResponse<T> implements BaseResponse { private String exception; private T rpcResult; public BlockingRpcResponse(){ } public String getException() { return exception; }<|fim▁hole|> this.exception = exception; } public T getRpcResult() { return rpcResult; } public void setRpcResult(T rpcResult) { this.rpcResult = rpcResult; } }<|fim▁end|>
public void setException(String exception) {
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>#include <rx/iterate.hpp> #include <rx/sum.hpp> #include <rx/take.hpp> #include <rx/select.hpp> #include <rx/where.hpp> #include <rx/concurrency.hpp> #include <boost/lexical_cast.hpp> #include <iostream> template<class T> class ConsoleWriter { public: typedef T value_type; void onnext(T const& value) { std::cout << value << std::endl; } void onerror(rx::error_type const& error) { std::cerr << error << std::endl; } void oncompleted() { std::cout << "completed" << std::endl; } }; class write_to_console { public: template<class Observable><|fim▁hole|> struct observable_type { typedef typename Observable::disposable_type type; }; template<class Observable> typename Observable::disposable_type operator()(Observable observable) const { return observable.subscribe(ConsoleWriter<typename Observable::value_type>()); } }; void run() { // auto cancel = rx::Disposable(); // cancel.dispose(); // cancel.dispose(); // cancel.dispose(); rx::EventLoopScheduler scheduler; // auto numbers // = rx::iterate(0, 15, scheduler) // | rx::take(5) // | rx::sum() // ; // std::cout << sizeof(rx::iterate(0, 15, scheduler)) << std::endl; // std::cout << sizeof(numbers) << std::endl; // auto c1 = numbers | write_to_console(); // auto c2 = numbers | write_to_console(); // auto c3 = numbers | write_to_console(); // auto c4 = numbers | write_to_console(); // auto c5 = numbers | write_to_console(); // auto cn = c1; // cn.dispose(); // c1.dispose(); // c1.dispose(); // c1.dispose(); // c2.dispose(); // c3.dispose(); // c4.dispose(); struct ToString { typedef std::string result_type; template<class T> result_type operator()(T value) const { return boost::lexical_cast<std::string>(value) + " **"; } }; struct Odd { template<class T> bool operator()(T const& value) const { throw std::runtime_error("custom error"); return 0 == (value % 2); } }; auto numbers2 = rx::iterate(0, 15, scheduler) | rx::where(Odd()) | rx::take(10) | rx::select(ToString()); numbers2 | write_to_console(); auto x = numbers2; x | rx::take(3) | write_to_console(); scheduler.pumpLoop(); } int main() { try { run(); } catch(std::exception const& error) { std::cerr << error.what() << std::endl; } return 0; }<|fim▁end|>
<|file_name|>Parent001.java<|end_file_name|><|fim▁begin|>package cn.bjsxt.oop.staticInitBlock; public class Parent001 /*extends Object*/ { static int aa; static { System.out.println(" 静态初始化Parent001"); aa=200; <|fim▁hole|><|fim▁end|>
} }
<|file_name|>alias.js<|end_file_name|><|fim▁begin|>import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import Ember from "ember-metal/core"; // Ember.assert import EmberError from "ember-metal/error"; import { Descriptor, defineProperty } from "ember-metal/properties"; import { ComputedProperty } from "ember-metal/computed"; import create from "ember-metal/platform/create"; import { meta, inspect } from "ember-metal/utils"; import { addDependentKeys, removeDependentKeys } from "ember-metal/dependent_keys"; export default function alias(altKey) { return new AliasedProperty(altKey); } export function AliasedProperty(altKey) { this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = create(Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function(obj, keyName) { addDependentKeys(this, obj, keyName, meta(obj)); }; AliasedProperty.prototype.didUnwatch = function(obj, keyName) { removeDependentKeys(this, obj, keyName, meta(obj)); }; AliasedProperty.prototype.setup = function(obj, keyName) { Ember.assert("Setting alias '" + keyName + "' on self", this.altKey !== keyName); var m = meta(obj); if (m.watching[keyName]) { addDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.teardown = function(obj, keyName) { var m = meta(obj); if (m.watching[keyName]) { removeDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.readOnly = function() { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new EmberError('Cannot set read-only property "' + keyName + '" on object: ' + inspect(obj)); } AliasedProperty.prototype.oneWay = function() { this.set = AliasedProperty_oneWaySet; return this; }; function AliasedProperty_oneWaySet(obj, keyName, value) {<|fim▁hole|> // Backwards compatibility with Ember Data AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = ComputedProperty.prototype.meta;<|fim▁end|>
defineProperty(obj, keyName, null); return set(obj, keyName, value); }
<|file_name|>mongo.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with lai-client. If not, see <http://www.gnu.org/licenses/>. import pymongo from pymongo.errors import AutoReconnect from lai.db.base import DBBase from lai.database import UPDATE_PROCESS, COMMIT_PROCESS from lai.database import DatabaseException, NotFoundError from lai import Document class DBMongo(DBBase): def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port def connect(self): try: self.connection = pymongo.Connection(self.host, self.port) self.db = self.connection[self.name] except AutoReconnect: raise DatabaseException("It's not possible connect to the database") def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id'] def search(self, regex): try: spec = {'$or': [{'data.content' : {'$regex': regex, '$options': 'im'}}, {'data.description': {'$regex': regex, '$options': 'im'}}]} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def get(self, id, pk='id', deleted=False): try: if pk == 'id': id = int(id) if deleted: spec = {pk: id} else: spec = {pk: id, 'data': {'$exists': 1}} fields = {'_id': 0} row = self.db.docs.find_one(spec, fields) except Exception as e: raise DatabaseException(e) if row: return Document(**row) raise NotFoundError('%s %s not found' % (pk, id)) def getall(self): try: spec = {'data': {'$exists': 1}} fields = {'_id': 0} sort = [('tid', 1)] cur = self.db.docs.find(spec, fields, sort=sort) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def save(self, doc):<|fim▁hole|> def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc def update(self, doc, process=None): if process is None: pk = 'id' id = doc.id doc.synced = False set = doc elif process == UPDATE_PROCESS: if self.db.docs.find({'sid': doc.sid}).count() == 0: return self.insert(doc, synced=True) pk = 'sid' id = doc.sid doc.synced = not doc.merged() # must be commited if was merged doc.merged(False) set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user, 'public': doc.public, 'synced': doc.synced} elif process == COMMIT_PROCESS: pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced} else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc def delete(self, doc): if doc.id is None: raise DatabaseException('Document does not have id') if doc.sid is None: try: rs = self.db.docs.remove({'id': doc.id}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return None doc.data = None return self.update(doc) def save_last_sync(self, ids, process): try: spec = {'_id': 'last_sync'} document = {'$set': {process: ids}} self.db.internal.update(spec, document, upsert=True) except Exception as e: raise DatabaseException(e) def get_docs_to_commit(self): try: spec = {'synced': False} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return list(cur) def get_last_tid(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0 def status(self): docs = {'updated' : [], 'committed': [], 'to_commit': []} row = self.db.internal.find_one({'_id': 'last_sync'}) if row and 'update' in row: for id in row['update']: docs['updated'].append(self.get(id, deleted=True)) if row and 'commit' in row: for id in row['commit']: docs['committed'].append(self.get(id, deleted=True)) to_commit = self.get_docs_to_commit() for row in to_commit: doc = Document(**row) docs['to_commit'].append(doc) return docs def __str__(self): return "%s://%s:%s/%s" % ('mongo', self.host, self.port, self.name)<|fim▁end|>
if doc.id: return self.update(doc) else: return self.insert(doc)
<|file_name|>MibObj.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.config.datacollection; import java.io.Reader; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.exolab.castor.xml.Validator; import org.opennms.core.xml.ValidateUsing; /** * a MIB object * * @version $Revision$ $Date$ */ @XmlRootElement(name="mibObj", namespace="http://xmlns.opennms.org/xsd/config/datacollection") @XmlAccessorType(XmlAccessType.NONE) @XmlType(propOrder={"oid", "instance", "alias", "type", "maxval", "minval"}) @ValidateUsing("datacollection-config.xsd") public class MibObj implements java.io.Serializable { private static final long serialVersionUID = -7831201614734695268L; /** * object identifier */ private String m_oid; /** * instance identifier. Only valid instance identifier * values are a positive integer value or the keyword * "ifIndex" which * indicates that the ifIndex of the interface is to be * substituted for * the instance value for each interface the oid is retrieved * for. */ private String m_instance; /** * a human readable name for the object (such as * "ifOctetsIn"). NOTE: This value is used as the RRD file * name and * data source name. RRD only supports data source names up to * 19 chars * in length. If the SNMP data collector encounters an alias * which * exceeds 19 characters it will be truncated. */ private String m_alias; /** * SNMP data type SNMP supported types: counter, gauge, * timeticks, integer, octetstring, string. The SNMP type is * mapped to * one of two RRD supported data types COUNTER or GAUGE, or * the * string.properties file. The mapping is as follows: SNMP * counter * -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring * -> * RRD GAUGE; SNMP string -> String properties file */ private String m_type; /** * Maximum Value. In order to correctly manage counter * wraps, it is possible to add a maximum value for a * collection. For * example, a 32-bit counter would have a max value of * 4294967295. */ private String m_maxval; /** * Minimum Value. For completeness, adding the ability * to use a minimum value. */ private String m_minval; public MibObj() { super(); } public MibObj(final String oid, final String instance, final String alias, final String type) { super(); m_oid = oid; m_instance = instance; m_alias = alias; m_type = type; } /** * Overrides the java.lang.Object.equals method. * * @param obj * @return true if the objects are equal. */ @Override() public boolean equals(final java.lang.Object obj) { if ( this == obj ) return true; if (obj instanceof MibObj) { final MibObj temp = (MibObj)obj; if (m_oid != null) { if (temp.m_oid == null) return false; else if (!(m_oid.equals(temp.m_oid))) return false; } else if (temp.m_oid != null) return false; if (m_instance != null) { if (temp.m_instance == null) return false; else if (!(m_instance.equals(temp.m_instance))) return false; } else if (temp.m_instance != null) return false; if (m_alias != null) { if (temp.m_alias == null) return false; else if (!(m_alias.equals(temp.m_alias))) return false; } else if (temp.m_alias != null) return false; if (m_type != null) { if (temp.m_type == null) return false; else if (!(m_type.equals(temp.m_type))) return false; } else if (temp.m_type != null) return false; if (m_maxval != null) { if (temp.m_maxval == null) return false; else if (!(m_maxval.equals(temp.m_maxval))) return false; } else if (temp.m_maxval != null) return false; if (m_minval != null) { if (temp.m_minval == null) return false; else if (!(m_minval.equals(temp.m_minval))) return false; } else if (temp.m_minval != null) return false; return true; } return false; } /** * Returns the value of field 'alias'. The field 'alias' has * the following description: a human readable name for the * object (such as * "ifOctetsIn"). NOTE: This value is used as the RRD file * name and * data source name. RRD only supports data source names up to * 19 chars * in length. If the SNMP data collector encounters an alias * which * exceeds 19 characters it will be truncated. * * @return the value of field 'Alias'. */ @XmlAttribute(name="alias", required=true) public String getAlias() { return m_alias; } /** * Returns the value of field 'instance'. The field 'instance' * has the following description: instance identifier. Only * valid instance identifier * values are a positive integer value or the keyword * "ifIndex" which * indicates that the ifIndex of the interface is to be * substituted for * the instance value for each interface the oid is retrieved * for. * * @return the value of field 'Instance'. */ @XmlAttribute(name="instance", required=true) public String getInstance() { return m_instance; } <|fim▁hole|> /** * Returns the value of field 'maxval'. The field 'maxval' has * the following description: Maximum Value. In order to * correctly manage counter * wraps, it is possible to add a maximum value for a * collection. For * example, a 32-bit counter would have a max value of * 4294967295. * * @return the value of field 'Maxval'. */ @XmlAttribute(name="maxval", required=false) public String getMaxval() { return m_maxval; } /** * Returns the value of field 'minval'. The field 'minval' has * the following description: Minimum Value. For completeness, * adding the ability * to use a minimum value. * * @return the value of field 'Minval'. */ @XmlAttribute(name="minval", required=false) public String getMinval() { return m_minval; } /** * Returns the value of field 'oid'. The field 'oid' has the * following description: object identifier * * @return the value of field 'Oid'. */ @XmlAttribute(name="oid", required=true) public String getOid() { return m_oid; } /** * Returns the value of field 'type'. The field 'type' has the * following description: SNMP data type SNMP supported types: * counter, gauge, * timeticks, integer, octetstring, string. The SNMP type is * mapped to * one of two RRD supported data types COUNTER or GAUGE, or * the * string.properties file. The mapping is as follows: SNMP * counter * -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring * -> * RRD GAUGE; SNMP string -> String properties file * * @return the value of field 'Type'. */ @XmlAttribute(name="type", required=true) public String getType() { return m_type; } /** * Overrides the java.lang.Object.hashCode method. * <p> * The following steps came from <b>Effective Java Programming * Language Guide</b> by Joshua Bloch, Chapter 3 * * @return a hash code value for the object. */ public int hashCode() { int result = 17; if (m_oid != null) { result = 37 * result + m_oid.hashCode(); } if (m_instance != null) { result = 37 * result + m_instance.hashCode(); } if (m_alias != null) { result = 37 * result + m_alias.hashCode(); } if (m_type != null) { result = 37 * result + m_type.hashCode(); } if (m_maxval != null) { result = 37 * result + m_maxval.hashCode(); } if (m_minval != null) { result = 37 * result + m_minval.hashCode(); } return result; } /** * Method isValid. * * @return true if this object is valid according to the schema */ @Deprecated public boolean isValid() { try { validate(); } catch (ValidationException vex) { return false; } return true; } /** * * * @param out * @throws MarshalException if object is * null or if any SAXException is thrown during marshaling * @throws ValidationException if this * object is an invalid instance according to the schema */ @Deprecated public void marshal(final java.io.Writer out) throws MarshalException, ValidationException { Marshaller.marshal(this, out); } /** * * * @param handler * @throws java.io.IOException if an IOException occurs during * marshaling * @throws ValidationException if this * object is an invalid instance according to the schema * @throws MarshalException if object is * null or if any SAXException is thrown during marshaling */ @Deprecated public void marshal(final org.xml.sax.ContentHandler handler) throws java.io.IOException, MarshalException, ValidationException { Marshaller.marshal(this, handler); } /** * Sets the value of field 'alias'. The field 'alias' has the * following description: a human readable name for the object * (such as * "ifOctetsIn"). NOTE: This value is used as the RRD file * name and * data source name. RRD only supports data source names up to * 19 chars * in length. If the SNMP data collector encounters an alias * which * exceeds 19 characters it will be truncated. * * @param alias the value of field 'alias'. */ public void setAlias(final String alias) { m_alias = alias.intern(); } /** * Sets the value of field 'instance'. The field 'instance' has * the following description: instance identifier. Only valid * instance identifier * values are a positive integer value or the keyword * "ifIndex" which * indicates that the ifIndex of the interface is to be * substituted for * the instance value for each interface the oid is retrieved * for. * * @param instance the value of field 'instance'. */ public void setInstance(final String instance) { m_instance = instance.intern(); } /** * Sets the value of field 'maxval'. The field 'maxval' has the * following description: Maximum Value. In order to correctly * manage counter * wraps, it is possible to add a maximum value for a * collection. For * example, a 32-bit counter would have a max value of * 4294967295. * * @param maxval the value of field 'maxval'. */ public void setMaxval(final String maxval) { m_maxval = maxval.intern(); } /** * Sets the value of field 'minval'. The field 'minval' has the * following description: Minimum Value. For completeness, * adding the ability * to use a minimum value. * * @param minval the value of field 'minval'. */ public void setMinval(final String minval) { m_minval = minval.intern(); } /** * Sets the value of field 'oid'. The field 'oid' has the * following description: object identifier * * @param oid the value of field 'oid'. */ public void setOid(final String oid) { m_oid = oid.intern(); } /** * Sets the value of field 'type'. The field 'type' has the * following description: SNMP data type SNMP supported types: * counter, gauge, * timeticks, integer, octetstring, string. The SNMP type is * mapped to * one of two RRD supported data types COUNTER or GAUGE, or * the * string.properties file. The mapping is as follows: SNMP * counter * -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring * -> * RRD GAUGE; SNMP string -> String properties file * * @param type the value of field 'type'. */ public void setType(final String type) { m_type = type.intern(); } /** * Method unmarshal. * * @param reader * @throws MarshalException if object is * null or if any SAXException is thrown during marshaling * @throws ValidationException if this * object is an invalid instance according to the schema * @return the unmarshaled * MibObj */ @Deprecated public static MibObj unmarshal(final Reader reader) throws MarshalException, ValidationException { return (MibObj)Unmarshaller.unmarshal(MibObj.class, reader); } /** * * * @throws ValidationException if this * object is an invalid instance according to the schema */ public void validate() throws ValidationException { Validator validator = new Validator(); validator.validate(this); } }<|fim▁end|>
<|file_name|>ucs_decode.py<|end_file_name|><|fim▁begin|>''' Created on Feb 4, 2016 Decoding tables taken from https://github.com/typiconman/Perl-Lingua-CU @author: mike kroutikov ''' from __future__ import print_function, unicode_literals import codecs def ucs_decode(input_, errors='strict'): return ''.join(decoding_table[x] for x in input_), len(input_) def ucs_encode(input_, errors): raise NotImplementedError('encoding to UCS is not implemented') ### Decoding Table decoding_table = ( '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\t', '\n', '\x0b', '\x0c', '\r', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', ' ', '!', '"', '\u0486', '\u0486\u0301', '\u0486\u0300', '\u0483', "'", '(', ')', '\ua673', '\u2de1\u0487', # combining VE ',', '-', '.', '/', '\u043e\u0301', '\u0301', '\u0300', '\u0486', '\u0486\u0301', '\u0486\u0300', '\u0311', # combining inverted breve '\u0483', # titlo '\u033e', # combining vertical tilde '\u0436\u0483', # zhe with titlo above ':', ';', '\u2def', # combining HA '\u2de9\u0487', # combining EN '\u2dec\u0487', # combining ER '\u2df1\u0487', # combining CHE '\u0300', '\u0430\u0300', # latin A maps to AZ with grave accent '\u0463\u0311', # latin B maps to Yat' with inverted breve '\u2ded\u0487', # combining ES '\u0434\u2ded\u0487', '\u0435\u0300', # latin E maps to e with grave accent '\u0472', # F maps to THETA '\u0433\u0483', # G maps to ge with TITLO '\u0461\u0301', # latin H maps to omega with acute accent '\u0406', '\u0456\u0300', '\ua656\u0486', # YA with psili '\u043b\u2de3', # el with cobining de '\u0476', # capital IZHITSA with kendema '\u047a\u0486', # capital WIDE ON with psili '\u047a', # just capital WIDE ON '\u0470', # capital PSI '\u047c', # capital omega with great apostrophe<|fim▁hole|> '\u0474', # capital IZHITSA '\u0460', # capital OMEGA '\u046e', # capital XI '\ua64b\u0300', # monograph uk with grave '\u0466', # capital SMALL YUS '[', '\u0483', # yet another titlo ']', '\u0311', # combining inverted breve '\u033e', # yet another yerik '`', '\u0430\u0301', # latin A maps to AZ with acute accent '\u2dea\u0487', # combining ON '\u2ded\u0487', # combining ES '\u2de3', # combining DE '\u0435\u0301', # latin E maps to e with acute accent '\u0473', # lowercase theta '\u2de2\u0487', # combining ge '\u044b\u0301', # ery with acute accent '\u0456', '\u0456\u0301', # i with acute accent '\ua657\u0486', # iotaed a with psili '\u043b\u0483', # el with titlo '\u0477', # izhitsa with izhe titlo '\u047b\u0486', # wide on with psili '\u047b', # wide on '\u0471', # lowercase psi '\u047d', # lowercase omega with great apostrophe '\u0440\u2ded\u0487', # lowercase er with combining es '\u0467\u0301', # lowercase small yus with acute accent '\u047f', # lowercase ot '\u1c82\u0443', # diagraph uk '\u0475', # lowercase izhitsa '\u0461', # lowercase omega '\u046f', # lowercase xi '\ua64b\u0301', # monograph uk with acute accent '\u0467', # lowercase small yus '\ua64b\u0311', # monograph uk with inverted breve '\u0467\u0486\u0300', # lowercase small yus with apostroph '\u0438\u0483', # the numeral eight '\u0301', # yet another acute accent '\x7f', '\u0475\u0301', # lowercase izhitsa with acute '\u0410\u0486\u0301', # uppercase A with psili and acute '\u201a', '\u0430\u0486\u0301', # lowercase A with psili and acute '\u201e', '\u046f\u0483', # the numberal sixty '\u0430\u0311', # lowercase a with inverted breve '\u0456\u0311', # lowercase i with inverted breve '\u2de5', # combining ze '\u0467\u0311', # lowercase small yus with inverted breve '\u0466\u0486', # upercase small yus with psili '\u0456\u0483', # the numeral ten '\u0460\u0486', # capital OMEGA with psili '\u041e\u0443\u0486\u0301', # diagraph uk with apostroph '\ua656\u0486\u0301', # uppercase Iotated A with apostroph '\u047a\u0486\u0301', # uppercase Round O with apostroph '\u0475\u2de2\u0487', # lowercase izhitsa with combining ge '\u2018', '\u2019', '\u201c', '\u201d', '\u2de4', # combining zhe '\u2013', '\u2014', '\ufffe', '\u0442\u0483', '\u0467\u0486', # lowercase small yus with psili '\u0475\u0311', # izhitsa with inverted breve '\u0461\u0486', # lowercase omega with psili '\u1c82\u0443\u0486\u0301', # diagraph uk with apostroph '\ua657\u0486\u0301', # lowercase iotaed a with apostroph '\u047b\u0486\u0301', # lowercase Round O with apostroph '\xa0', '\u041e\u0443\u0486', # Capital Diagraph Uk with psili '\u1c82\u0443\u0486', # lowercase of the above '\u0406\u0486\u0301', # Uppercase I with apostroph '\u0482', # cyrillic thousands sign '\u0410\u0486', # capital A with psili '\u0445\u0483', # lowercase kha with titlo '\u0447\u0483', # the numeral ninety '\u0463\u0300', # lowecase yat with grave accent '\u0441\u0483', # the numeral two hundred '\u0404', '\xab', '\xac', '\xad', '\u0440\u2de3', # lowercase er with dobro titlo '\u0406\u0486', '\ua67e', # kavyka '\ua657\u0486\u0300', '\u0406', '\u0456\u0308', '\u0430\u0486', '\u0443', # small letter u (why encoded at the micro sign?!) '\xb6', '\xb7', '\u0463\u0301', # lowercase yat with acute accent '\u0430\u0483', # the numeral one '\u0454', # wide E '\xbb', '\u0456\u0486\u0301', # lowercase i with apostroph '\u0405', '\u0455', '\u0456\u0486', # lowercase i with psili '\u0410', '\u0411', '\u0412', '\u0413', '\u0414', '\u0415', '\u0416', '\u0417', '\u0418', '\u0419', '\u041a', '\u041b', '\u041c', '\u041d', '\u041e', '\u041f', '\u0420', '\u0421', '\u0422', '\ua64a', '\u0424', '\u0425', '\u0426', '\u0427', '\u0428', '\u0429', '\u042a', '\u042b', '\u042c', '\u0462', # capital yat '\u042e', '\ua656', # capital Iotified A '\u0430', '\u0431', '\u0432', '\u0433', '\u0434', '\u0435', '\u0436', '\u0437', '\u0438', '\u0439', '\u043a', '\u043b', '\u043c', '\u043d', '\u043e', '\u043f', '\u0440', '\u0441', '\u0442', '\ua64b', # monograph Uk (why?!) '\u0444', '\u0445', '\u0446', '\u0447', '\u0448', '\u0449', '\u044a', '\u044b', '\u044c', '\u0463', # lowercase yat '\u044e', '\ua657', # iotaed a ) def _build_decoding_table(fname): '''unitily to build decoding_table from Perl's ucsequivs file. we base on cp1251 and overlay data from ucsequivs''' from encodings import cp1251 decode_table = list(cp1251.decoding_table) comments = [None] * 256 with codecs.open(fname, 'r', 'utf-8') as f: for line in f: line = line.strip() if not line or line == 'use utf8;' or line.startswith('#'): continue key, chars, comment = parse_perl_dictionary_entry(line) decode_table[key] = chars comments[key] = comment return decode_table, comments def parse_perl_dictionary_entry(line): key, value = line.split('=>') key = key.strip().strip("'") if key == '\\\\': key = '\\' key = key.encode('cp1251') assert len(key) == 1, key key = int(key[0]) value = value.strip() values = value.split('#', 1) value = values[0].strip() # removes trailing comment if len(values) == 2: comment = values[1].strip() else: comment = None value = value.rstrip(',') chars = [x.strip() for x in value.split('.')] assert min(x.startswith('chr(') and x.endswith(')') for x in chars) chars = [int(x[4:-1], 0) for x in chars] chars = ''.join(chr(x) for x in chars) return key, chars, comment if __name__ == '__main__': '''Code that generates "decoding_table" from Perl ucs encoding table. 1. Download Perl UCS encoding table from: https://raw.githubusercontent.com/typiconman/Perl-Lingua-CU/master/lib/Lingua/CU/Scripts/ucsequivs 2. Put it into current directory. 3. Run this code to generate Python array "decoding_table" ''' dt, cm = _build_decoding_table('ucsequivs') print('decoding_table = (') for x,c in zip(dt, cm): if c is not None: c = ' # ' + c else: c = '' if x == "'": # treat single quote separately to avoid syntax error (is there a better way? - MK) print('\t"%s",%s' % (x.encode('unicode-escape').decode(), c)) else: print("\t'%s',%s" % (x.encode('unicode-escape').decode(), c)) print(')')<|fim▁end|>
'\u0440\u0483', # lowercase re with titlo '\u0467\u0300', # lowercase small yus with grave '\u047e', # capital OT '\u041e\u0443', # diagraph capital UK
<|file_name|>jquery.multi-select.js<|end_file_name|><|fim▁begin|>/* * MultiSelect v0.9.8 * Copyright (c) 2012 Louis Cuny * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ !function ($) { "use strict"; /* MULTISELECT CLASS DEFINITION * ====================== */ var MultiSelect = function (element, options) { this.options = options; this.$element = $(element); this.$container = $('<div/>', { 'class': "ms-container" }); this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' }); this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' }); this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.scrollTo = 0; this.sanitizeRegexp = new RegExp("\\W+", 'gi'); this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')'; }; MultiSelect.prototype = { constructor: MultiSelect, init: function(){ var that = this, ms = this.$element; if (ms.next('.ms-container').length === 0){ ms.css({ position: 'absolute', left: '-9999px' }); ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect'); this.$container.attr('id', 'ms-'+ms.attr('id')); ms.find('option').each(function(){ that.generateLisFromOption(this); }); this.$selectionUl.find('.ms-optgroup-label').hide(); if (that.options.selectableHeader){ that.$selectableContainer.append(that.options.selectableHeader); } that.$selectableContainer.append(that.$selectableUl); if (that.options.selectableFooter){ that.$selectableContainer.append(that.options.selectableFooter); } if (that.options.selectionHeader){ that.$selectionContainer.append(that.options.selectionHeader); } that.$selectionContainer.append(that.$selectionUl); if (that.options.selectionFooter){ that.$selectionContainer.append(that.options.selectionFooter); } that.$container.append(that.$selectableContainer); that.$container.append(that.$selectionContainer); ms.after(that.$container); that.activeMouse(that.$selectableUl); that.activeKeyboard(that.$selectableUl);<|fim▁hole|> var action = that.options.dblClick ? 'dblclick' : 'click'; that.$selectableUl.on(action, '.ms-elem-selectable', function(){ that.select($(this).data('ms-value')); }); that.$selectionUl.on(action, '.ms-elem-selection', function(){ that.deselect($(this).data('ms-value')); }); that.activeMouse(that.$selectionUl); that.activeKeyboard(that.$selectionUl); ms.on('focus', function(){ that.$selectableUl.focus(); }) } var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get(); that.select(selectedValues, 'init'); if (typeof that.options.afterInit === 'function') { that.options.afterInit.call(this, this.$container); } }, 'generateLisFromOption' : function(option){ var that = this, ms = that.$element, attributes = "", $option = $(option); for (var cpt = 0; cpt < option.attributes.length; cpt++){ var attr = option.attributes[cpt]; if(attr.name !== 'value' && attr.name !== 'disabled'){ attributes += attr.name+'="'+attr.value+'" '; } } var selectableLi = $('<li '+attributes+'><span>'+$option.text()+'</span></li>'), selectedLi = selectableLi.clone(), value = $option.val(), elementId = that.sanitize(value, that.sanitizeRegexp); selectableLi .data('ms-value', value) .addClass('ms-elem-selectable') .attr('id', elementId+'-selectable'); selectedLi .data('ms-value', value) .addClass('ms-elem-selection') .attr('id', elementId+'-selection') .hide(); if ($option.prop('disabled') || ms.prop('disabled')){ selectedLi.addClass(that.options.disabledClass); selectableLi.addClass(that.options.disabledClass); } var $optgroup = $option.parent('optgroup'); if ($optgroup.length > 0){ var optgroupLabel = $optgroup.attr('label'), optgroupId = that.sanitize(optgroupLabel, that.sanitizeRegexp), $selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId), $selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId); if ($selectableOptgroup.length === 0){ var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>', optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>'; $selectableOptgroup = $(optgroupContainerTpl); $selectionOptgroup = $(optgroupContainerTpl); $selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId); $selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId); $selectableOptgroup.append($(optgroupTpl)); $selectionOptgroup.append($(optgroupTpl)); if (that.options.selectableOptgroup){ $selectableOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':not(:selected)').map(function(){ return $(this).val() }).get(); that.select(values); }); $selectionOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':selected').map(function(){ return $(this).val() }).get(); that.deselect(values); }); } that.$selectableUl.append($selectableOptgroup); that.$selectionUl.append($selectionOptgroup); } $selectableOptgroup.children().append(selectableLi); $selectionOptgroup.children().append(selectedLi); } else { that.$selectableUl.append(selectableLi); that.$selectionUl.append(selectedLi); } }, 'activeKeyboard' : function($list){ var that = this; $list.on('focus', function(){ $(this).addClass('ms-focus'); }) .on('blur', function(){ $(this).removeClass('ms-focus'); }) .on('keydown', function(e){ switch (e.which) { case 40: case 38: e.preventDefault(); e.stopPropagation(); that.moveHighlight($(this), (e.which === 38) ? -1 : 1); return; case 37: case 39: e.preventDefault(); e.stopPropagation(); that.switchList($list); return; case 9: if(that.$element.is('[tabindex]')){ e.preventDefault(); var tabindex = parseInt(that.$element.attr('tabindex'), 10); tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1; $('[tabindex="'+(tabindex)+'"]').focus(); return; }else{ if(e.shiftKey){ that.$element.trigger('focus'); } } } if($.inArray(e.which, that.options.keySelect) > -1){ e.preventDefault(); e.stopPropagation(); that.selectHighlighted($list); return; } }); }, 'moveHighlight': function($list, direction){ var $elems = $list.find(this.elemsSelector), $currElem = $elems.filter('.ms-hover'), $nextElem = null, elemHeight = $elems.first().outerHeight(), containerHeight = $list.height(), containerSelector = '#'+this.$container.prop('id'); // Deactive mouseenter event when move is active // It fixes a bug when mouse is over the list $elems.off('mouseenter'); $elems.removeClass('ms-hover'); if (direction === 1){ // DOWN $nextElem = $currElem.nextAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $nextOptgroupLi = $optgroupLi.next(':visible'); if ($nextOptgroupLi.length > 0){ $nextElem = $nextOptgroupLi.find(this.elemsSelector).first(); } else { $nextElem = $elems.first(); } } else { $nextElem = $elems.first(); } } } else if (direction === -1){ // UP $nextElem = $currElem.prevAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $prevOptgroupLi = $optgroupLi.prev(':visible'); if ($prevOptgroupLi.length > 0){ $nextElem = $prevOptgroupLi.find(this.elemsSelector).last(); } else { $nextElem = $elems.last(); } } else { $nextElem = $elems.last(); } } } if ($nextElem.length > 0){ $nextElem.addClass('ms-hover'); var scrollTo = $list.scrollTop() + $nextElem.position().top - containerHeight / 2 + elemHeight / 2; $list.scrollTop(scrollTo); } }, 'selectHighlighted' : function($list){ var $elems = $list.find(this.elemsSelector), $highlightedElem = $elems.filter('.ms-hover').first(); if ($highlightedElem.length > 0){ if ($list.parent().hasClass('ms-selectable')){ this.select($highlightedElem.data('ms-value')); } else { this.deselect($highlightedElem.data('ms-value')); } $elems.removeClass('ms-hover'); } }, 'switchList' : function($list){ $list.blur(); if ($list.parent().hasClass('ms-selectable')){ this.$selectionUl.focus(); } else { this.$selectableUl.focus(); } }, 'activeMouse' : function($list){ var that = this; var lastMovedDom = false; $list.on('mousemove', function(){ if (lastMovedDom === this) return; lastMovedDom = this; var elems = $list.find(that.elemsSelector); elems.on('mouseenter', function(){ elems.removeClass('ms-hover'); $(this).addClass('ms-hover'); }); }); }, 'refresh' : function() { this.destroy(); this.$element.multiSelect(this.options); }, 'destroy' : function(){ $("#ms-"+this.$element.attr("id")).remove(); this.$element.removeData('multiselect'); }, 'select' : function(value, method){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'), options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selectables.length > 0){ selectables.addClass('ms-selected').hide(); selections.addClass('ms-selected').show(); options.prop('selected', true); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){ $(this).find('.ms-optgroup-label').hide(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); } else { if (that.options.keepOrder){ var selectionLiLast = that.$selectionUl.find('.ms-selected'); if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) { selections.insertAfter(selectionLiLast.last()); } } } if (method !== 'init'){ ms.trigger('change'); if (typeof that.options.afterSelect === 'function') { that.options.afterSelect.call(this, value); } } } }, 'deselect' : function(value){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected'), options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selections.length > 0){ selectables.removeClass('ms-selected').show(); selections.removeClass('ms-selected').hide(); options.prop('selected', false); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.filter(':not(.ms-selected)').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length === 0){ $(this).find('.ms-optgroup-label').hide(); } }); } ms.trigger('change'); if (typeof that.options.afterDeselect === 'function') { that.options.afterDeselect.call(this, value); } } }, 'select_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option:not(":disabled")').prop('selected', true); this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide(); this.$selectionUl.find('.ms-optgroup-label').show(); this.$selectableUl.find('.ms-optgroup-label').hide(); this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show(); this.$selectionUl.focus(); ms.trigger('change'); if (typeof this.options.afterSelect === 'function') { var selectedValues = $.grep(ms.val(), function(item){ return $.inArray(item, values) < 0; }); this.options.afterSelect.call(this, selectedValues); } }, 'deselect_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option').prop('selected', false); this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show(); this.$selectionUl.find('.ms-optgroup-label').hide(); this.$selectableUl.find('.ms-optgroup-label').show(); this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide(); this.$selectableUl.focus(); ms.trigger('change'); if (typeof this.options.afterDeselect === 'function') { this.options.afterDeselect.call(this, values); } }, sanitize: function(value, reg){ return(value.replace(reg, '_')); } }; /* MULTISELECT PLUGIN DEFINITION * ======================= */ $.fn.multiSelect = function () { var option = arguments[0], args = arguments; return this.each(function () { var $this = $(this), data = $this.data('multiselect'), options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option); if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); } if (typeof option === 'string'){ data[option](args[1]); } else { data.init(); } }); }; $.fn.multiSelect.defaults = { keySelect: [32], selectableOptgroup: false, disabledClass : 'disabled', dblClick : false, keepOrder: false }; $.fn.multiSelect.Constructor = MultiSelect; }(window.jQuery);<|fim▁end|>
<|file_name|>update-list-item.3.x.js<|end_file_name|><|fim▁begin|>// To set up environmental variables, see http://twil.io/secure const accountSid = process.env.TWILIO_ACCOUNT_SID;<|fim▁hole|>const Twilio = require('twilio').Twilio; const client = new Twilio(accountSid, authToken); const service = client.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); service .syncLists('MyFirstList') .syncListItems(0) .update({ data: { number: '001', attack: '49', name: 'Bulbasaur', }, }) .then(response => { console.log(response); }) .catch(error => { console.log(error); });<|fim▁end|>
const authToken = process.env.TWILIO_AUTH_TOKEN;
<|file_name|>test_client.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2011 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # TODO: More tests import socket import unittest from StringIO import StringIO from urlparse import urlparse # TODO: mock http connection class with more control over headers from test.unit.proxy.test_server import fake_http_connect from swift.common import client as c class TestHttpHelpers(unittest.TestCase): def test_quote(self): value = 'standard string' self.assertEquals('standard%20string', c.quote(value)) value = u'\u0075nicode string' self.assertEquals('unicode%20string', c.quote(value)) def test_http_connection(self): url = 'http://www.test.com' _junk, conn = c.http_connection(url) self.assertTrue(isinstance(conn, c.HTTPConnection)) url = 'https://www.test.com' _junk, conn = c.http_connection(url) self.assertTrue(isinstance(conn, c.HTTPSConnection)) url = 'ftp://www.test.com' self.assertRaises(c.ClientException, c.http_connection, url) class TestClientException(unittest.TestCase): def test_is_exception(self): self.assertTrue(issubclass(c.ClientException, Exception)) def test_format(self): exc = c.ClientException('something failed') self.assertTrue('something failed' in str(exc)) test_kwargs = ( 'scheme', 'host', 'port', 'path', 'query', 'status', 'reason', 'device', ) for value in test_kwargs: kwargs = { 'http_%s' % value: value, } exc = c.ClientException('test', **kwargs) self.assertTrue(value in str(exc)) class TestJsonImport(unittest.TestCase): def tearDown(self): try: import json except ImportError: pass else: reload(json) try: import simplejson except ImportError: pass else: reload(simplejson) def test_any(self): self.assertTrue(hasattr(c, 'json_loads')) def test_no_simplejson(self): # break simplejson try: import simplejson except ImportError: # not installed, so we don't have to break it for these tests pass else: delattr(simplejson, 'loads') reload(c) try: from json import loads except ImportError: # this case is stested in _no_json pass else: self.assertEquals(loads, c.json_loads) def test_no_json(self): # first break simplejson try: import simplejson except ImportError: # not installed, so we don't have to break it for these tests pass else: delattr(simplejson, 'loads') # then break json try: import json except ImportError: # not installed, so we don't have to break it for these tests _orig_dumps = None else: # before we break json, grab a copy of the orig_dumps function _orig_dumps = json.dumps delattr(json, 'loads') reload(c) if _orig_dumps: # basic test of swift.common.client.json_loads using json.loads data = { 'string': 'value', 'int': 0, 'bool': True, 'none': None, } json_string = _orig_dumps(data) else: # even more basic test using a hand encoded json string data = ['value1', 'value2'] json_string = "['value1', 'value2']" self.assertEquals(data, c.json_loads(json_string)) self.assertRaises(AttributeError, c.json_loads, self) class MockHttpTest(unittest.TestCase): def setUp(self): def fake_http_connection(*args, **kwargs): _orig_http_connection = c.http_connection def wrapper(url, proxy=None): parsed, _conn = _orig_http_connection(url, proxy=proxy) conn = fake_http_connect(*args, **kwargs)() def request(*args, **kwargs): return conn.request = request conn.has_been_read = False _orig_read = conn.read def read(*args, **kwargs): conn.has_been_read = True return _orig_read(*args, **kwargs) conn.read = read return parsed, conn return wrapper self.fake_http_connection = fake_http_connection def tearDown(self): reload(c) # TODO: following tests are placeholders, need more tests, better coverage class TestGetAuth(MockHttpTest): def test_ok(self): c.http_connection = self.fake_http_connection(200) url, token = c.get_auth('http://www.test.com', 'asdf', 'asdf') self.assertEquals(url, None) self.assertEquals(token, None) class TestGetAccount(MockHttpTest): def test_no_content(self): c.http_connection = self.fake_http_connection(204) value = c.get_account('http://www.test.com', 'asdf')[1] self.assertEquals(value, []) class TestHeadAccount(MockHttpTest): def test_ok(self): c.http_connection = self.fake_http_connection(200) value = c.head_account('http://www.tests.com', 'asdf') # TODO: Hmm. This doesn't really test too much as it uses a fake that # always returns the same dict. I guess it "exercises" the code, so<|fim▁hole|> def test_server_error(self): c.http_connection = self.fake_http_connection(500) self.assertRaises(c.ClientException, c.head_account, 'http://www.tests.com', 'asdf') class TestGetContainer(MockHttpTest): def test_no_content(self): c.http_connection = self.fake_http_connection(204) value = c.get_container('http://www.test.com', 'asdf', 'asdf')[1] self.assertEquals(value, []) class TestHeadContainer(MockHttpTest): def test_server_error(self): c.http_connection = self.fake_http_connection(500) self.assertRaises(c.ClientException, c.head_container, 'http://www.test.com', 'asdf', 'asdf', ) class TestPutContainer(MockHttpTest): def test_ok(self): c.http_connection = self.fake_http_connection(200) value = c.put_container('http://www.test.com', 'asdf', 'asdf') self.assertEquals(value, None) class TestDeleteContainer(MockHttpTest): def test_ok(self): c.http_connection = self.fake_http_connection(200) value = c.delete_container('http://www.test.com', 'asdf', 'asdf') self.assertEquals(value, None) class TestGetObject(MockHttpTest): def test_server_error(self): c.http_connection = self.fake_http_connection(500) self.assertRaises(c.ClientException, c.get_object, 'http://www.test.com', 'asdf', 'asdf', 'asdf') class TestHeadObject(MockHttpTest): def test_server_error(self): c.http_connection = self.fake_http_connection(500) self.assertRaises(c.ClientException, c.head_object, 'http://www.test.com', 'asdf', 'asdf', 'asdf') class TestPutObject(MockHttpTest): def test_ok(self): c.http_connection = self.fake_http_connection(200) args = ('http://www.test.com', 'asdf', 'asdf', 'asdf', 'asdf') value = c.put_object(*args) self.assertTrue(isinstance(value, basestring)) def test_server_error(self): c.http_connection = self.fake_http_connection(500) args = ('http://www.test.com', 'asdf', 'asdf', 'asdf', 'asdf') self.assertRaises(c.ClientException, c.put_object, *args) class TestPostObject(MockHttpTest): def test_ok(self): c.http_connection = self.fake_http_connection(200) args = ('http://www.test.com', 'asdf', 'asdf', 'asdf', {}) value = c.post_object(*args) def test_server_error(self): c.http_connection = self.fake_http_connection(500) self.assertRaises(c.ClientException, c.post_object, 'http://www.test.com', 'asdf', 'asdf', 'asdf', {}) class TestDeleteObject(MockHttpTest): def test_ok(self): c.http_connection = self.fake_http_connection(200) value = c.delete_object('http://www.test.com', 'asdf', 'asdf', 'asdf') def test_server_error(self): c.http_connection = self.fake_http_connection(500) self.assertRaises(c.ClientException, c.delete_object, 'http://www.test.com', 'asdf', 'asdf', 'asdf') class TestConnection(MockHttpTest): def test_instance(self): conn = c.Connection('http://www.test.com', 'asdf', 'asdf') self.assertEquals(conn.retries, 5) def test_retry(self): c.http_connection = self.fake_http_connection(500) def quick_sleep(*args): pass c.sleep = quick_sleep conn = c.Connection('http://www.test.com', 'asdf', 'asdf') self.assertRaises(c.ClientException, conn.head_account) self.assertEquals(conn.attempts, conn.retries + 1) def test_resp_read_on_server_error(self): c.http_connection = self.fake_http_connection(500) conn = c.Connection('http://www.test.com', 'asdf', 'asdf', retries=0) def get_auth(*args, **kwargs): return 'http://www.new.com', 'new' conn.get_auth = get_auth self.url, self.token = conn.get_auth() method_signatures = ( (conn.head_account, []), (conn.get_account, []), (conn.head_container, ('asdf',)), (conn.get_container, ('asdf',)), (conn.put_container, ('asdf',)), (conn.delete_container, ('asdf',)), (conn.head_object, ('asdf', 'asdf')), (conn.get_object, ('asdf', 'asdf')), (conn.put_object, ('asdf', 'asdf', 'asdf')), (conn.post_object, ('asdf', 'asdf', {})), (conn.delete_object, ('asdf', 'asdf')), ) for method, args in method_signatures: self.assertRaises(c.ClientException, method, *args) try: self.assertTrue(conn.http_conn[1].has_been_read) except AssertionError: msg = '%s did not read resp on server error' % method.__name__ self.fail(msg) except Exception, e: raise e.__class__("%s - %s" % (method.__name__, e)) def test_reauth(self): c.http_connection = self.fake_http_connection(401) def get_auth(*args, **kwargs): return 'http://www.new.com', 'new' def swap_sleep(*args): self.swap_sleep_called = True c.get_auth = get_auth c.http_connection = self.fake_http_connection(200) c.sleep = swap_sleep self.swap_sleep_called = False conn = c.Connection('http://www.test.com', 'asdf', 'asdf', preauthurl='http://www.old.com', preauthtoken='old', ) self.assertEquals(conn.attempts, 0) self.assertEquals(conn.url, 'http://www.old.com') self.assertEquals(conn.token, 'old') value = conn.head_account() self.assertTrue(self.swap_sleep_called) self.assertEquals(conn.attempts, 2) self.assertEquals(conn.url, 'http://www.new.com') self.assertEquals(conn.token, 'new') def test_reset_stream(self): class LocalContents(object): def __init__(self, tell_value=0): self.already_read = False self.seeks = [] self.tell_value = tell_value def tell(self): return self.tell_value def seek(self, position): self.seeks.append(position) self.already_read = False def read(self, size=-1): if self.already_read: return '' else: self.already_read = True return 'abcdef' class LocalConnection(object): def putrequest(self, *args, **kwargs): return def putheader(self, *args, **kwargs): return def endheaders(self, *args, **kwargs): return def send(self, *args, **kwargs): raise socket.error('oops') def request(self, *args, **kwargs): return def getresponse(self, *args, **kwargs): self.status = 200 return self def getheader(self, *args, **kwargs): return '' def read(self, *args, **kwargs): return '' def local_http_connection(url, proxy=None): parsed = urlparse(url) return parsed, LocalConnection() orig_conn = c.http_connection try: c.http_connection = local_http_connection conn = c.Connection('http://www.example.com', 'asdf', 'asdf', retries=1, starting_backoff=.0001) contents = LocalContents() exc = None try: conn.put_object('c', 'o', contents) except socket.error, err: exc = err self.assertEquals(contents.seeks, [0]) self.assertEquals(str(exc), 'oops') contents = LocalContents(tell_value=123) exc = None try: conn.put_object('c', 'o', contents) except socket.error, err: exc = err self.assertEquals(contents.seeks, [123]) self.assertEquals(str(exc), 'oops') contents = LocalContents() contents.tell = None exc = None try: conn.put_object('c', 'o', contents) except c.ClientException, err: exc = err self.assertEquals(contents.seeks, []) self.assertEquals(str(exc), "put_object('c', 'o', ...) failure " "and no ability to reset contents for reupload.") finally: c.http_connection = orig_conn if __name__ == '__main__': unittest.main()<|fim▁end|>
# I'll leave it for now. self.assertEquals(type(value), dict)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import py4j class CapturedException(Exception): def __init__(self, desc, stackTrace): self.desc = desc self.stackTrace = stackTrace def __str__(self): return repr(self.desc) class AnalysisException(CapturedException): """ Failed to analyze a SQL query plan. """ class ParseException(CapturedException): """ Failed to parse a SQL command. """ class IllegalArgumentException(CapturedException): """ Passed an illegal or inappropriate argument. """ class StreamingQueryException(CapturedException): """ Exception that stopped a :class:`StreamingQuery`. """ class QueryExecutionException(CapturedException): """ Failed to execute a query. """ def capture_sql_exception(f): def deco(*a, **kw): try: return f(*a, **kw) except py4j.protocol.Py4JJavaError as e: s = e.java_exception.toString() stackTrace = '\n\t at '.join(map(lambda x: x.toString(), e.java_exception.getStackTrace())) if s.startswith('org.apache.spark.sql.AnalysisException: '): raise AnalysisException(s.split(': ', 1)[1], stackTrace) if s.startswith('org.apache.spark.sql.catalyst.analysis'): raise AnalysisException(s.split(': ', 1)[1], stackTrace) if s.startswith('org.apache.spark.sql.catalyst.parser.ParseException: '): raise ParseException(s.split(': ', 1)[1], stackTrace) if s.startswith('org.apache.spark.sql.streaming.StreamingQueryException: '): raise StreamingQueryException(s.split(': ', 1)[1], stackTrace) if s.startswith('org.apache.spark.sql.execution.QueryExecutionException: '): raise QueryExecutionException(s.split(': ', 1)[1], stackTrace) if s.startswith('java.lang.IllegalArgumentException: '): raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace) raise return deco def install_exception_handler(): """ Hook an exception handler into Py4j, which could capture some SQL exceptions in Java. When calling Java API, it will call `get_return_value` to parse the returned object. If any exception happened in JVM, the result will be Java exception object, it raise py4j.protocol.Py4JJavaError. We replace the original `get_return_value` with one that could capture the Java exception and throw a Python one (with the same error message). It's idempotent, could be called multiple times. """ original = py4j.protocol.get_return_value # The original `get_return_value` is not patched, it's idempotent. patched = capture_sql_exception(original) # only patch the one used in py4j.java_gateway (call Java API) py4j.java_gateway.get_return_value = patched def toJArray(gateway, jtype, arr): <|fim▁hole|> :param arr: python type list """ jarr = gateway.new_array(jtype, len(arr)) for i in range(0, len(arr)): jarr[i] = arr[i] return jarr<|fim▁end|>
""" Convert python list to java type array :param gateway: Py4j Gateway :param jtype: java type of element in array
<|file_name|>create_proposals.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This code example creates new proposals. To determine which proposals exist, run get_all_proposals.py. """ import uuid # Import appropriate modules from the client library. from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. proposal_service = client.GetService('ProposalService', version='v201811') network_service = client.GetService('NetworkService', version='v201811') # Create proposal objects. proposal = { 'name': 'Proposal #%s' % uuid.uuid4(), 'advertiser': { 'companyId': advertiser_id, 'type': 'ADVERTISER' }, 'primarySalesperson': { 'userId': primary_salesperson_id, 'split': '75000' }, 'secondarySalespeople': [{ 'userId': secondary_salesperson_id, 'split': '25000'<|fim▁hole|> }], 'primaryTraffickerId': primary_trafficker_id, 'probabilityOfClose': '100000', 'budget': { 'microAmount': '100000000', 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] }, 'billingCap': 'CAPPED_CUMULATIVE', 'billingSource': 'DFP_VOLUME' } # Add proposals. proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: print ('Proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID)<|fim▁end|>
<|file_name|>api_test.go<|end_file_name|><|fim▁begin|>package keyapi import ( "bytes" "crypto/tls" "crypto/x509" "errors" "io/ioutil" "log" "net" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/sipb/homeworld/platform/keysystem/keyserver/account" "github.com/sipb/homeworld/platform/keysystem/keyserver/authorities" "github.com/sipb/homeworld/platform/keysystem/keyserver/config" "github.com/sipb/homeworld/platform/keysystem/keyserver/verifier" "github.com/sipb/homeworld/platform/util/testkeyutil" "github.com/sipb/homeworld/platform/util/wraputil" ) func TestVerifyAccountIP_NoLimit(t *testing.T) { acnt := &account.Account{ LimitIP: nil, } request := httptest.NewRequest("GET", "/test", nil) request.RemoteAddr = "192.168.0.1:1234" err := verifyAccountIP(acnt, request) if err != nil { t.Error(err) } } func TestVerifyAccountIP_Valid(t *testing.T) { acnt := &account.Account{ LimitIP: net.IPv4(192, 168, 0, 3), } request := httptest.NewRequest("GET", "/test", nil) request.RemoteAddr = "192.168.0.3:1234" err := verifyAccountIP(acnt, request) if err != nil { t.Error(err) } } func TestVerifyAccountIP_Invalid(t *testing.T) { acnt := &account.Account{ LimitIP: net.IPv4(192, 168, 0, 3), } request := httptest.NewRequest("GET", "/test", nil) request.RemoteAddr = "172.16.0.1:1234" err := verifyAccountIP(acnt, request) if err == nil { t.Error("Expected error") } else if !strings.Contains(err.Error(), "wrong IP address") { t.Error("Wrong error.") } } func TestVerifyAccountIP_BadRequest(t *testing.T) { acnt := &account.Account{ LimitIP: net.IPv4(192, 168, 0, 3), } request := httptest.NewRequest("GET", "/test", nil) request.RemoteAddr = "invalid" err := verifyAccountIP(acnt, request) if err == nil { t.Error("Expected error") } else if !strings.Contains(err.Error(), "invalid request address") { t.Errorf("Wrong error: %s", err) } } func TestAttemptAuthentication_NoAuthentication(t *testing.T) { request := httptest.NewRequest("GET", "/test", nil) keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), } _, err = attemptAuthentication(&gctx, request)<|fim▁hole|> t.Error("Expected error") } else if !strings.Contains(err.Error(), "No authentication method") { t.Error("Wrong error.") } } func TestAttemptAuthentication_TokenAuth(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{ "test-user": {Principal: "test-user"}, }, } request := httptest.NewRequest("GET", "/test", nil) request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute)) acnt, err := attemptAuthentication(&gctx, request) if err != nil { t.Error(err) } else if acnt.Principal != "test-user" { t.Error("Wrong account.") } } func TestAttemptAuthentication_TokenAuth_Fail(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{ "test-user": {Principal: "test-user"}, }, } request := httptest.NewRequest("GET", "/test", nil) request.Header.Set(verifier.TokenHeader, "this-is-not-a-valid-token") _, err = attemptAuthentication(&gctx, request) if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "Unrecognized token") { t.Errorf("Wrong error: %s", err.Error()) } } func TestAttemptAuthentication_MissingAccount_Token(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{}, } request := httptest.NewRequest("GET", "/test", nil) request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute)) _, err = attemptAuthentication(&gctx, request) if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "Cannot find account") { t.Errorf("Wrong error: %s", err) } } func TestAttemptAuthentication_NoDirectAuth_Token(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{ "test-user": {Principal: "test-user", DisableDirectAuth: true}, }, } request := httptest.NewRequest("GET", "/test", nil) request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute)) _, err = attemptAuthentication(&gctx, request) if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "disabled direct authentication") { t.Errorf("Wrong error: %s", err) } } func TestAttemptAuthentication_InvalidIP_Token(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{ "test-user": {Principal: "test-user", LimitIP: net.IPv4(192, 168, 0, 16)}, }, } request := httptest.NewRequest("GET", "/test", nil) request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute)) request.RemoteAddr = "192.168.0.17:50000" _, err = attemptAuthentication(&gctx, request) if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "from wrong IP address") { t.Errorf("Wrong error: %s", err) } } const ( TLS_CLIENT_CSR = "-----BEGIN CERTIFICATE REQUEST-----\nMIIBVTCBvwIBADAWMRQwEgYDVQQDDAtjbGllbnQtdGVzdDCBnzANBgkqhkiG9w0B\nAQEFAAOBjQAwgYkCgYEAtKukT2LT/PJ/i1pbqfe4Vm9iN2yMFoiKj0em7FFOrAeU\n/5onq8fZEXhUruN+OhjMr+K1c2qy7noqbzD3Fz/vi2frB9DUFMA9rkj3teRIEXKB\nBDzb1cbDSTL0HxH47/tURxzxzGCVfTCc1xUY+dqMsd8SvowxuEptU4SO9H8CR2MC\nAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4GBALCOKX+QHmNLGrrSCWB8p2iMuS+aPOcW\nYI9c1VaaTSQ43HOjF1smvGIa1iicM2L5zTBOEG36kI+sKFDOF2cXclhQF1WfLcxC\nIi/JSV+W7hbS6zWvJOnmoi15hzvVa1MRk8HZH+TpiMxO5uqQdDiEkV1sJ50v0ZtR\nTMuSBjdmmJ1t\n-----END CERTIFICATE REQUEST-----" ) func prepCertAuth(t *testing.T, gctx *config.Context) *http.Request { certstr, err := gctx.AuthenticationAuthority.Sign(TLS_CLIENT_CSR, false, time.Minute, "test-user", []string{}) if err != nil { t.Fatal(err) } cert, err := wraputil.LoadX509CertFromPEM([]byte(certstr)) if err != nil { t.Fatal(err) } request := httptest.NewRequest("GET", "/test", nil) request.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{cert}}} return request } func TestAttemptAuthentication_CertAuth(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{ "test-user": {Principal: "test-user"}, }, } acnt, err := attemptAuthentication(&gctx, prepCertAuth(t, &gctx)) if err != nil { t.Error(err) } else if acnt.Principal != "test-user" { t.Error("Wrong account.") } } func TestAttemptAuthentication_MissingAccount_Cert(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{}, } _, err = attemptAuthentication(&gctx, prepCertAuth(t, &gctx)) if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "Cannot find account") { t.Errorf("Wrong error: %s", err) } } func TestAttemptAuthentication_NoDirectAuth_Cert(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{ "test-user": {Principal: "test-user", DisableDirectAuth: true}, }, } _, err = attemptAuthentication(&gctx, prepCertAuth(t, &gctx)) if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "disabled direct authentication") { t.Errorf("Wrong error: %s", err) } } func TestAttemptAuthentication_InvalidIP_Cert(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } gctx := config.Context{ TokenVerifier: verifier.NewTokenVerifier(), AuthenticationAuthority: authority.(*authorities.TLSAuthority), Accounts: map[string]*account.Account{ "test-user": {Principal: "test-user", LimitIP: net.IPv4(192, 168, 0, 16)}, }, } request := prepCertAuth(t, &gctx) request.RemoteAddr = "192.168.0.17:50000" _, err = attemptAuthentication(&gctx, request) if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "from wrong IP address") { t.Errorf("Wrong error: %s", err) } } func TestConfiguredKeyserver_GetClientCAs(t *testing.T) { keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, certdata) if err != nil { t.Fatal(err) } ks := &ConfiguredKeyserver{Context: &config.Context{AuthenticationAuthority: authority.(*authorities.TLSAuthority)}} subjects := ks.GetClientCAs().Subjects() cert, err := x509.ParseCertificate(ks.Context.AuthenticationAuthority.ToHTTPSCert().Certificate[0]) if err != nil { t.Fatal(err) } if len(subjects) != 1 { t.Error("Wrong number of subjects.") } else if !bytes.Equal(subjects[0], cert.RawSubject) { t.Error("Mismatched raw subject bytes.") } } func TestConfiguredKeyserver_GetServerCert(t *testing.T) { keydata, _, cdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil) authority, err := authorities.LoadTLSAuthority(keydata, cdata) if err != nil { t.Fatal(err) } ks := &ConfiguredKeyserver{ServerCert: authority.(*authorities.TLSAuthority).ToHTTPSCert()} if len(ks.GetServerCert().Certificate) != 1 { t.Fatal("Wrong number of certs") } certdata := ks.GetServerCert().Certificate[0] refdata, err := wraputil.LoadSinglePEMBlock(cdata, []string{"CERTIFICATE"}) if err != nil { t.Error(err) } else if !bytes.Equal(certdata, refdata) { t.Error("Cert mismatch") } } func TestConfiguredKeyserver_HandleStaticRequest(t *testing.T) { ks := &ConfiguredKeyserver{Context: &config.Context{StaticFiles: map[string]config.StaticFile{ "testa.txt": {Filename: "testa.txt", Filepath: "../config/testdir/testa.txt"}, }}} recorder := httptest.NewRecorder() err := ks.HandleStaticRequest(recorder, "testa.txt") if err != nil { t.Error(err) } result := recorder.Result() if result.Body == nil { t.Fatal("Nil body.") } response, err := ioutil.ReadAll(result.Body) if err != nil { t.Fatal(err) } ref, err := ioutil.ReadFile("../config/testdir/testa.txt") if err != nil { t.Fatal(err) } if !bytes.Equal(response, ref) { t.Error("Mismatched file data.") } } func TestConfiguredKeyserver_HandleStaticRequest_NonexistentEntry(t *testing.T) { ks := &ConfiguredKeyserver{Context: &config.Context{}} err := ks.HandleStaticRequest(nil, "testa.txt") if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "No such static file") { t.Error("Wrong error.") } } func TestConfiguredKeyserver_HandleStaticRequest_NonexistentFile(t *testing.T) { ks := &ConfiguredKeyserver{Context: &config.Context{StaticFiles: map[string]config.StaticFile{ "testa.txt": {Filename: "testa.txt", Filepath: "../config/testdir/nonexistent.txt"}, }}} err := ks.HandleStaticRequest(nil, "testa.txt") if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "no such file") { t.Errorf("Wrong error: %s", err) } } func TestConfiguredKeyserver_HandlePubRequest_NoAuthority(t *testing.T) { ks := &ConfiguredKeyserver{Context: &config.Context{}} err := ks.HandlePubRequest(nil, "grant") if err == nil { t.Error("Expected error.") } else if !strings.Contains(err.Error(), "No such authority") { t.Errorf("Wrong error: %s", err) } } type BrokenConnection struct { } func (BrokenConnection) Read(p []byte) (n int, err error) { return 0, errors.New("connection cut by a squirrel with scissors") } func TestConfiguredKeyserver_HandleAPIRequest_ConnError(t *testing.T) { logrecord := bytes.NewBuffer(nil) logger := log.New(logrecord, "", 0) ks := &ConfiguredKeyserver{ Context: &config.Context{ TokenVerifier: verifier.NewTokenVerifier(), }, Logger: logger, } recorder := httptest.NewRecorder() request := httptest.NewRequest("GET", "/api", BrokenConnection{}) request.Header.Set(verifier.TokenHeader, ks.Context.TokenVerifier.Registry.GrantToken("test-account", time.Minute)) err := ks.HandleAPIRequest(recorder, request) if err == nil { t.Error("Expected error") } else if !strings.Contains(err.Error(), "connection cut by a squirrel with scissors") { t.Errorf("Wrong error: %s", err) } if logrecord.String() != "" { t.Error("Unexpected logging.") } } func TestConfiguredKeyserver_HandleAPIRequest_Unauthed(t *testing.T) { logrecord := bytes.NewBuffer(nil) logger := log.New(logrecord, "", 0) ks := &ConfiguredKeyserver{ Context: &config.Context{ TokenVerifier: verifier.NewTokenVerifier(), }, Logger: logger, } recorder := httptest.NewRecorder() request := httptest.NewRequest("GET", "/api", nil) err := ks.HandleAPIRequest(recorder, request) if err == nil { t.Error("Expected error") } else if !strings.Contains(err.Error(), "No authentication method found in request") { t.Errorf("Wrong error: %s", err) } if logrecord.String() != "" { t.Error("Unexpected logging.") } } func TestConfiguredKeyserver_HandleAPIRequest_NoSuchGrant(t *testing.T) { logrecord := bytes.NewBuffer(nil) logger := log.New(logrecord, "", 0) ks := &ConfiguredKeyserver{ Context: &config.Context{ TokenVerifier: verifier.NewTokenVerifier(), Accounts: map[string]*account.Account{ "test-account": { Principal: "test-account", }, }, }, Logger: logger, } request_data := []byte("[{\"api\": \"test-api\", \"body\": \"\"}]") recorder := httptest.NewRecorder() request := httptest.NewRequest("GET", "/api", bytes.NewReader(request_data)) request.Header.Set(verifier.TokenHeader, ks.Context.TokenVerifier.Registry.GrantToken("test-account", time.Minute)) err := ks.HandleAPIRequest(recorder, request) if err == nil { t.Error("Expected error") } else if !strings.Contains(err.Error(), "could not find API request") { t.Errorf("Wrong error: %s", err) } if logrecord.String() != "" { t.Error("Unexpected logging.") } }<|fim▁end|>
if err == nil {
<|file_name|>WB_MutableCoordinateMath3D.java<|end_file_name|><|fim▁begin|>/* * HE_Mesh Frederik Vanhoutte - www.wblut.com * * https://github.com/wblut/HE_Mesh * A Processing/Java library for for creating and manipulating polygonal meshes. * * Public Domain: http://creativecommons.org/publicdomain/zero/1.0/ * I , Frederik Vanhoutte, have waived all copyright and related or neighboring * rights. * * This work is published from Belgium. (http://creativecommons.org/publicdomain/zero/1.0/) * */ package wblut.geom; /** * Interface for implementing mutable mathematical operations on 3D coordinates. * * All of the operators defined in the interface change the calling object. All * operators use the label "Self", such as "addSelf" to indicate this. * * @author Frederik Vanhoutte * */ public interface WB_MutableCoordinateMath3D extends WB_CoordinateMath3D { /** * Add coordinate values. * * @param x * @return this */ public WB_Coord addSelf(final double... x); /** * Add coordinate values. * * @param p * @return this */ public WB_Coord addSelf(final WB_Coord p); /** * Subtract coordinate values. * * @param x * @return this */ public WB_Coord subSelf(final double... x); /** * Subtract coordinate values. * * @param p * @return this */ public WB_Coord subSelf(final WB_Coord p); /** * Multiply by factor. * * @param f * @return this */ public WB_Coord mulSelf(final double f); /** * Divide by factor. * * @param f * @return this */ public WB_Coord divSelf(final double f); /** * Add multiple of coordinate values. * * @param f * multiplier * @param x * @return this */ public WB_Coord addMulSelf(final double f, final double... x); /** * Add multiple of coordinate values. * * @param f * @param p * @return this */ public WB_Coord addMulSelf(final double f, final WB_Coord p); /**<|fim▁hole|> * Multiply this coordinate by factor f and add other coordinate values * multiplied by g. * * @param f * @param g * @param x * @return this */ public WB_Coord mulAddMulSelf(final double f, final double g, final double... x); /** * Multiply this coordinate by factor f and add other coordinate values * multiplied by g. * * @param f * @param g * @param p * @return this */ public WB_Coord mulAddMulSelf(final double f, final double g, final WB_Coord p); /** * * * @param p * @return this */ public WB_Coord crossSelf(final WB_Coord p); /** * Normalize this vector. Return the length before normalization. If this * vector is degenerate 0 is returned and the vector remains the zero * vector. * * @return this */ public double normalizeSelf(); /** * If vector is larger than given value, trim vector. * * @param d * @return this */ public WB_Coord trimSelf(final double d); }<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>"""simpleplantms URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """<|fim▁hole|>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ #home page url(r'^$', 'home.views.index'), #this will send requests to the sites app example /simpleplantms/sites/ url(r'^sites/', include('sites.urls')), #this will send requests to the departments app example /simpleplantms/departments/ url(r'^departments/', include('departments.urls')), #this will send requests to the departments app example /simpleplantms/equipment/ url(r'^equipment/', include('equipment.urls')), #this will send requests to the auth app example /simpleplantms/accounts/ url(r'^accounts/', include('accounts.urls')), #This will send requests for profile info to the profiles app /simpleplantms/profiles/ url(r'^profiles/', include('profiles.urls')), #This will route requests about maintenance tasks to the app eg /simpleplantms/maintjobs/ url(r'^maintjobs/', include('mainttask.urls')), #This will route requests about maintenance tasks to the app eg /simpleplantms/maintenance/ url(r'^maintenance/', include('maintenance.urls')), url(r'^jet/', include('jet.urls','jet')), url(r'^jet/dashboard/', include('jet.dashboard.urls','jet-dashboard')), url(r'^admin/', include(admin.site.urls)), ]<|fim▁end|>
<|file_name|>friendly-unit.js<|end_file_name|><|fim▁begin|>ig.module(<|fim▁hole|>).defines(function () { FriendlyUnit = Unit.extend({ // Nothing yet! }); });<|fim▁end|>
'game.entities.abstract.friendly-unit' ).requires( 'game.entities.abstract.unit'
<|file_name|>NewMovie.js<|end_file_name|><|fim▁begin|>module.exports = function() { 'use strict'; this.title = element(by.model('movie.title')); this.releaseYear = element(by.model('movie.releaseYear')); this.description = element(by.css('div[contenteditable=true]')); this.save = element(by.css('.btn-primary')); this.open = function() { browser.get('/movies/new'); }; this.addMovie = function(title, description, releaseYear) { this.open(); this.title.clear(); this.title.sendKeys(title); if (releaseYear !== undefined) {<|fim▁hole|> } this.description.clear(); this.description.sendKeys(description); this.save.click(); }; };<|fim▁end|>
this.releaseYear.clear(); this.releaseYear.sendKeys(releaseYear);
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import hr_payroll_payslips_by_employees import hr_payroll_contribution_register_report <|fim▁hole|><|fim▁end|>
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: