docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Creates a Future that tracks when a Channel is ready. Cancelling the Future does not affect the channel's state machine. It merely decouples the Future from channel state machine. Args: channel: A Channel object. Returns: A Future object that matures when the channel connectivity is ChannelConnec...
def channel_ready_future(channel): fut = channel._loop.create_future() def _set_result(state): if not fut.done() and state is _grpc.ChannelConnectivity.READY: fut.set_result(None) fut.add_done_callback(lambda f: channel.unsubscribe(_set_result)) channel.subscribe(_set_result, tr...
472,817
Creates an insecure Channel to a server. Args: target: The server address options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object.
def insecure_channel(target, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): return Channel(_grpc.insecure_channel(target, options), loop, executor, standalone_pool_for_streaming)
472,818
Creates a secure Channel to a server. Args: target: The server address. credentials: A ChannelCredentials instance. options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object.
def secure_channel(target, credentials, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): return Channel(_grpc.secure_channel(target, credentials, options), loop, executor, standalone_pool_for_streaming)
472,819
Constructor. Args: _channel: wrapped grpc.Channel loop: asyncio event loop executor: a thread pool, or None to use the default pool of the loop standalone_pool_for_streaming: create a new thread pool (with 1 thread) for each streaming ...
def __init__(self, _channel, loop=None, executor=None, standalone_pool_for_streaming=False): self._channel = _channel if loop is None: loop = _asyncio.get_event_loop() self._loop = loop self._executor = executor self._standalone_pool = standalone_pool_for_str...
472,829
Load a config file from the given path. Load all normalizations from the config file received as argument. It expects to find a YAML file with a list of normalizations and arguments under the key 'normalizations'. Args: path: Path to YAML file.
def _load_from_file(path): config = [] try: with open(path, 'r') as config_file: config = yaml.load(config_file)['normalizations'] except EnvironmentError as e: raise ConfigError('Problem while loading file: %s' % e....
473,205
Parse a normalization item. Transform dicts into a tuple containing the normalization options. If a string is found, the actual value is used. Args: normalization: Normalization to parse. Returns: Tuple or string containing the parsed normalization.
def _parse_normalization(normalization): parsed_normalization = None if isinstance(normalization, dict): if len(normalization.keys()) == 1: items = list(normalization.items())[0] if len(items) == 2: # Two elements tuple # Convert ...
473,206
Returns a list of parsed normalizations. Iterates over a list of normalizations, removing those not correctly defined. It also transform complex items to have a common format (list of tuples and strings). Args: normalizations: List of normalizations to parse. Retur...
def _parse_normalizations(self, normalizations): parsed_normalizations = [] if isinstance(normalizations, list): for item in normalizations: normalization = self._parse_normalization(item) if normalization: parsed_normalizations.a...
473,207
Set up logger to be used by the library. Args: debug: Wheter to use debug level or not. Returns: A logger ready to be used.
def initialize_logger(debug): level = logging.DEBUG if debug else logging.INFO logger = logging.getLogger('cucco') logger.setLevel(level) formatter = logging.Formatter('%(asctime)s %(levelname).1s %(message)s') console_handler = logging.StreamHandler() console_handler.setLevel(level) co...
473,208
Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for eac...
def files_generator(path, recursive): if recursive: for (path, _, files) in os.walk(path): for file in files: if not file.endswith(BATCH_EXTENSION): yield (path, file) else: for file in os.listdir(path): if (os.path.isfile(os.path....
473,212
Process a file applying normalizations. Get a file as input and generate a new file with the result of applying normalizations to every single line in the original file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: path: Path to t...
def process_file(self, path): if self._config.verbose: self._logger.info('Processing file "%s"', path) output_path = '%s%s' % (path, BATCH_EXTENSION) with open(output_path, 'w') as file: for line in lines_generator(path): file.write('%s\n' % sel...
473,214
Apply normalizations over all files in the given directory. Iterate over all files in a given directory. Normalizations will be applied to each file, storing the result in a new file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: p...
def process_files(self, path, recursive=False): self._logger.info('Processing files in "%s"', path) for (path, file) in files_generator(path, recursive): if not file.endswith(BATCH_EXTENSION): self.process_file(os.path.join(path, file))
473,215
Watch for files in a directory and apply normalizations. Watch for new or changed files in a directory and apply normalizations over them. Args: path: Path to the directory. recursive: Whether to find files recursively or not.
def watch(self, path, recursive=False): self._logger.info('Initializing watcher for path "%s"', path) handler = FileHandler(self) self._observer = Observer() self._observer.schedule(handler, path, recursive) self._logger.info('Starting watcher') self._observer....
473,217
Process received events. Process events received, applying normalization for those events referencing a new or changed file and only if it's not the result of a previous normalization. Args: event: Event to process.
def _process_event(self, event): if (not event.is_directory and not event.src_path.endswith(BATCH_EXTENSION)): self._logger.info('Detected file change: %s', event.src_path) self._batch.process_file(event.src_path)
473,219
Function called everytime a new file is created. Args: event: Event to process.
def on_created(self, event): self._logger.debug('Detected create event on watched path: %s', event.src_path) self._process_event(event)
473,220
Function called everytime a new file is modified. Args: event: Event to process.
def on_modified(self, event): self._logger.debug('Detected modify event on watched path: %s', event.src_path) self._process_event(event)
473,221
Load stop words into __stop_words set. Stop words will be loaded according to the language code received during instantiation. Args: language: Language code. Returns: A boolean indicating whether a file was loaded.
def _load_stop_words(self, language=None): self._logger.debug('Loading stop words') loaded = False if language: file_path = 'data/stop-' + language loaded = self._parse_stop_words_file(os.path.join(PATH, file_path)) else: for file in os.list...
473,223
Parse and yield normalizations. Parse normalizations parameter that yield all normalizations and arguments found on it. Args: normalizations: List of normalizations. Yields: A tuple with a parsed normalization. The first item will contain the normal...
def _parse_normalizations(normalizations): str_type = str if sys.version_info[0] > 2 else (str, unicode) for normalization in normalizations: yield (normalization, {}) if isinstance(normalization, str_type) else normalization
473,224
Load stop words from the given path. Parse the stop words file, saving each word found in it in a set for the language of the file. This language is obtained from the file name. If the file doesn't exist, the method will have no effect. Args: path: Path to the stop ...
def _parse_stop_words_file(self, path): language = None loaded = False if os.path.isfile(path): self._logger.debug('Loading stop words in %s', path) language = path.split('-')[-1] if not language in self.__stop_words: self.__stop_wo...
473,225
Normalize a given text applying all normalizations. Normalizations to apply can be specified through a list of parameters and will be executed in that order. Args: text: The text to be processed. normalizations: List of normalizations to apply. Returns: ...
def normalize(self, text, normalizations=None): for normalization, kwargs in self._parse_normalizations( normalizations or self._config.normalizations): try: text = getattr(self, normalization)(text, **kwargs) except AttributeError as e: ...
473,226
Remove accent marks from input text. This function removes accent marks in the text, but leaves unicode characters defined in the 'excluded' parameter. Args: text: The text to be processed. excluded: Set of unicode characters to exclude. Returns: Th...
def remove_accent_marks(text, excluded=None): if excluded is None: excluded = set() return unicodedata.normalize( 'NFKC', ''.join( c for c in unicodedata.normalize( 'NFKD', text) if unicodedata.category(c) != 'Mn' or c in excluded))
473,227
Remove stop words. Stop words are loaded on class instantiation according to the specified language. Args: text: The text to be processed. ignore_case: Whether or not to ignore case. language: Code of the language to use (defaults to 'en'). Returns:...
def remove_stop_words(self, text, ignore_case=True, language=None): if not language: language = self._config.language if language not in self.__stop_words: if not self._load_stop_words(language): self._logger.error('No stop words file for the given langu...
473,228
Remove characters from text. Removes custom characters from input text or replaces them with a string if specified. Args: text: The text to be processed. characters: Characters that will be replaced. replacement: New text that will replace the custom charact...
def replace_characters(self, text, characters, replacement=''): if not characters: return text characters = ''.join(sorted(characters)) if characters in self._characters_regexes: characters_regex = self._characters_regexes[characters] else: c...
473,229
Replace punctuation symbols in text. Removes punctuation from input text or replaces them with a string if specified. Characters replaced will be those in string.punctuation. Args: text: The text to be processed. excluded: Set of characters to exclude. ...
def replace_punctuation(self, text, excluded=None, replacement=''): if excluded is None: excluded = set() elif not isinstance(excluded, set): excluded = set(excluded) punct = ''.join(self.__punctuation.difference(excluded)) return self.replace_characters...
473,230
Replace symbols in text. Removes symbols from input text or replaces them with a string if specified. Args: text: The text to be processed. form: Unicode form. excluded: Set of unicode characters to exclude. replacement: New text that will replac...
def replace_symbols( text, form='NFKD', excluded=None, replacement=''): if excluded is None: excluded = set() categories = set(['Mn', 'Sc', 'Sk', 'Sm', 'So']) return ''.join(c if unicodedata.category(c) not in categories or c...
473,231
Initialize a switch parser. Args: ea: An address of a switch jump instruction.
def __init__(self, ea): self._ea = ea results = self._calc_cases() self._map = self._build_map(results) self._reverse_map = self._build_reverse(self._map)
473,345
Initialize the graph viewer. To avoid bizarre IDA errors (crashing when creating 2 graphs with the same title,) a counter is appended to the title (similar to "Hex View-1".) Args: graph: A NetworkX graph to display. title: The graph title. handler: The defau...
def __init__(self, graph, title="GraphViewer", handler=None, padding=PADDING): title = self._make_unique_title(title) idaapi.GraphViewer.__init__(self, title) self._graph = graph if handler is None: handler = self.DEFAULT_HANDLER # Here we make sure the h...
473,397
get_func(func_t or ea) -> func_t Take an IDA function (``idaapi.func_t``) or an address (EA) and return an IDA function object. Use this when APIs can take either a function or an address. Args: func_ea: ``idaapi.func_t`` or ea of the function. Returns: An ``idaapi.func_t`` objec...
def get_func(func_ea): if isinstance(func_ea, idaapi.func_t): return func_ea func = idaapi.get_func(func_ea) if func is None: raise exceptions.SarkNoFunction("No function at 0x{:08X}".format(func_ea)) return func
473,430
Get all `CodeBlock`s in a given range. Args: start - start address of the range. If `None` uses IDB start. end - end address of the range. If `None` uses IDB end. full - `True` is required to change node info (e.g. color). `False` causes faster iteration.
def codeblocks(start=None, end=None, full=True): if full: for function in functions(start, end): fc = FlowChart(f=function.func_t) for block in fc: yield block else: start, end = fix_addresses(start, end) for code_block in FlowChart(bounds=(...
473,442
Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: A ``SarkErrorAddStructMemeberFailed`` derivative exception, wi...
def struct_member_error(err, sid, name, offset, size): exception, msg = STRUCT_ERROR_MAP[err] struct_name = idc.GetStrucName(sid) return exception(('AddStructMember(struct="{}", member="{}", offset={}, size={}) ' 'failed: {}').format( struct_name, name, off...
473,448
Create a structure. Args: name: The structure's name Returns: The sturct ID Raises: exceptions.SarkStructAlreadyExists: A struct with the same name already exists exceptions.SarkCreationFailed: Struct creation failed
def create_struct(name): sid = idc.GetStrucIdByName(name) if sid != idaapi.BADADDR: # The struct already exists. raise exceptions.SarkStructAlreadyExists("A struct names {!r} already exists.".format(name)) sid = idc.AddStrucEx(-1, name, 0) if sid == idaapi.BADADDR: raise ex...
473,449
Get a struct by it's name. Args: name: The name of the struct Returns: The struct's id Raises: exceptions.SarkStructNotFound: is the struct does not exist.
def get_struct(name): sid = idc.GetStrucIdByName(name) if sid == idaapi.BADADDR: raise exceptions.SarkStructNotFound() return sid
473,450
Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in this case `ebx`, are counted. The most used one is returned. Ar...
def get_common_register(start, end): registers = defaultdict(int) for line in lines(start, end): insn = line.insn for operand in insn.operands: if not operand.type.has_phrase: continue if not operand.base: continue regi...
473,453
Create a new enum. Args: name: Name of the enum to create. index: The index of the enum. Leave at default to append the enum as the last enum. flags: Enum type flags. bitfield: Is the enum a bitfield. Returns: An `Enum` object.
def add_enum(name=None, index=None, flags=idaapi.hexflag(), bitfield=False): if name is not None: with ignored(exceptions.EnumNotFound): _get_enum(name) raise exceptions.EnumAlreadyExists() if index is None or index < 0: index = idaapi.get_enum_qty() eid = idaa...
473,472
Add an enum member Args: name: Name of the member value: value of the member bitmask: bitmask. Only use if enum is a bitfield.
def add(self, name, value, bitmask=DEFMASK): _add_enum_member(self._eid, name, value, bitmask)
473,483
Get an existing enum. Only provide one of `name` and `eid`. Args: name: Name of the enum eid: Enum ID
def __init__(self, name=None, eid=None): if None not in (name, eid): raise TypeError("Provide only a `name` or an `eid`.") self._eid = eid or _get_enum(name) self._comments = EnumComments(self._eid)
473,487
Get all functions in range. Args: start: Start address of the range. Defaults to IDB start. end: End address of the range. Defaults to IDB end. Returns: This is a generator that iterates over all the functions in the IDB.
def functions(start=None, end=None): start, end = fix_addresses(start, end) for func_t in idautils.Functions(start, end): yield Function(func_t)
473,517
Set Function Name. Default behavior throws an exception when setting to a name that already exists in the IDB. to make IDA automatically add a counter to the name (like in the GUI,) use `anyway=True`. Args: name: Desired name. anyway: `True` to set anyway.
def set_name(self, name, anyway=False): set_name(self.startEA, name, anyway=anyway)
473,524
Iterate lines in range. Args: start: Starting address, start of IDB if `None`. end: End address, end of IDB if `None`. reverse: Set to true to iterate in reverse order. selection: If set to True, replaces start and end with current selection. Returns: iterator of `Line`...
def lines(start=None, end=None, reverse=False, selection=False): if selection: start, end = get_selection() else: start, end = fix_addresses(start, end) if not reverse: item = idaapi.get_item_head(start) while item < end: yield Line(item) item +...
473,530
Grab an image of a Qt widget Args: widget: The Qt Widget to capture path (optional): The path to save to. If not provided - will return image data. Returns: If a path is provided, the image will be saved to it. If not, the PNG buffer will be returned.
def capture_widget(widget, path=None): if use_qt5: pixmap = widget.grab() else: pixmap = QtGui.QPixmap.grabWidget(widget) if path: pixmap.save(path) else: image_buffer = QtCore.QBuffer() image_buffer.open(QtCore.QIODevice.ReadWrite) pixmap.save(ima...
473,560
Iterate segments based on type Args: seg_type: type of segment e.g. SEG_CODE Returns: iterator of `Segment` objects. if seg_type is None , returns all segments otherwise returns only the relevant ones
def segments(seg_type=None): for index in xrange(idaapi.get_segm_qty()): seg = Segment(index=index) if (seg_type is None) or (seg.type == seg_type): yield Segment(index=index)
473,571
Wrapper around IDA segments. There are 3 ways to get a segment - by name, ea or index. Only use one. Args: ea - address in the segment name - name of the segment index - index of the segment
def __init__(self, ea=UseCurrentAddress, name=None, index=None, segment_t=None): if sum((ea not in (self.UseCurrentAddress, None), name is not None, index is not None, segment_t is not None,)) > 1: raise ValueError(( "Expected only one (ea, n...
473,577
Creates a wrapper to perform API actions. Arguments: domain: the Freshdesk domain (not custom). e.g. company.freshdesk.com api_key: the API key Instances: .tickets: the Ticket API
def __init__(self, domain, api_key, verify=True, proxies=None): self._api_prefix = 'https://{}/api/v2/'.format(domain.rstrip('/')) self._session = requests.Session() self._session.auth = (api_key, 'unused_with_api_key') self._session.verify = verify self._session.proxie...
473,804
Creates a wrapper to perform API actions. Arguments: domain: the Freshdesk domain (not custom). e.g. company.freshdesk.com api_key: the API key Instances: .tickets: the Ticket API
def __init__(self, domain, api_key): self._api_prefix = 'https://{}/'.format(domain.rstrip('/')) self.auth = (api_key, 'X') self.headers = {'Content-Type': 'application/json'} self.tickets = TicketAPI(self) self.contacts = ContactAPI(self) self.agents = AgentAP...
473,820
Write the utterance transcriptions to files in the tgt_dir. Is lazy and checks if the file already exists. Args: utterances: A list of Utterance objects to be written. tgt_dir: The directory in which to write the text of the utterances, one file per utterance. ext: The file ...
def write_transcriptions(utterances: List[Utterance], tgt_dir: Path, ext: str, lazy: bool) -> None: tgt_dir.mkdir(parents=True, exist_ok=True) for utter in utterances: out_path = tgt_dir / "{}.{}".format(utter.prefix, ext) if lazy and out_path.is_file(): ...
473,988
Remove empty utterances from a list of utterances Args: utterances: The list of utterance we are processing
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: return [utter for utter in utterances if utter.text.strip() != ""]
473,990
Get the duration of an entire list of utterances in milliseconds Args: utterances: The list of utterance we are finding the duration of
def total_duration(utterances: List[Utterance]) -> int: return sum([duration(utter) for utter in utterances])
473,991
Calculate the word error rate of a sequence against a reference. Args: ref: The gold-standard reference sequence hyp: The hypothesis to be evaluated against the reference. Returns: The word error rate of the supplied hypothesis with respect to the reference string. Raises:...
def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float: if len(ref) == 0: raise EmptyReferenceException( "Cannot calculating word error rate against a length 0 "\ "reference sequence.") distance = min_edit_distance(ref, hyp) return 100 * float(distance) / len...
473,998
Find the prefixes for all the wav files that do not have an associated transcription Args: wav_path: Path to search for wav files in transcription_path: Path to search for transcriptions in label_type: The type of labels for transcriptions. Eg "phonemes" "phonemes_and_tones" Returns: ...
def find_untranscribed_wavs(wav_path: Path, transcription_path: Path, label_type: str) -> List[str]: audio_files = wav_path.glob("**/*.wav") transcription_files = transcription_path.glob("**/*.{}".format(label_type)) transcription_file_prefixes = [t_file.stem for t_file in transcription_files] un...
474,010
Returns a set of all phonemes found in the corpus. Assumes that WAV files and label files are split into utterances and segregated in a directory which contains a "wav" subdirectory and "label" subdirectory. Arguments: target_dir: A `Path` to the directory where the corpus data is found lab...
def determine_labels(target_dir: Path, label_type: str) -> Set[str]: logger.info("Finding phonemes of type %s in directory %s", label_type, target_dir) label_dir = target_dir / "label/" if not label_dir.is_dir(): raise FileNotFoundError( "The directory {} does not exist.".format(ta...
474,012
Performs feature extraction from the WAV files in a directory. Args: dirpath: A `Path` to the directory where the WAV files reside. feat_type: The type of features that are being used.
def from_dir(dirpath: Path, feat_type: str) -> None: logger.info("Extracting features from directory {}".format(dirpath)) dirname = str(dirpath) def all_wavs_processed() -> bool: for fn in os.listdir(dirname): prefix, ext = os.path.splitext(fn) if ext == ".w...
474,081
Converts the wav into a 16bit mono 16000Hz wav. Args: org_wav_fn: A `Path` to the original wave file tgt_wav_fn: The `Path` to output the processed wave file
def convert_wav(org_wav_fn: Path, tgt_wav_fn: Path) -> None: if not org_wav_fn.exists(): raise FileNotFoundError args = [config.FFMPEG_PATH, "-i", str(org_wav_fn), "-ac", "1", "-ar", "16000", str(tgt_wav_fn)] subprocess.run(args)
474,082
Extracts part of a WAV File. First attempts to call sox. If sox is unavailable, it backs off to pydub+ffmpeg. Args: in_path: A path to the source file to extract a portion of out_path: A path describing the to-be-created WAV file. start_time: The point in the source WAV file at whi...
def trim_wav_ms(in_path: Path, out_path: Path, start_time: int, end_time: int) -> None: try: trim_wav_sox(in_path, out_path, start_time, end_time) except FileNotFoundError: # Then sox isn't installed, so use pydub/ffmpeg trim_wav_pydub(in_path, out_path, start_time,...
474,090
Extracts WAVs from the media files associated with a list of Utterance objects and stores it in a target directory. Args: utterances: A list of Utterance objects, which include information about the source media file, and the offset of the utterance in the media_file. tg...
def extract_wavs(utterances: List[Utterance], tgt_dir: Path, lazy: bool) -> None: tgt_dir.mkdir(parents=True, exist_ok=True) for utter in utterances: wav_fn = "{}.{}".format(utter.prefix, "wav") out_wav_path = tgt_dir / wav_fn if lazy and out_wav_path.is_file(): ...
474,093
Preprocess Na sentences Args: sent: A sentence label_type: The type of label provided
def preprocess_na(sent, label_type): if label_type == "phonemes_and_tones": phonemes = True tones = True tgm = True elif label_type == "phonemes_and_tones_no_tgm": phonemes = True tones = True tgm = False elif label_type == "phonemes": phonemes = ...
474,103
Find a sequence of addresses. Args: addresses: a list of IPv4 or IPv6 addresses. Returns: A tuple containing the first and last IP addresses in the sequence, and the index of the last IP address in the sequence.
def _find_address_range(addresses): first = last = addresses[0] last_index = 0 for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip last_index += 1 else: break return (first, last, last_index)
479,023
Validate and return a prefix length integer. Args: prefixlen: An integer containing the prefix length. Returns: The input, possibly converted from long to int. Raises: NetmaskValueError: If the input is not an integer, or out of range.
def _prefix_from_prefix_int(self, prefixlen): if not isinstance(prefixlen, (int, long)): raise NetmaskValueError('%r is not an integer' % prefixlen) prefixlen = int(prefixlen) if not (0 <= prefixlen <= self._max_prefixlen): raise NetmaskValueError('%d is not a va...
479,024
Finalize and stop service Args: nowait: set to True to terminate immediately and skip processing messages still in the queue
def terminate(self, nowait=False): logger.debug("Acquiring lock for service termination") with self.lock: logger.debug("Terminating service") if not self.listener: logger.warning("Service already stopped.") return self.listen...
479,468
Init the service class. Args: endpoint: endpoint of report portal service. project: project name to use for launch names. token: authorization token. api_base: defaults to api/v1, can be changed to other version. is_skipped_an_issue: option to mark sk...
def __init__(self, endpoint, project, token, api_base="api/v1", is_skipped_an_issue=True, verify_ssl=True): super(ReportPortalService, self).__init__() self.endpoint = endpoint self.api_base = api_base self.project = project self.token = token se...
479,480
Logs batch of messages with attachment. Args: log_data: list of log records. log record is a dict of; time, message, level, attachment attachment is a dict of: name: name of attachment data: fileobj or content ...
def log_batch(self, log_data): url = uri_join(self.base_url, "log") attachments = [] for log_item in log_data: log_item["item_id"] = self.stack[-1] attachment = log_item.get("attachment", None) if "attachment" in log_item: del log_i...
479,489
Train a network with the quasi-Newton method. Args: X (np.array of float): feature matrix for training y (np.array of float): target values for training X_val (np.array of float): feature matrix for validation y_val (np.array of float): target values for ...
def fit(self, X, y, X_val=None, y_val=None): y = y.reshape((len(y), 1)) if sparse.issparse(X): X = X.tocsr() if X_val is not None: n_val = len(y_val) y_val = y_val.reshape((n_val, 1)) # Set initial weights randomly. self.i = X.shape...
479,512
Predict targets for a feature matrix. Args: X (np.array of float): feature matrix for prediction Returns: prediction (np.array)
def predict(self, X): logger.info('predicting ...') ps = self.predict_raw(X) return sigm(ps[:, 0])
479,513
Predict targets for a feature matrix. Args: X (np.array of float): feature matrix for prediction
def predict_raw(self, X): # b -- bias for the input and h layers b = np.ones((X.shape[0], 1)) w2 = self.w[-(self.h + 1):].reshape(self.h + 1, 1) w1 = self.w[:-(self.h + 1)].reshape(self.i + 1, self.h) # Make X to have the same number of columns as self.i. # Beca...
479,514
Return the costs of the neural network for predictions. Args: w (array of float): weight vectors such that: w[:-h1] -- weights between the input and h layers w[-h1:] -- weights between the h and output layers args: features (args[0]) and target (args[1]) ...
def func(self, w, *args): x0 = args[0] x1 = args[1] n0 = x0.shape[0] n1 = x1.shape[0] # n -- number of pairs to evaluate n = max(n0, n1) * 10 idx0 = np.random.choice(range(n0), size=n) idx1 = np.random.choice(range(n1), size=n) # b -- b...
479,515
Return the derivatives of the cost function for predictions. Args: w (array of float): weight vectors such that: w[:-h1] -- weights between the input and h layers w[-h1:] -- weights between the h and output layers args: features (args[0]) and target (args...
def fprime(self, w, *args): x0 = args[0] x1 = args[1] n0 = x0.shape[0] n1 = x1.shape[0] # n -- number of pairs to evaluate n = max(n0, n1) * 10 idx0 = np.random.choice(range(n0), size=n) idx1 = np.random.choice(range(n1), size=n) # b -...
479,516
Normalize numerical columns. Args: X (numpy.array) : numerical columns to normalize Returns: X (numpy.array): normalized numerical columns
def transform(self, X): for col in range(X.shape[1]): X[:, col] = self._transform_col(X[:, col], col) return X
479,520
Normalize numerical columns. Args: X (numpy.array) : numerical columns to normalize Returns: X (numpy.array): normalized numerical columns
def fit_transform(self, X, y=None): self.ecdfs = [None] * X.shape[1] for col in range(X.shape[1]): self.ecdfs[col] = ECDF(X[:, col]) X[:, col] = self._transform_col(X[:, col], col) return X
479,521
Normalize one numerical column. Args: x (numpy.array): a numerical column to normalize col (int): column index Returns: A normalized feature vector.
def _transform_col(self, x, col): return norm.ppf(self.ecdfs[col](x) * .998 + .001)
479,522
Return a mapping from values and its maximum of a column to integer labels. Args: x (pandas.Series): a categorical column to encode. Returns: label_encoder (dict): mapping from values of features to integers max_label (int): maximum label
def _get_label_encoder_and_max(self, x): # NaN cannot be used as a key for dict. So replace it with a random integer. label_count = x.fillna(NAN_INT).value_counts() n_uniq = label_count.shape[0] label_count = label_count[label_count >= self.min_obs] n_uniq_new = label_...
479,523
Encode one categorical column into labels. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: x (pandas.Series): a column with labels.
def _transform_col(self, x, i): return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)
479,524
Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: X (pandas.DataFrame): label encoded columns
def transform(self, X): for i, col in enumerate(X.columns): X.loc[:, col] = self._transform_col(X[col], i) return X
479,526
Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: X (pandas.DataFrame): label encoded columns
def fit_transform(self, X, y=None): self.label_encoders = [None] * X.shape[1] self.label_maxes = [None] * X.shape[1] for i, col in enumerate(X.columns): self.label_encoders[i], self.label_maxes[i] = \ self._get_label_encoder_and_max(X[col]) X.l...
479,527
Initialize the OneHotEncoder class object. Args: min_obs (int): minimum number of observation to create a dummy variable label_encoder (LabelEncoder): LabelEncoder that transofrm
def __init__(self, min_obs=10): self.min_obs = min_obs self.label_encoder = LabelEncoder(min_obs)
479,528
Encode one categorical column into sparse matrix with one-hot-encoding. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: X (scipy.sparse.coo_matrix): sparse matrix encoding a categorical ...
def _transform_col(self, x, i): labels = self.label_encoder._transform_col(x, i) label_max = self.label_encoder.label_maxes[i] # build row and column index for non-zero values of a sparse matrix index = np.array(range(len(labels))) i = index[labels > 0] j = lab...
479,529
Encode categorical columns into sparse matrix with one-hot-encoding. Args: X (pandas.DataFrame): categorical columns to encode Returns: X_new (scipy.sparse.coo_matrix): sparse matrix encoding categorical variables into dummy variable...
def transform(self, X): for i, col in enumerate(X.columns): X_col = self._transform_col(X[col], i) if X_col is not None: if i == 0: X_new = X_col else: X_new = sparse.hstack((X_new, X_col)) log...
479,530
Return a mapping from categories to average target values. Args: x (pandas.Series): a categorical column to encode. y (pandas.Series): the target column Returns: target_encoder (dict): mapping from categories to average target values
def _get_target_encoder(self, x, y): assert len(x) == len(y) # NaN cannot be used as a key for dict. So replace it with a random integer df = pd.DataFrame({y.name: y, x.name: x.fillna(NAN_INT)}) return df.groupby(x.name)[y.name].mean().to_dict()
479,531
Encode one categorical column into average target values. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: x (pandas.Series): a column with labels.
def _transform_col(self, x, i): return x.fillna(NAN_INT).map(self.target_encoders[i]).fillna(self.target_mean)
479,532
Encode categorical columns into average target values. Args: X (pandas.DataFrame): categorical columns to encode y (pandas.Series): the target column Returns: X (pandas.DataFrame): encoded columns
def fit(self, X, y): self.target_encoders = [None] * X.shape[1] self.target_mean = y.mean() for i, col in enumerate(X.columns): self.target_encoders[i] = self._get_target_encoder(X[col], y) return self
479,533
Encode categorical columns into average target values. Args: X (pandas.DataFrame): categorical columns to encode y (pandas.Series): the target column Returns: X (pandas.DataFrame): encoded columns
def fit_transform(self, X, y): self.target_encoders = [None] * X.shape[1] self.target_mean = y.mean() for i, col in enumerate(X.columns): self.target_encoders[i] = self._get_target_encoder(X[col], y) X.loc[:, col] = X[col].fillna(NAN_INT).map(self.target_encode...
479,534
Combine predictions with the optimal weights to minimize RMSE. Args: es (list of float): RMSEs of predictions ps (list of np.array): predictions e0 (float): RMSE of all zero prediction l (float): lambda as in the ridge regression Returns: Ensemble prediction (np.array) ...
def netflix(es, ps, e0, l=.0001): m = len(es) n = len(ps[0]) X = np.stack(ps).T pTy = .5 * (n * e0**2 + (X**2).sum(axis=0) - n * np.array(es)**2) w = np.linalg.pinv(X.T.dot(X) + l * n * np.eye(m)).dot(pTy) return X.dot(w), w
479,542
Save data as a CSV, LibSVM or HDF5 file based on the file extension. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. If None, all zero vector will be saved. path (str): Path to the CSV, LibSVM or HDF5 file to save data.
def save_data(X, y, path): catalog = {'.csv': save_csv, '.sps': save_libsvm, '.h5': save_hdf5} ext = os.path.splitext(path)[1] func = catalog[ext] if y is None: y = np.zeros((X.shape[0], )) func(X, y, path)
479,543
Save data as a CSV file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the CSV file to save data.
def save_csv(X, y, path): if sparse.issparse(X): X = X.todense() np.savetxt(path, np.hstack((y.reshape((-1, 1)), X)), delimiter=',')
479,544
Save data as a LibSVM file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the CSV file to save data.
def save_libsvm(X, y, path): dump_svmlight_file(X, y, path, zero_based=False)
479,545
Save data as a HDF5 file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the HDF5 file to save data.
def save_hdf5(X, y, path): with h5py.File(path, 'w') as f: is_sparse = 1 if sparse.issparse(X) else 0 f['issparse'] = is_sparse f['target'] = y if is_sparse: if not sparse.isspmatrix_csr(X): X = X.tocsr() f['shape'] = np.array(X.shape) ...
479,546
Load data from a CSV, LibSVM or HDF5 file based on the file extension. Args: path (str): A path to the CSV, LibSVM or HDF5 format file containing data. dense (boolean): An optional variable indicating if the return matrix should be dense. By default, it is false. Retu...
def load_data(path, dense=False): catalog = {'.csv': load_csv, '.sps': load_svmlight_file, '.h5': load_hdf5} ext = os.path.splitext(path)[1] func = catalog[ext] X, y = func(path) if dense and sparse.issparse(X): X = X.todense() return X, y
479,547
Load data from a CSV file. Args: path (str): A path to the CSV format file containing data. dense (boolean): An optional variable indicating if the return matrix should be dense. By default, it is false. Returns: Data matrix X and target vector y
def load_csv(path): with open(path) as f: line = f.readline().strip() X = np.loadtxt(path, delimiter=',', skiprows=0 if is_number(line.split(',')[0]) else 1) y = np.array(X[:, 0]).flatten() X = X[:, 1:] return X, y
479,548
Load data from a HDF5 file. Args: path (str): A path to the HDF5 format file containing data. dense (boolean): An optional variable indicating if the return matrix should be dense. By default, it is false. Returns: Data matrix X and target vector y
def load_hdf5(path): with h5py.File(path, 'r') as f: is_sparse = f['issparse'][...] if is_sparse: shape = tuple(f['shape'][...]) data = f['data'][...] indices = f['indices'][...] indptr = f['indptr'][...] X = sparse.csr_matrix((data, ...
479,549
Read a LibSVM file line-by-line. Args: path (str): A path to the LibSVM file to read. Yields: data (list) and target (int).
def read_sps(path): for line in open(path): # parse x xs = line.rstrip().split(' ') yield xs[1:], int(xs[0])
479,550
Mean Absolute Percentage Error (MAPE). Args: y (numpy.array): target p (numpy.array): prediction Returns: e (numpy.float64): MAPE
def mape(y, p): filt = np.abs(y) > EPS return np.mean(np.abs(1 - p[filt] / y[filt]))
479,568
Root Mean Squared Error (RMSE). Args: y (numpy.array): target p (numpy.array): prediction Returns: e (numpy.float64): RMSE
def rmse(y, p): # check and get number of samples assert y.shape == p.shape return np.sqrt(mse(y, p))
479,569
Normalized Gini Coefficient. Args: y (numpy.array): target p (numpy.array): prediction Returns: e (numpy.float64): normalized Gini coefficient
def gini(y, p): # check and get number of samples assert y.shape == p.shape n_samples = y.shape[0] # sort rows on prediction column # (from largest to smallest) arr = np.array([y, p]).transpose() true_order = arr[arr[:,0].argsort()][::-1,0] pred_order = arr[arr[:,1].argsort()][::...
479,570
Bounded log loss error. Args: y (numpy.array): target p (numpy.array): prediction Returns: bounded log loss error
def logloss(y, p): p[p < EPS] = EPS p[p > 1 - EPS] = 1 - EPS return log_loss(y, p)
479,575
Fetches course details. Args: course_id (str): An edx course id. Returns: CourseDetail
def get_detail(self, course_id): # the request is done in behalf of the current logged in user resp = self._requester.get( urljoin( self._base_url, '/api/courses/v1/courses/{course_key}/'.format(course_key=course_id) ) ) r...
481,522
Fetches course blocks. Args: course_id (str): An edx course id. username (str): username of the user to query for (can reveal hidden modules) Returns: Structure
def course_blocks(self, course_id, username): resp = self.requester.get( urljoin(self.base_url, '/api/courses/v1/blocks/'), params={ "depth": "all", "username": username, "course_id": course_id, "requested_fields": ...
481,525
Returns an CurrentGrade object for the user in a course Args: username (str): an edx user's username course_id (str): an edX course id. Returns: CurrentGrade: object representing the student current grade for a course
def get_student_current_grade(self, username, course_id): # the request is done in behalf of the current logged in user resp = self.requester.get( urljoin( self.base_url, '/api/grades/v1/courses/{course_key}/?username={username}'.format( ...
481,526
Returns a CurrentGradesByUser object with the user current grades. Args: username (str): an edx user's username course_ids (list): a list of edX course ids. Returns: CurrentGradesByUser: object representing the student current grades
def get_student_current_grades(self, username, course_ids=None): # if no course ids are provided, let's get the user enrollments if course_ids is None: enrollments_client = CourseEnrollments(self.requester, self.base_url) enrollments = enrollments_client.get_student_enro...
481,527
Returns a CurrentGradesByCourse object for all users in the specified course. Args: course_id (str): an edX course ids. Returns: CurrentGradesByCourse: object representing the student current grades Authorization: The authenticated user must have staff perm...
def get_course_current_grades(self, course_id): resp = self.requester.get( urljoin( self.base_url, '/api/grades/v1/courses/{course_key}/'.format(course_key=course_id) ) ) resp.raise_for_status() resp_json = resp.json() ...
481,528
Creates a CCX Args: master_course_id (str): edx course id of the master course coach_email (str): email of the user to make a coach. This user must exist on edx. max_students_allowed (int): Maximum number of students to allow in this ccx. title (str): Title of th...
def create(self, master_course_id, coach_email, max_students_allowed, title, modules=None): payload = { 'master_course_id': master_course_id, 'coach_email': coach_email, 'max_students_allowed': max_students_allowed, 'display_name': title, } ...
481,531
Creates an audit enrollment for the user in a given course Args: course_id (str): an edX course id Returns: Enrollment: object representing the student enrollment in the provided course
def create_audit_student_enrollment(self, course_id): audit_enrollment = { "mode": "audit", "course_details": {"course_id": course_id} } # the request is done in behalf of the current logged in user resp = self.requester.post( urljoin(self.bas...
481,535
Returns an Certificate object with the user certificates Args: username (str): an edx user's username course_id (str): an edX course id. Returns: Certificate: object representing the student certificate for a course
def get_student_certificate(self, username, course_id): # the request is done in behalf of the current logged in user resp = self.requester.get( urljoin( self.base_url, '/api/certificates/v0/certificates/{username}/courses/{course_key}/'.format( ...
481,536
Returns an Certificates object with the user certificates Args: username (str): an edx user's username course_ids (list): a list of edX course ids. Returns: Certificates: object representing the student certificates for a course
def get_student_certificates(self, username, course_ids=None): # if no course ids are provided, let's get the user enrollments if course_ids is None: enrollments_client = CourseEnrollments(self.requester, self.base_url) enrollments = enrollments_client.get_student_enroll...
481,537