code stringlengths 1 18.2k |
|---|
def uninstall(args, env, console, ciprcfg): """ Remove a package """ for name in args: package_dir = path.join(env.package_dir, name) if path.exists(package_dir): console.quiet('Removing %s...' % name) if path.islink(package_dir): os.remove(package_dir) else: shutil.rmtree(package_dir) ciprcfg.remove_package(name) |
def install(args, console, env, ciprcfg, opts): """ Install a package from github and make it available for use. """ if len(args) == 0: # Is this a cipr project? if ciprcfg.exists: # Install all the packages for this project console.quiet('Installing current project packages...') for name, source in ciprcfg.packages.it... |
path.exists(package_json): # Looks like a cipr package, copy directly shutil.move(tmpdir, package_dir) else: # Not a cipr package, sandbox in sub-directory shutil.move(tmpdir, path.join(package_dir, name)) console.quiet('`%s` installed from git repo to `%s`' % (name, package_dir)) elif path.exists(package): # Local os.... |
def packages(ciprcfg, env, opts, console): """ List installed packages for this project """ for name, source in ciprcfg.packages.items(): console.normal('- %s' % name) if opts.long_details: console.normal(' - directory: %s' % path.join(env.package_dir, name)) console.normal(' - source: %s' % source) |
def run(env): """ Run current project in the Corona Simulator """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) # `Corona Terminal` doesn't support spaces in filenames so we cd in and use '.'. cmd = AND( clom.cd(path.dirname(env.project_directory)), clom[CORONA_SIMULATOR_P... |
def build(env, ciprcfg, console): """ Build the current project for distribution """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) build_settings = path.join(env.project_directory, 'build.settings') with open(build_settings, 'r') as f: data = f.read() m = _build_re.search(... |
= AND(clom.cd(env.build_dir), clom[CORONA_SIMULATOR_PATH](env.build_dir)) console.normal('Be sure to output your app to %s' % env.dist_dir) try: cmd.shell.execute() except KeyboardInterrupt: pass |
def packageipa(env, console): """ Package the built app as an ipa for distribution in iOS App Store """ ipa_path, app_path = _get_ipa(env) output_dir = path.dirname(ipa_path) if path.exists(ipa_path): console.quiet('Removing %s' % ipa_path) os.remove(ipa_path) zf = zipfile.ZipFile(ipa_path, mode='w') payload_dir = 'Pay... |
def expanddotpaths(env, console): """ Move files with dots in them to sub-directories """ for filepath in os.listdir(path.join(env.dir)): filename, ext = path.splitext(filepath) if ext == '.lua' and '.' in filename: paths, newfilename = filename.rsplit('.', 1) newpath = paths.replace('.', '/') newfilename = path.join(n... |
def check_file_existence(path): """ :return: FileType :rtype: int :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError: """ pathvalidate.validate_file_path(path) if not os.path.lexists(path): raise FileNotFoundError(path) if os.path.isfile(path): logger.debug("file found: " + path) return FileT... |
def parsePermission3Char(permission): """ 'rwx' 形式のアクセス権限文字列 permission を8進数形式に変換する :return: :rtype: int """ if len(permission) != 3: raise ValueError(permission) permission_int = 0 if permission[0] == "r": permission_int += 4 if permission[1] == "w": permission_int += 2 if permission[2] == "x": permission_int += 1 ret... |
def parseLsPermissionText(permission_text): """ parse "ls -l" style permission text: e.g. -rw-r--r-- """ from six.moves import range match = re.search("[-drwx]+", permission_text) if match is None: raise ValueError( "invalid permission character: " + permission_text) if len(permission_text) != 10: raise ValueError( "in... |
def chmod(cls, path, permission_text): """ :param str permission_text: "ls -l" style permission string. e.g. -rw-r--r-- """ try: check_file_existence(path) except FileNotFoundError: _, e, _ = sys.exc_info() # for python 2.5 compatibility logger.debug(e) return False logger.debug("chmod %s %s" % (path, permission_text))... |
def jpl_horizons_ephemeris( log, objectId, mjd, obscode=500, verbose=False): """Given a known solar-system object ID (human-readable name, MPC number or MPC packed format) and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC... |
.. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId=1, mjd=57916., obscode='T05' ) or to generate an ephemeris for multiple epochs: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId="ceres... |
"sun_obs_target_angle", "apparent_motion_relative_to_sun", "sun_target_obs_angle", "ra_3sig_error", "dec_3sig_error", "true_anomaly_angle", "phase_angle", "phase_angle_bisector_long", "phase_angle_bisector_lat"] if verbose == True: order = ["requestId", "objectId", "mjd", "ra_deg", "dec_deg", "ra_3sig_error", "dec_3sig... |
as e: pass theseparams = copy.deepcopy(params) theseparams["COMMAND"] = '"' + objectId + '"' paramList.append(theseparams) # TEST THE URL # try: # import requests # response = requests.get( # url="https://ssd.jpl.nasa.gov/horizons_batch.cgi", # params=theseparams, # ) # content = response.content # status_code = respon... |
Request failed') sys.exit(0) objectDict = {} for k in keys: v = None objectDict[k] = v objectDict["objectId"] = requestId + " - NOT FOUND" objectDict["requestId"] = requestId objectDict["mjd"] = None orderDict = collections.OrderedDict({}) for i in order: orderDict[i] = objectDict[i] resultList.append(orderDict) contin... |
``jpl_horizons_ephemeris`` function') return resultList |
def status(self, key, value): """Update the status of a build""" value = value.lower() if value not in valid_statuses: raise ValueError("Build Status must have a value from:\n{}".format(", ".join(valid_statuses))) self.obj['status'][key] = value self.changes.append("Updating build:{}.status.{}={}" .format(self.obj['nam... |
def state(self, state): """Update the status of a build""" state = state.lower() if state not in valid_states: raise ValueError("Build state must have a value from:\n{}".format(", ".join(valid_state))) self.obj['state'] = state self.changes.append("Updating build:{}.state={}" .format(self.obj['name'], state)) return se... |
def change(self, key, value): """Update any other attribute on the build object""" self.obj[key] = value self.changes.append("Updating build:{}.{}={}" .format(self.obj['name'], key, value)) return self |
def release(self, lane, status, target=None, meta=None, svcs=None): """Set release information on a build""" if target not in (None, 'current', 'future'): raise ValueError("\nError: Target must be None, 'current', or 'future'\n") svcs, meta, lane = self._prep_for_release(lane, svcs=svcs, meta=meta) when = time.time() #... |
curver: prev = [curver] + prev while len(prev) > 5: # magic values FTW prev.pop() # only keep history of 5 previous rel_data['previous'] = prev self.rcs.patch('service', svc, { "release": rel_data, "statuses": {status: when}, "status": status }) |
def promote(self, lane, svcs=None, meta=None): """promote a build so it is ready for an upper lane""" svcs, meta, lane = self._prep_for_release(lane, svcs=svcs, meta=meta) # iterate and mark as future release for svc in svcs: self.changes.append("Promoting: {}.release.future={}".format(svc, self.name)) self.rcs.patch('... |
def add_info(self, data): """add info to a build""" for key in data: # verboten if key in ('status','state','name','id','application','services','release'): raise ValueError("Sorry, cannot set build info with key of {}".format(key)) self.obj[key] = data[key] self.changes.append("Adding build info") return self |
def validate_field(self, value): ''' Method that must validate the value It must return None if the value is valid and a error msg otherelse. Ex: If expected input must be int, validate should a return a msg like "The filed must be a integer value" ''' if self.choices: value = self.normalize_field(value) if value in se... |
def normalize_field(self, value): """ Method that must transform the value from string Ex: if the expected type is int, it should return int(self._attr) """ if self.default is not None: if value is None or value == '': value = self.default return value |
def localize_field(self, value): """ Method that must transform the value from object to localized string """ if self.default is not None: if value is None or value == '': value = self.default return value or '' |
def journal_composition(collection, issn, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs":... |
} } } query_result = tc.search('article', json.dumps(body), query_parameters) computed = _compute_journal_composition(query_result) return query_result if raw else computed |
def collection_composition(collection, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12... |
} } } query_result = tc.search('article', json.dumps(body), query_parameters) computed = _compute_collection_composition(query_result) return query_result if raw else computed |
def journals_status(collection, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "i... |
def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]: """ input: ------ E: 1-D vector of energy bins [eV] E0: characteristic energy (scalar or vector) [eV] Q0: flux coefficient (scalar or vector) (to yield overall flux Q) output: ------- Phi: differential number flux Q: total flux T... |
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray, Bhf: np.ndarray, bh: float, verbose: int = 0): """ strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0 """ Bh = np.empty_like(E0) for iE0 in np.arange(E0.size): Bh[iE0] = Bhf[iE0]*diffnumflux[isimE0[iE0],... |
def handler(self, path='/app', mode='debug'): """ Handler that executes the application build based on its platform (using the ``project`` package). param: path(str): the project source code path, default is '/app'. param: target(str): the platform target, android-23 is the default for android platform if no value is p... |
def handler(self, path='/app'): """ Handler that prints the apk file(s) path that can be exported from the container (using the ``project`` package). :param path(str): the project source code path, default is '/app'. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR (separated by a comma). """ ... |
def handler(self, path='/app', ctx='all'): """ Handler that prints the project build log into the STDOUT (using the ``project`` package). :param path(str): the project source code path, default is '/app'. :param ctx(str): build log context file to be used, available options: validate, prepare, build or all. Returns: Do... |
def diffuse(self, *args): """ this is a dispatcher of diffuse implementation. Depending of the arguments used. """ mode = diffusingModeEnum.unknown if (isinstance(args[0], str) and (len(args) == 3)): # reveived diffuse(str, any, any) mode = diffusingModeEnum.element elif (hasattr(args[0], "__len__") and (len(args) == 2... |
def json_response(data, status=200): """Return a JsonResponse. Make sure you have django installed first.""" from django.http import JsonResponse return JsonResponse(data=data, status=status, safe=isinstance(data, dict)) |
def error_response(message, status=400, code=None): """"Return error message(in dict).""" from django.http import JsonResponse data = {'message': message} if code: data['code'] = code LOG.error("Error response, status code is : {} | {}".format(status, data)) return JsonResponse(data=data, status=status) |
def send_email_template(slug, base_url=None, context=None, user=None, to=None, cc=None, bcc=None, attachments=None, headers=None, connection=None, fail_silently=False): """ Shortcut to send an email template. """ email_template = EmailTemplate.objects.get_for_slug(slug) email = email_template.get_email_message( base_ur... |
def parse_assign(string): """Parse an assignment line: >>> parse_assign(" scenario8.Actuator_MagazinVacuumOn = TRUE") ("scenario8.Actuator_MagazinVacuumOn", "TRUE") """ try: a, b = string.split(" = ") return a.strip(), b.strip() except: print("Error with assignment: %s" % string, file=sys.stderr) return None, None |
def from_file(filename): """Read in filename and creates a trace object. :param filename: path to nu(x|s)mv output file :type filename: str :return: """ trace = Trace() reached = False with open(filename) as fp: for line in fp.readlines(): if not reached and line.strip() == "Trace Type: Counterexample": reached = True ... |
def run(self): """ run method """ if self.pre_message is None: try: input() # pre message of None causes the input to be silent except EOFError: pass else: try: input(self.pre_message) except EOFError: pass if self.post_message: print(self.post_message) self.exit_time = time.time() |
def kwargs_helper(kwargs): """This function preprocesses the kwargs dictionary to sanitize it.""" args = [] for param, value in kwargs.items(): param = kw_subst.get(param, param) args.append((param, value)) return args |
def GetDate(text=None, selected=None, **kwargs): """Prompt the user for a date. This will raise a Zenity Calendar Dialog for the user to pick a date. It will return a datetime.date object with the date or None if the user hit cancel. text - Text to be displayed in the calendar dialog. selected - A datetime.date object ... |
def GetFilename(multiple=False, sep='|', **kwargs): """Prompt the user for a filename. This will raise a Zenity File Selection Dialog. It will return a list with the selected files or None if the user hit cancel. multiple - True to allow the user to select multiple files. sep - Token to use as the path separator when p... |
def GetDirectory(multiple=False, selected=None, sep=None, **kwargs): """Prompt the user for a directory. This will raise a Zenity Directory Selection Dialog. It will return a list with the selected directories or None if the user hit cancel. multiple - True to allow the user to select multiple directories. selected - P... |
def GetSavename(default=None, **kwargs): """Prompt the user for a filename to save as. This will raise a Zenity Save As Dialog. It will return the name to save a file as or None if the user hit cancel. default - The default name that should appear in the save as dialog. kwargs - Optional command line parameters for Zen... |
def Notification(text=None, window_icon=None, **kwargs): """Put an icon in the notification area. This will put an icon in the notification area and return when the user clicks on it. text - The tooltip that will show when the user hovers over it. window_icon - The stock icon ("question", "info", "warning", "error") or... |
def List(column_names, title=None, boolstyle=None, editable=False, select_col=None, sep='|', data=[], **kwargs): """Present a list of items to select. This will raise a Zenity List Dialog populated with the colomns and rows specified and return either the cell or row that was selected or None if the user hit cancel. co... |
Zenity's return. Cells should not contain this token. data - A list or tuple of tuples that contain the cells in the row. The size of the row's tuple must be equal to the number of columns. kwargs - Optional command line parameters for Zenity such as height, width, etc.""" args = [] for column in column_names: args.app... |
def ErrorMessage(text, **kwargs): """Show an error message dialog to the user. This will raise a Zenity Error Dialog with a description of the error. text - A description of the error. kwargs - Optional command line parameters for Zenity such as height, width, etc.""" args = ['--text=%s' % text] for generic_args in kwa... |
def Progress(text='', percentage=0, auto_close=False, pulsate=False, **kwargs): """Show a progress dialog to the user. This will raise a Zenity Progress Dialog. It returns a callback that accepts two arguments. The first is a numeric value of the percent complete. The second is a message about the progress. NOTE: This ... |
height, width, etc.""" args = [] if text: args.append('--text=%s' % text) if percentage: args.append('--percentage=%s' % percentage) if auto_close: args.append('--auto-close=%s' % auto_close) if pulsate: args.append('--pulsate=%s' % pulsate) for generic_args in kwargs_helper(kwargs): args.append('--%s=%s' % generic_arg... |
def GetText(text='', entry_text='', password=False, **kwargs): """Get some text from the user. This will raise a Zenity Text Entry Dialog. It returns the text the user entered or None if the user hit cancel. text - A description of the text to enter. entry_text - The initial value of the text entry box. password - True... |
def TextInfo(filename=None, editable=False, **kwargs): """Show the text of a file to the user. This will raise a Zenity Text Information Dialog presenting the user with the contents of a file. It returns the contents of the text box. filename - The path to the file to show. editable - True if the text should be editabl... |
def get_backend_name(self, location): """ Return the name of the version control backend if found at given location, e.g. vcs.get_backend_name('/path/to/vcs/checkout') """ for vc_type in self._registry.values(): path = os.path.join(location, vc_type.dirname) if os.path.exists(path): return vc_type.name return None |
def check_destination(self, dest, url, rev_options, rev_display): """ Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise. """ checkout = True prompt = False if os.path.exists(dest): checkout = False if os.path.exists(os.path.join(des... |
%s repository %s' % (self.name, url)) response = ask('What to do? %s' % prompt[0], prompt[1]) if response == 's': logger.notify('Switching %s %s to %s%s' % (self.repo_name, display_path(dest), url, rev_display)) self.switch(dest, url, rev_options) elif response == 'i': # do nothing pass elif response == 'w': logger.war... |
def parse(file_contents, file_name): """ This takes a list of filenames and their paths of expected yaml files and tried to parse them, erroring if there are any parsing issues. Args: file_contents (str): Contents of a yml file Raises: yaml.parser.ParserError: Raises an error if the file contents cannot be parsed and i... |
def get_or_create(cls, **kwargs): ''' If a record matching the instance already exists in the database, then return it, otherwise create a new record. ''' q = cls._get_instance(**kwargs) if q: return q q = cls(**kwargs) _action_and_commit(q, session.add) return q |
def update(cls, **kwargs): ''' If a record matching the instance id already exists in the database, update it. If a record matching the instance id does not already exist, create a new record. ''' q = cls._get_instance(**{'id': kwargs['id']}) if q: for k, v in kwargs.items(): setattr(q, k, v) _action_and_commit(q, sess... |
def delete(cls, **kwargs): ''' If a record matching the instance id exists in the database, delete it. ''' q = cls._get_instance(**kwargs) if q: _action_and_commit(q, session.delete) |
def _get_instance(self, **kwargs): '''Return the first existing instance of the response record. ''' return session.query(self.response_class).filter_by(**kwargs).first() |
def get_or_create_from_legacy_response(self, response, **kwargs): ''' If a record matching the instance already does not already exist in the database, then create a new record. ''' response_cls = self.response_class(**kwargs).get_or_create(**kwargs) if not getattr(response_cls, self.column): setattr(response_cls, self... |
def update(self, response, **kwargs): ''' If a record matching the instance already exists in the database, update it, else create a new record. ''' response_cls = self._get_instance(**kwargs) if response_cls: setattr(response_cls, self.column, self.accessor(response)) _action_and_commit(response_cls, session.add) else... |
def delete(self, response, **kwargs): ''' If a record matching the instance id exists in the database, delete it. ''' response_cls = self._get_instance(**kwargs) if response_cls: _action_and_commit(response_cls, session.delete) |
def get_or_create_from_legacy_response(self, response, **kwargs): ''' If a record matching the instance already does not already exist in the database, then create a new record. ''' response_cls = self.response_class(**kwargs).get_or_create(**kwargs) if not getattr(response_cls, self.column): setattr(response_cls, self... |
def update(self, response, **kwargs): ''' If a record matching the instance already exists in the database, update both the column and venue column attributes, else create a new record. ''' response_cls = super( LocationResponseClassLegacyAccessor, self)._get_instance(**kwargs) if response_cls: setattr(response_cls, se... |
def common_update_sys(self): """ update system package """ try: sudo('apt-get update -y --fix-missing') except Exception as e: print(e) print(green('System package is up to date.')) print() |
def common_install_mysql(self): """ Install mysql """ sudo("debconf-set-selections <<< 'mysql-server mysql-server/root_password password {0}'".format(self.mysql_password)) sudo("debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password {0}'".format(self.mysql_password)) sudo('apt-get install my... |
def update_source_list(self): """ update ubuntu 16 source list :return: """ with cd('/etc/apt'): sudo('mv sources.list sources.list.bak') put(StringIO(bigdata_conf.ubuntu_source_list_16), 'sources.list', use_sudo=True) sudo('apt-get update -y --fix-missing') |
def common_install_nginx(self): """ Install nginx """ run('echo "deb http://ppa.launchpad.net/nginx/stable/ubuntu $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/nginx-stable.list') sudo('apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C300EE8C') sudo('apt-get update -y') sudo('apt-get install ngin... |
def common_config_nginx_ssl(self): """ Convert nginx server from http to https """ if prompt(red(' * Change url from http to https (y/n)?'), default='n') == 'y': if not exists(self.nginx_ssl_dir): sudo('mkdir -p {0}'.format(self.nginx_ssl_dir)) # generate ssh key sudo('openssl req -x509 -nodes -days 365 -newkey rsa:204... |
def common_install_apache2(self): """ Install apache2 web server """ try: sudo('apt-get install apache2 -y') except Exception as e: print(e) print(green(' * Installed Apache2 in the system.')) print(green(' * Done')) print() |
def common_install_python_env(self): """ Install python virtualenv """ sudo('apt-get install python3 python3-pip -y') sudo('pip3 install virtualenv') run('virtualenv {0}'.format(self.python_env_dir)) print(green(' * Installed Python3 virtual environment in the system.')) print(green(' * Done')) print() |
def systemctl_autostart(self, service_name, start_cmd, stop_cmd): """ ubuntu 16.04 systemctl service config :param service_name: :param start_cmd: :param stop_cmd: :return: """ # get config content service_content = bigdata_conf.systemctl_config.format( service_name=service_name, start_cmd=start_cmd, stop_cmd=stop_cmd ... |
def java_install(self): """ install java :return: """ sudo('apt-get install openjdk-8-jdk -y') java_home = run('readlink -f /usr/bin/java | ' 'sed "s:/jre/bin/java::"') append(bigdata_conf.global_env_home, 'export JAVA_HOME={0}'.format( java_home ), use_sudo=True) run('source {0}'.format(bigdata_conf.global_env_home)) |
def kafka_install(self): """ kafka download and install :return: """ with cd('/tmp'): if not exists('kafka.tgz'): sudo('wget {0} -O kafka.tgz'.format( bigdata_conf.kafka_download_url )) sudo('tar -zxf kafka.tgz') sudo('rm -rf {0}'.format(bigdata_conf.kafka_home)) sudo('mv kafka_* {0}'.format(bigdata_conf.kafka_home)) |
def kafka_config(self): """ kafka config :return: """ # 读取配置文件中的端口 config_obj = self.configure[self.args.config[1]] kafka_ports = config_obj.get('KAFKA_PORTS') # 默认端口9092 if not kafka_ports: kafka_ports_arr = ['9092'] else: kafka_ports_arr = kafka_ports.replace(' ', '').split(',') # chmod project root owner sudo('chown... |
def elastic_install(self): """ elasticsearch install :return: """ with cd('/tmp'): if not exists('elastic.deb'): sudo('wget {0} -O elastic.deb'.format( bigdata_conf.elastic_download_url )) sudo('dpkg -i elastic.deb') sudo('apt-get install -y') |
def logstash_install(self): """ logstash install :return: """ with cd('/tmp'): if not exists('logstash.deb'): sudo('wget {0} -O logstash.deb'.format( bigdata_conf.logstash_download_url )) sudo('dpkg -i logstash.deb') sudo('apt-get install -y') |
def kibana_install(self): """ kibana install :return: """ with cd('/tmp'): if not exists('kibana.deb'): sudo('wget {0} -O kibana.deb'.format( bigdata_conf.kibana_download_url )) sudo('dpkg -i kibana.deb') sudo('apt-get install -y') |
def kibana_config(self): """ config kibana :return: """ uncomment("/etc/kibana/kibana.yml", "#server.host:", use_sudo=True) sed('/etc/kibana/kibana.yml', 'server.host:.*', 'server.host: "{0}"'.format(env.host_string), use_sudo=True) sudo('systemctl stop kibana.service') sudo('systemctl daemon-reload') sudo('systemctl e... |
def hadoop_install(self): """ install hadoop :return: """ with cd('/tmp'): if not exists('hadoop.tar.gz'): sudo('wget {0} -O hadoop.tar.gz'.format( bigdata_conf.hadoop_download_url )) sudo('rm -rf hadoop-*') sudo('tar -zxf hadoop.tar.gz') sudo('rm -rf {0}'.format(bigdata_conf.hadoop_home)) sudo('mv hadoop-* {0}'.format... |
def spark_install(self): """ download and install spark :return: """ sudo('apt-get -y install build-essential python-dev python-six \ python-virtualenv libcurl4-nss-dev libsasl2-dev libsasl2-modules \ maven libapr1-dev libsvn-dev zlib1g-dev') with cd('/tmp'): if not exists('spark.tgz'): sudo('wget {0} -O spark.tgz'.for... |
def spark_config(self): """ config spark :return: """ configs = [ 'export LD_LIBRARY_PATH={0}/lib/native/:$LD_LIBRARY_PATH'.format( bigdata_conf.hadoop_home ), 'export SPARK_LOCAL_IP={0}'.format(env.host_string) ] append(bigdata_conf.global_env_home, configs, use_sudo=True) run('source {0}'.format(bigdata_conf.global_e... |
def reset_server_env(self, server_name, configure): """ reset server env to server-name :param server_name: :param configure: :return: """ env.host_string = configure[server_name]['host'] env.user = configure[server_name]['user'] env.password = configure[server_name]['passwd'] |
def generate_ssh(self, server, args, configure): """ 异步同时执行SSH生成 generate ssh :param server: :param args: :param configure: :return: """ self.reset_server_env(server, configure) # chmod project root owner sudo('chown {user}:{user} -R {path}'.format( user=configure[server]['user'], path=bigdata_conf.project_root )) # ge... |
def add_spark_slave(self, master, slave, configure): """ add spark slave :return: """ # go to master server, add config self.reset_server_env(master, configure) with cd(bigdata_conf.spark_home): if not exists('conf/spark-env.sh'): sudo('cp conf/spark-env.sh.template conf/spark-env.sh') spark_env = bigdata_conf.spark_en... |
def new_tmp(self): """ Create a new temp file allocation """ self.tmp_idx += 1 return p.join(self.tmp_dir, 'tmp_' + str(self.tmp_idx)) |
def new_backup(self, src): """ Create a new backup file allocation """ backup_id_file = p.join(self.backup_dir, '.bk_idx') backup_num = file_or_default(backup_id_file, 1, int) backup_name = str(backup_num) + "_" + os.path.basename(src) backup_num += 1 file_put_contents(backup_id_file, str(backup_num)) return p.join(sel... |
def begin(self): """ Begin a transaction """ if self.journal != None: raise Exception('Storage is already active, nested begin not supported') # under normal operation journal is deleted at end of transaction # if it does exist we need to roll back if os.path.isfile(self.j_file): self.rollback() self.journal = open(sel... |
def do_action(self, command, journal = True): """ Implementation for declarative file operations. """ cmd = 0; src = 1; path = 1; data = 2; dst = 2 if journal is True: self.journal.write(json.dumps(command['undo']) + "\n") self.journal.flush() d = command['do'] if d[cmd] == 'copy': shutil.copy(d[src], d[dst]) elif d[cm... |
def rollback(self): """ Do journal rollback """ # Close the journal for writing, if this is an automatic rollback following a crash, # the file descriptor will not be open, so don't need to do anything. if self.journal != None: self.journal.close() self.journal = None # Read the journal journ_list = [] with open(self.j... |
def commit(self, cont = False): """ Finish a transaction """ self.journal.close() self.journal = None os.remove(self.j_file) for itm in os.listdir(self.tmp_dir): os.remove(cpjoin(self.tmp_dir, itm)) if cont is True: self.begin() |
def file_get_contents(self, path): """ Returns contents of file located at 'path', not changing FS so does not require journaling """ with open(self.get_full_file_path(path), 'r') as f: return f.read() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.