code stringlengths 1 18.2k |
|---|
def getRegisterUserInfo(self, svctype = "Android NDrive App ver", auth = 0): """Get registerUserInfo Args: svctype: Platform information auth: ??? Returns: True: Success False: Failed """ data = {'userid': self.user_id, 'svctype': svctype, 'auth': auth} r = self.session.get(nurls['getRegisterUserInfo'], params = data) ... |
def checkStatus(self): """Check status Args: Returns: True: Sucess False: Failed """ checkAccount() data = {'userid': self.user_id, 'useridx': self.useridx } r = self.session.post(nurls['checkStatus'], data = data) p = re.compile(r'\<message\>(?P<message>.+)\</message\>') message = p.search(r.text).group('message') if ... |
def uploadFile(self, file_path, upload_path = '', overwrite = False): """uploadFile Remarks: How Ndrive uploads a file to its server: 1. POST /CheckStatus.ndrive 2. POST /GetDiskSpace.ndrive 3. POST /CheckUpload.ndrive 4. PUT /FILE_PATH 5. POST /GetList.ndrive 6. POST /GetWasteInfo.ndrive 7. POST /GetDiskSpace.ndrive "... |
def getDiskSpace(self, file_path, upload_path = '', overwrite = False): """getDiskSpace Args: file_path: Full path for a file you want to checkUpload upload_path: Ndrive path where you want to upload file ex) /Picture/ Returns: True: Possible to upload a file with a given file_size False: Impossible to upload a file wi... |
def put(self, file_path, upload_path = ''): """PUT Args: file_path: Full path for a file you want to upload upload_path: Ndrive path where you want to upload file ex) /Picture/ Returns: True: Upload success False: Upload failed """ f = open(file_path, "r") c = f.read() file_name = os.path.basename(file_path) now = date... |
def delete(self, file_path): """DELETE Args: file_path: Full path for a file you want to delete upload_path: Ndrive path where you want to delete file ex) /Picture/ Returns: True: Delete success False: Delete failed """ now = datetime.datetime.now().isoformat() url = nurls['put'] + upload_path + file_name headers = {'u... |
def getList(self, dummy = 56184, orgresource = '/', type = 1, dept = 0, sort = 'name', order = 'asc', startnum = 0, pagingrow = 1000): """GetList Args: dummy: ??? orgresource: Directory path to get the file list ex) /Picture/ type: 1 => only directories with idxfolder property 2 => only files 3 => directories and files... |
index ? Returns: FileInfo list: List of files for a path False: Failed to get list """ url = nurls['getList'] data = {'userid': self.user_id, 'useridx': self.useridx, 'dummy': dummy, 'orgresource': orgresource, 'type': type, 'dept': dept, 'sort': sort, 'order': order, 'startnum': startnum, 'pagingrow': pagingrow, } r =... |
= i['lastmodifieduser'] f.getcontentlength = i['getcontentlength'] f.lastaccessed = i['lastaccessed'] f.virusstatus = i['virusstatus'] f.idxfolder = i['idxfolder'] f.creationdate = i['creationdate'] f.nocache = i['nocache'] f.viewWidth = i['viewWidth'] f.viewHeight = i['viewHeight'] f.setJson(j['resultvalue']) files.ap... |
def doMove(self, orgresource, dstresource, dummy = 56184, stresource = 'F', bShareFireCopy = 'false'): """DoMove Args: dummy: ??? orgresource: Path for a file which you want to move dstresource: Destination path bShareFireCopy: ??? Returns: True: Move success False: Move failed """ url = nurls['doMove'] data = {'userid... |
def getProperty(self, orgresource, dummy = 56184): """GetProperty Args: dummy: ??? orgresource: File path Returns: FileInfo object: False: Failed to get property """ url = nurls['getProperty'] data = {'userid': self.user_id, 'useridx': self.useridx, 'dummy': dummy, 'orgresource': orgresource, } r = self.session.post(ur... |
def getVersionListCount(self, orgresource): """GetVersionListCount Args: orgresource: File path Returns: Integer number: # of version list False: Failed to get property """ url = nurls['getVersionListCount'] data = {'userid': self.user_id, 'useridx': self.useridx, 'orgresource': orgresource, } r = self.session.post(url... |
def setProperty(self, orgresource, protect, dummy = 7046): """SetProperty Args: orgresource: File path protect: 'Y' or 'N', 중요 표시 Returns: Integer number: # of version list False: Failed to get property """ url = nurls['setProperty'] data = {'userid': self.user_id, 'useridx': self.useridx, 'orgresource': orgresource, '... |
def getMusicAlbumList(self, tagtype = 0, startnum = 0, pagingrow = 100): """GetMusicAlbumList Args: tagtype = ??? startnum pagingrow Returns: ??? False: Failed to get property """ url = nurls['setProperty'] data = {'userid': self.user_id, 'useridx': self.useridx, 'tagtype': tagtype, 'startnum': startnum, 'pagingrow': p... |
def resultManager(self, text): """ resultcode & message: 0 = success => if "resultvalue" = null: no result to show 11 = Not Exist Path 36 = File Infomation Not Found 2002 = Invalidation Cookie """ j = json.loads(text) if j['message'] != 'success': print "[*] Error : " + j['message'] return False else: return True |
def update(connection, force_download): """Update the database""" manager.database.update( connection=connection, force_download=force_download ) |
def set_mysql(host, user, password, db, charset): """Set the SQLAlchemy connection string with MySQL settings""" manager.database.set_mysql_connection( host=host, user=user, password=password, db=db, charset=charset ) |
def main(): "Main program" generators = check_dependencies() args = docopt(__doc__, version='md2ebook 0.0.1-dev') commander = Commander(args, generators) commander.handle() |
def quantile_gaussianize(x): """Normalize a sequence of values via rank and Normal c.d.f. Args: x (array_like): sequence of values. Returns: Gaussian-normalized values. Example: .. doctest:: >>> from scipy_sugar.stats import quantile_gaussianize >>> print(quantile_gaussianize([-1, 0, 2])) [-0.67448975 0. 0.67448975] ""... |
def apply_noise(self, noise_generator, split_idx, ndigits=6): """Apply noise to dimensions within a peak. :param noise_generator: Noise generator object. :param int split_idx: Index specifying which peak list split parameters to use. :return: None :rtype: :py:obj:`None` """ noise = noise_generator.generate(self.labels,... |
def _to_sparky(self): """Save :class:`~nmrstarlib.plsimulator.PeakList` into Sparky-formatted string. :return: Peak list representation in Sparky format. :rtype: :py:class:`str` """ sparky_str = "Assignment\t\t{}\n\n".format("\t\t".join(["w" + str(i + 1) for i in range(len(self.labels))])) for peak in self: assignment_... |
def _to_autoassign(self): """Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string. :return: Peak list representation in AutoAssign format. :rtype: :py:class:`str` """ autoassign_str = "#Index\t\t{}\t\tIntensity\t\tWorkbook\n".format( "\t\t".join([str(i + 1) + "Dim" for i in range(len(self.lab... |
def _to_json(self): """Save :class:`~nmrstarlib.plsimulator.PeakList` into JSON string. :return: Peak list representation in JSON format. :rtype: :py:class:`str` """ json_list = [{"Assignment": peak.assignments_list, "Dimensions": peak.chemshifts_list} for peak in self] return json.dumps(json_list, sort_keys=True, inde... |
def write(self, filehandle, fileformat): """Write :class:`~nmrstarlib.plsimulator.PeakList` data into file. :param filehandle: file-like object. :type filehandle: :py:class:`io.TextIOWrapper` :param str fileformat: Format to use to write data: `sparky`, `autoassign`, or `json`. :return: None :rtype: :py:obj:`None` """ ... |
def is_sequential(self): """Check if residues that sequence site is composed of are in sequential order. :return: If sequence site is in valid sequential order (True) or not (False). :rtype: :py:obj:`True` or :py:obj:`False` """ seq_ids = tuple(int(residue["Seq_ID"]) for residue in self) return seq_ids == tuple(range(i... |
def create_dimension_groups(dimension_positions): """Create list of dimension groups. :param zip dimension_positions: List of tuples describing dimension and its position within sequence site. :return: List of dimension groups. :rtype: :py:class:`list` """ dimension_groups = [] for dim_group_label, position in dimensio... |
def peak_templates(self): """Create a list of concrete peak templates from a list of general peak descriptions. :return: List of peak templates. :rtype: :py:class:`list` """ peak_templates = [] for peak_descr in self: expanded_dims = [dim_group.dimensions for dim_group in peak_descr] templates = product(*expanded_dims)... |
def seq_site_length(self): """Calculate length of a single sequence site based upon relative positions specified in peak descriptions. :return: Length of sequence site. :rtype: :py:class:`int` """ relative_positions_set = set() for peak_descr in self: relative_positions_set.update(peak_descr.relative_positions) return ... |
def create_spectrum(spectrum_name): """Initialize spectrum and peak descriptions. :param str spectrum_name: Name of the spectrum from which peak list will be simulated. :return: Spectrum object. :rtype: :class:`~nmrstarlib.plsimulator.Spectrum` """ try: spectrum_description = nmrstarlib.SPECTRUM_DESCRIPTIONS[spectrum_n... |
def create_sequence_sites(chain, seq_site_length): """Create sequence sites using sequence ids. :param dict chain: Chain object that contains chemical shift values and assignment information. :param int seq_site_length: Length of a single sequence site. :return: List of sequence sites. :rtype: :py:class:`list` """ seq_... |
def calculate_intervals(chunk_sizes): """Calculate intervals for a given chunk sizes. :param list chunk_sizes: List of chunk sizes. :return: Tuple of intervals. :rtype: :py:class:`tuple` """ start_indexes = [sum(chunk_sizes[:i]) for i in range(0, len(chunk_sizes))] end_indexes = [sum(chunk_sizes[:i+1]) for i in range(0... |
def split_by_percent(self, spin_systems_list): """Split list of spin systems by specified percentages. :param list spin_systems_list: List of spin systems. :return: List of spin systems divided into sub-lists corresponding to specified split percentages. :rtype: :py:class:`list` """ chunk_sizes = [int((i*len(spin_syste... |
def create_peaklist(self, spectrum, chain, chain_idx, source): """Create peak list file. :param spectrum: Spectrum object instance. :type spectrum: :class:`~nmrstarlib.plsimulator.Spectrum` :param dict chain: Chain object that contains chemical shift values and assignment information. :param int chain_idx: Protein chai... |
self.split_by_percent(spin_systems) for split_idx, chunk in enumerate(spin_systems_chunks): for spin_system in chunk: for peak in spin_system: peak.apply_noise(self.noise_generator, split_idx) return peaklist |
def distArrayFactory(BaseClass): """ Returns a distributed array class that derives from BaseClass @param BaseClass base class, e.g. numpy.ndarray or numpy.ma.masked_array @return dist array class """ class DistArrayAny(BaseClass): """ Distributed array. Each process owns data and can expose a subset of the data to oth... |
# the type of data self.dtyp = dtyp # this process's MPI rank self.rk = self.comm.Get_rank() # number of processes self.sz = self.comm.Get_size() # mapping of numpy data types to MPI data types, # assumes that the data are of some numpy variant self.dtypMPI = None if dtyp == numpy.float64: self.dtypMPI = MPI.DOUBLE eli... |
rank """ return self.rk def getMPISize(self): """ Get the MPI size (number of processes) of this communicator @return rank """ return self.sz def expose(self, slce, winID): """ Collective operation to expose a sub-set of data @param slce tuple of slice objects @param winID the data window ID """ # buffer for source dat... |
mask array or None (if there is no mask) @note this is a no operation if there is no mask attached to the data """ if 'maskWindow' not in self.windows: # no mask, no op return None iw = self.windows[winID] slce = iw['slice'] maskSrc = iw['maskSrc'] maskDst = iw['maskDst'] # copy src mask into buffer maskSrc[...] = self... |
| MPI.MODE_NOPRECEDE) if pe is not None: win.Get([dataDst, self.dtypMPI], pe) win.Fence(MPI.MODE_NOSUCCEED) return dataDst def free(self): """ Must be called to free all exposed windows """ for iw in self.windows: self.windows[iw]['dataWindow'].Free() def reduce(self, op, initializer=None, rootPe=0): """ Collective red... |
def daArray(arry, dtype=numpy.float): """ Array constructor for numpy distributed array @param arry numpy-like array """ a = numpy.array(arry, dtype) res = DistArray(a.shape, a.dtype) res[:] = a return res |
def daZeros(shap, dtype=numpy.float): """ Zero constructor for numpy distributed array @param shap the shape of the array @param dtype the numpy data type """ res = DistArray(shap, dtype) res[:] = 0 return res |
def daOnes(shap, dtype=numpy.float): """ One constructor for numpy distributed array @param shap the shape of the array @param dtype the numpy data type """ res = DistArray(shap, dtype) res[:] = 1 return res |
def mdaArray(arry, dtype=numpy.float, mask=None): """ Array constructor for masked distributed array @param arry numpy-like array @param mask mask array (or None if all data elements are valid) """ a = numpy.array(arry, dtype) res = MaskedDistArray(a.shape, a.dtype) res[:] = a res.mask = mask return res |
def mdaZeros(shap, dtype=numpy.float, mask=None): """ Zero constructor for masked distributed array @param shap the shape of the array @param dtype the numpy data type @param mask mask array (or None if all data elements are valid) """ res = MaskedDistArray(shap, dtype) res[:] = 0 res.mask = mask return res |
def mdaOnes(shap, dtype=numpy.float, mask=None): """ One constructor for masked distributed array @param shap the shape of the array @param dtype the numpy data type @param mask mask array (or None if all data elements are valid) """ res = MaskedDistArray(shap, dtype) res[:] = 1 res.mask = mask return res |
def format_help(self): """ The help statement is slightly changed in that: 1) MapConstants.placeholderCounterHelpVersion is replaced MapConstants.placeholderCounter 2) 'COUNT_FROM', 'NUMBER_LENGTH', and 'EXTENSIONS' are shortened to 'VALUE', 'LENGTH', and 'EXT', respectively. """ return super(MapArgumentParser,self).fo... |
def stash(self, storage, url): """Stores the uploaded file in a temporary storage location.""" result = {} if self.is_valid(): upload = self.cleaned_data['upload'] name = storage.save(upload.name, upload) result['filename'] = os.path.basename(name) try: result['url'] = storage.url(name) except NotImplementedError: resu... |
def login(self, email=None, password=None, timeout=5): """Log in to CANDY HOUSE account. Return True on success.""" if email is not None: self.email = email if password is not None: self.password = password url = self.api_url + API_LOGIN_ENDPOINT data = json.dumps({'email': self.email, 'password': self.password}) heade... |
def request(self, method, endpoint, payload=None, timeout=5): """Send request to API.""" url = self.api_url + endpoint data = None headers = {} if payload is not None: data = json.dumps(payload) headers['Content-Type'] = 'application/json' try: if self.auth_token is not None: headers[API_AUTH_HEADER] = self.auth_token ... |
def sesames(self): """Return list of Sesames.""" response = self.request('GET', API_SESAME_LIST_ENDPOINT) if response is not None and response.status_code == 200: return json.loads(response.text)['sesames'] _LOGGER.warning("Unable to list Sesames") return [] |
def get_api( profile=None, config_file=None, requirements=None): ''' Generate a datafs.DataAPI object from a config profile ``get_api`` generates a DataAPI object based on a pre-configured datafs profile specified in your datafs config file. To create a datafs config file, use the command line tool ``datafs configure -... |
from StringIO import StringIO ... except ImportError: ... from io import StringIO ... >>> import tempfile >>> tempdir = tempfile.mkdtemp() >>> >>> config_file = StringIO(""" ... default-profile: my-data ... profiles: ... my-data: ... manager: ... class: MongoDBManager ... kwargs: ... database_name: 'MyDatabase' ... tab... |
... >>> archive.delete() >>> import shutil >>> shutil.rmtree(tempdir) ''' config = ConfigFile(config_file=config_file) config.read_config() if profile is None: profile = config.config['default-profile'] profile_config = config.get_profile_config(profile) default_versions = {} if requirements is None: requirements = con... |
def check_requirements(to_populate, prompts, helper=False): ''' Iterates through required values, checking to_populate for required values If a key in prompts is missing in to_populate and ``helper==True``, prompts the user using the values in to_populate. Otherwise, raises an error. Parameters ---------- to_populate :... |
def write_all(self, data): """ :param list[int] data: """ self._set_cursor_x(0) self._set_cursor_y(0) self.DC.on() self._write(data) |
def cli(parser): ''' Simply calls out to easy_install --upgrade ''' parser.add_argument('packages', nargs='*', default=local_packages(), help='Packages to upgrade (defaults to all installed packages)') parser.add_argument('-n', '--dry-run', action='store_true', help='Print upgrade actions without running') opts = parse... |
def post(self, *args, **kwargs): """Save file and return saved info or report errors.""" if self.upload_allowed(): form = self.get_upload_form() result = {} if form.is_valid(): storage = self.get_storage() result['is_valid'] = True info = form.stash(storage, self.request.path) result.update(info) else: result.update({ ... |
def get_upload_form(self): """Construct form for accepting file upload.""" return self.form_class(self.request.POST, self.request.FILES) |
def from_url(location): """ HTTP request for page at location returned as string malformed url returns ValueError nonexistant IP returns URLError wrong subnet IP return URLError reachable IP, no HTTP server returns URLError reachable IP, HTTP, wrong page returns HTTPError """ req = urllib.request.Request(location) with... |
def parse_description_xml(location): """ Extract serial number, base ip, and img url from description.xml missing data from XML returns AttributeError malformed XML returns ParseError Refer to included example for URLBase and serialNumber elements """ class _URLBase(str): """ Convenient access to hostname (ip) portion ... |
root.find('root:device', rootname) serial = device.find('root:serialNumber', rootname).text # anicon = device.find('root:iconList', rootname).find('root:icon', rootname) # imgurl = anicon.find('root:url', rootname).text # Alternatively, could look directly in the modelDescription field if all(x in xml_str.lower() for x... |
def _build_from(baseip): """ Build URL for description.xml from ip """ from ipaddress import ip_address try: ip_address(baseip) except ValueError: # """attempt to construct url but the ip format has changed""" # logger.warning("Format of internalipaddress changed: %s", baseip) if 'http' not in baseip[0:4].lower(): base... |
def parse_portal_json(): """ Extract id, ip from https://www.meethue.com/api/nupnp Note: the ip is only the base and needs xml file appended, and the id is not exactly the same as the serial number in the xml """ try: json_str = from_url('https://www.meethue.com/api/nupnp') except urllib.request.HTTPError as error: log... |
def via_upnp(): """ Use SSDP as described by the Philips guide """ ssdp_list = ssdp_discover("ssdp:all", timeout=5) #import pickle #with open("ssdp.pickle", "wb") as f: #pickle.dump(ssdp_list,f) bridges_from_ssdp = [u for u in ssdp_list if 'IpBridge' in u.server] logger.info('SSDP returned %d items with %d Hue bridges(... |
def via_nupnp(): """ Use method 2 as described by the Philips guide """ bridges_from_portal = parse_portal_json() logger.info('Portal returned %d Hue bridges(s).', len(bridges_from_portal)) # Confirm Portal gave an accessible bridge device by reading from the returned # location. Should look like: http://192.168.0.1/de... |
def via_scan(): """ IP scan - now implemented """ import socket import ipaddress import httpfind bridges_from_scan = [] hosts = socket.gethostbyname_ex(socket.gethostname())[2] for host in hosts: bridges_from_scan += httpfind.survey( # TODO: how do we determine subnet configuration? ipaddress.ip_interface(host+'/24').n... |
def find_bridges(prior_bridges=None): """ Confirm or locate IP addresses of Philips Hue bridges. `prior_bridges` -- optional list of bridge serial numbers * omitted - all discovered bridges returned as dictionary * single string - returns IP as string or None * dictionary - validate provided ip's before attempting disc... |
provided IP, add to found found_bridges[serial] = baseip else: # nothing usable at that ip logger.info('%s not found at %s', prior_sn, prior_ip) run_discovery = found_bridges.keys() != prior_bridges.keys() # prior_bridges is None, unknown, dict of unfound SNs, or empty dict # found_bridges is dict of found SNs from pri... |
%s.', type(prior_bridges)) except KeyError: # user provided Serial Number was not found # TODO: dropping tuples here if return none executed # return None pass # let it turn the string into a set, eww else: # user provided Serial Number found return ip_address # Filter the found list to subset of prior prior_bridges_ke... |
bridge with Serial ID %s', serial) else: # prior_bridges is None or empty dict, return all found pass return found_bridges |
def matches(self, a, b, **config): """ The message must match by package """ package_a = self.processor._u2p(a['msg']['update']['title'])[0] package_b = self.processor._u2p(b['msg']['update']['title'])[0] if package_a != package_b: return False return True |
def cli(parser): ''' Currently a cop-out -- just calls easy_install ''' parser.add_argument('-n', '--dry-run', action='store_true', help='Print uninstall actions without running') parser.add_argument('packages', nargs='+', help='Packages to install') opts = parser.parse_args() for package in opts.packages: install(pack... |
def mget(m_dict, keys, default=None, delimiter=':'): """ :param m_dict: A dictionary to search inside of :type m_dict: dict :param keys: A list of keys :type keys: str :param default: A default value to return if none found :param delimiter: The delimiter used in the keys list :type delimiter: str :return: The value ac... |
def mset(m_dict, keys, value, delimiter=':'): """ :param m_dict: A dictionary to set the value inside of :type m_dict: dict :param keys: A list of keys :type keys: str :param value: The value to set inside of the dictionary :param delimiter: The delimiter used in the keys list :type delimiter: str """ val = m_dict keys... |
def parse_grain(grain): """ Parse a string to a granularity, e.g. "Day" to InstantTime.day. :param grain: a string representing a granularity. """ if not grain: return InstantTime.day if grain.lower() == 'week': return InstantTime.week return InstantTime.day |
def update_from_pypi(self): """Call get_latest_version and then save the object.""" package = pypi.Package(self.package_name) self.licence = package.licence() if self.is_parseable: self.latest_version = package.latest_version() self.next_version = package.next_version(self.current_version) self.diff_status = pypi.versi... |
def close(self): """close conn""" if not self._s or not hasattr(self._s, "close"): return try: self._s.close() except BaseException: pass |
def sendfile(self, data, zlib_compress=None, compress_level=6): """Send data from a file object""" if hasattr(data, 'seek'): data.seek(0) chunk_size = CHUNK_SIZE if zlib_compress: chunk_size = BLOCK_SIZE compressor = compressobj(compress_level) while 1: binarydata = data.read(chunk_size) if binarydata == '': break if z... |
def ghostedDistArrayFactory(BaseClass): """ Returns a ghosted distributed array class that derives from BaseClass @param BaseClass base class, e.g. DistArray or MaskedDistArray @return ghosted dist array class """ class GhostedDistArrayAny(BaseClass): """ Ghosted distributed array. Each process owns data and exposes th... |
(-1, 1): # the window id uniquely specifies the # location of the window. we use 0's to indicate # a slab extending over the entire length for a # given direction, a 1 represents a layer of # thickness numGhosts on the high index side, # -1 on the low index side. winId = tuple([0 for i in range(dim)] + [drect] + [0 for... |
along dimension dim @return slab """ shape = self.shape ndim = len(shape) slab = [slice(0, shape[i]) for i in range(dim)] + \ [slce] + [slice(0, shape[i]) for i in range(dim+1, ndim)] return slab def getEllipsis(self, winID): """ Get the ellipsis for a given halo side @param winID a tuple of zeros and one +1 or -1. To ... |
def gdaArray(arry, dtype, numGhosts=1): """ ghosted distributed array constructor @param arry numpy-like array @param numGhosts the number of ghosts (>= 0) """ a = numpy.array(arry, dtype) res = GhostedDistArray(a.shape, a.dtype) res.setNumberOfGhosts(numGhosts) res[:] = a return res |
def gdaZeros(shape, dtype, numGhosts=1): """ ghosted distributed array zero constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0) """ res = GhostedDistArray(shape, dtype) res.setNumberOfGhosts(numGhosts) res[:] = 0 return res |
def gdaOnes(shape, dtype, numGhosts=1): """ ghosted distributed array one constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0) """ res = GhostedDistArray(shape, dtype) res.setNumberOfGhosts(numGhosts) res[:] = 1 return res |
def gmdaArray(arry, dtype, mask=None, numGhosts=1): """ ghosted distributed array constructor @param arry numpy-like array @param numGhosts the number of ghosts (>= 0) """ a = numpy.array(arry, dtype) res = GhostedMaskedDistArray(a.shape, a.dtype) res.mask = mask res.setNumberOfGhosts(numGhosts) res[:] = a return res |
def gmdaZeros(shape, dtype, mask=None, numGhosts=1): """ ghosted distributed array zero constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0) """ res = GhostedMaskedDistArray(shape, dtype) res.mas = mask res.setNumberOfGhosts(numGhosts) res[:] = 0 ... |
def gmdaOnes(shape, dtype, mask=None, numGhosts=1): """ ghosted distributed array one constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0) """ res = GhostedMaskedDistArray(shape, dtype) res.mask = mask res.setNumberOfGhosts(numGhosts) res[:] = 1 r... |
def serialize_upload(name, storage, url): """ Serialize uploaded file by name and storage. Namespaced by the upload url. """ if isinstance(storage, LazyObject): # Unwrap lazy storage class storage._setup() cls = storage._wrapped.__class__ else: cls = storage.__class__ return signing.dumps({ 'name': name, 'storage': '%s... |
def deserialize_upload(value, url): """ Restore file and name and storage from serialized value and the upload url. """ result = {'name': None, 'storage': None} try: result = signing.loads(value, salt=url) except signing.BadSignature: # TODO: Log invalid signature pass else: try: result['storage'] = get_storage_class(r... |
def open_stored_file(value, url): """ Deserialize value for a given upload url and return open file. Returns None if deserialization fails. """ upload = None result = deserialize_upload(value, url) filename = result['name'] storage_class = result['storage'] if storage_class and filename: storage = storage_class() if st... |
def _check_action(action): """check for invalid actions""" if isinstance(action, types.StringTypes): action = action.lower() if action not in ['learn', 'forget', 'report', 'revoke']: raise SpamCError('The action option is invalid') return action |
def get_response(cmd, conn): """Return a response""" resp = conn.socket().makefile('rb', -1) resp_dict = dict( code=0, message='', isspam=False, score=0.0, basescore=0.0, report=[], symbols=[], headers={}, ) if cmd == 'TELL': resp_dict['didset'] = False resp_dict['didremove'] = False data = resp.read() lines = data.spl... |
part[1] score = score.strip() resp_dict['report'].append( dict(score=score, name=part[2], description=SPACE_RE.sub(" ", part[3]))) if line.startswith('DidSet:'): resp_dict['didset'] = True if line.startswith('DidRemove:'): resp_dict['didremove'] = True if cmd == 'PROCESS': resp_dict['message'] = ''.join(lines[4:]) + '\... |
def get_connection(self): """Creates a new connection""" if self.host is None: connector = SpamCUnixConnector conn = connector(self.socket_file, self.backend_mod) else: connector = SpamCTcpConnector conn = connector( self.host, self.port, self.backend_mod, is_ssl=self.is_ssl, **self.ssl_args) return conn |
def get_headers(self, cmd, msg_length, extra_headers): """Returns the headers string based on command to execute""" cmd_header = "%s %s" % (cmd, PROTOCOL_VERSION) len_header = "Content-length: %s" % msg_length headers = [cmd_header, len_header] if self.user: user_header = "User: %s" % self.user headers.append(user_head... |
def perform(self, cmd, msg='', extra_headers=None): """Perform the call""" tries = 0 while 1: conn = None try: conn = self.get_connection() if hasattr(msg, 'read') and hasattr(msg, 'fileno'): msg_length = str(os.fstat(msg.fileno()).st_size) elif hasattr(msg, 'read'): msg.seek(0, 2) msg_length = str(msg.tell() + 2) else... |
as err: if conn is not None: conn.release() raise SpamCTimeOutError(str(err)) except socket.error as err: if conn is not None: conn.close() errors = (errno.EAGAIN, errno.EPIPE, errno.EBADF, errno.ECONNRESET) if err[0] not in errors or tries >= self.max_tries: raise SpamCError("socket.error: %s" % str(err)) except BaseE... |
def tell(self, msg, action, learnas=''): """Tell what type of we are to process and what should be done with that message. This includes setting or removing a local or a remote database (learning, reporting, forgetting, revoking).""" action = _check_action(action) mode = learnas.upper() headers = { 'Message-class': '',... |
def learn(self, msg, learnas): """Learn message as spam/ham or forget""" if not isinstance(learnas, types.StringTypes): raise SpamCError('The learnas option is invalid') if learnas.lower() == 'forget': resp = self.tell(msg, 'forget') else: resp = self.tell(msg, 'learn', learnas) return resp |
def generate_key(filepath): ''' generates a new, random secret key at the given location on the filesystem and returns its path ''' fs = path.abspath(path.expanduser(filepath)) with open(fs, 'wb') as outfile: outfile.write(Fernet.generate_key()) chmod(fs, 0o400) return fs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.