file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
main.ts
'use strict'; import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocuments, TextDocument, DiagnosticSeverity, Diagnostic, InitializeResult, TextDocumentPositionParams, CompletionItem, CompletionItemKind } from 'vscode-languageserver'; var SwaggerParser = require('swagger-parse...
} catch (err) { // if parsing the document fails try looking for the swagger key var sourceText = document.getText().toLowerCase(); // if the swagger key is present, assume this is a swagger file // and formatting or syntax errors prevent parsing. if (sourceText.indexOf("...
{ return resultObj; }
conditional_block
main.ts
'use strict'; import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocuments, TextDocument, DiagnosticSeverity, Diagnostic, InitializeResult, TextDocumentPositionParams, CompletionItem, CompletionItemKind } from 'vscode-languageserver'; var SwaggerParser = require('swagger-parse...
(textDocument: TextDocument): void { var swaggerObj = validateSwaggerSyntax(textDocument); if (!swaggerObj) { return; } SwaggerParser.validate(swaggerObj) .then(function (_api: any) { // empty the diagnostics information since swagger defintion seems to be correct ...
validateTextDocument
identifier_name
main.ts
'use strict'; import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocuments, TextDocument, DiagnosticSeverity, Diagnostic, InitializeResult, TextDocumentPositionParams, CompletionItem, CompletionItemKind } from 'vscode-languageserver'; var SwaggerParser = require('swagger-parse...
function validateTextDocument(textDocument: TextDocument): void { var swaggerObj = validateSwaggerSyntax(textDocument); if (!swaggerObj) { return; } SwaggerParser.validate(swaggerObj) .then(function (_api: any) { // empty the diagnostics information since swagger defintio...
{ let diagnostics: Diagnostic[] = []; try { var resultObj: Object; switch (document.languageId) { case "json": { // try parsing it resultObj = JSON.parse(document.getText()); } case "yaml": case "yml": { ...
identifier_body
main.ts
'use strict'; import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocuments, TextDocument, DiagnosticSeverity, Diagnostic, InitializeResult, TextDocumentPositionParams, CompletionItem, CompletionItemKind } from 'vscode-languageserver'; var SwaggerParser = require('swagger-parse...
try { var resultObj: Object; switch (document.languageId) { case "json": { // try parsing it resultObj = JSON.parse(document.getText()); } case "yaml": case "yml": { // try parsing it re...
function validateSwaggerSyntax(document: TextDocument): Object { let diagnostics: Diagnostic[] = [];
random_line_split
preprocess.py
# -*- coding: utf-8 -*- from __future__ import division #division en flottants par défaut # Preprocessing primitives import os import numpy as np import octaveIO as oio import subprocess as sp from sklearn import mixture import string def gmm(x, nbG): g=mixture.GMM(n_components=nbG) g.fit(x) return g de...
f (verbose >= 1): print 'Enter preprocess' if not os.path.exists(dataDir): print 'Missing data' return [], {}, [], [], {} else: nbC2=nbC mfccs=[] #contiendra l'ensemble des mfccs mfccMatching={} mu=[] pi=[] gmmMatching={} numM=0 ...
identifier_body
preprocess.py
# -*- coding: utf-8 -*- from __future__ import division #division en flottants par défaut # Preprocessing primitives import os import numpy as np import octaveIO as oio import subprocess as sp from sklearn import mixture import string def gmm(x, nbG): g=mixture.GMM(n_components=nbG) g.fit(x) return g de...
else: nbC2=nbC mfccs=[] #contiendra l'ensemble des mfccs mfccMatching={} mu=[] pi=[] gmmMatching={} numM=0 numG=0 for root, dirs, files in os.walk(dataDir): for file in files: if file.endswith('.wav'): ...
rint 'Missing data' return [], {}, [], [], {}
conditional_block
preprocess.py
# -*- coding: utf-8 -*- from __future__ import division #division en flottants par défaut # Preprocessing primitives import os import numpy as np import octaveIO as oio import subprocess as sp from sklearn import mixture import string def gmm(x, nbG): g=mixture.GMM(n_components=nbG) g.fit(x) return g de...
if (verbose >= 2): print newvf, nbG g = gmm(newvf, nbG) if (verbose >= 1): print 'Done' mu_j = g.means pi_j = g.weig...
print 'Computing GMM fitting...' print str(nbC)+' points for '+str(nbG)+' gaussians'
random_line_split
preprocess.py
# -*- coding: utf-8 -*- from __future__ import division #division en flottants par défaut # Preprocessing primitives import os import numpy as np import octaveIO as oio import subprocess as sp from sklearn import mixture import string def g
x, nbG): g=mixture.GMM(n_components=nbG) g.fit(x) return g def mfcc(wavFile, verbose=0): mfccFile='data/tmpmfcc.mat' command=['octave', '--silent', '--eval','cepstraux('+'\''+wavFile+'\',\''+mfccFile+'\')'] if (verbose >= 2): print string.join(command) sp.call(command) c=oio.ret...
mm(
identifier_name
testsettings.py
# This file is exec'd from settings.py, so it has access to and can # modify all the variables in settings.py. # If this file is changed in development, the development server will # have to be manually restarted because changes will not be noticed # immediately. DEBUG = False ALLOWED_HOSTS = ["*"] # disable compress...
# for unit tests, that swap test connection in for default HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS # secret key added as a travis build step
'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores', } }
random_line_split
mini_dateutil.py
# This module is a very stripped down version of the dateutil # package for when dateutil has not been installed. As a replacement # for dateutil.parser.parse, the parsing methods from # http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/ #As such, the following copyri...
def tzname(self, dt): return self._name def __eq__(self, other): return (isinstance(other, tzoffset) and self._offset == other._offset) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): retu...
return ZERO
identifier_body
mini_dateutil.py
# This module is a very stripped down version of the dateutil # package for when dateutil has not been installed. As a replacement # for dateutil.parser.parse, the parsing methods from # http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/ #As such, the following copyri...
return _fixed_offset_tzs[offsetmins] _iso8601_parser = re.compile(""" ^ (?P<year> [0-9]{4})?(?P<ymdsep>-?)? (?P<month>[0-9]{2})?(?P=ymdsep)? (?P<day> [0-9]{2})? (?: # time part... optional... at least hour must be specified (?:T|\s+)? (?P<hou...
if offsetmins < 0: sign = '-' absoff = -offsetmins else: sign = '+' absoff = offsetmins name = "UTC%s%02d:%02d" % (sign, int(absoff / 60), absoff % 60) inst = tzoffset(offsetmins, name) _fixed_offset_tzs[off...
conditional_block
mini_dateutil.py
# This module is a very stripped down version of the dateutil # package for when dateutil has not been installed. As a replacement # for dateutil.parser.parse, the parsing methods from # http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/ #As such, the following copyri...
# dateutil - Extensions to the standard python 2.3+ datetime module. # # Copyright (c) 2003-2011 - Gustavo Niemeyer <gustavo@niemeyer.net> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # ...
random_line_split
mini_dateutil.py
# This module is a very stripped down version of the dateutil # package for when dateutil has not been installed. As a replacement # for dateutil.parser.parse, the parsing methods from # http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/ #As such, the following copyri...
(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name = name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): r...
__repr__
identifier_name
events.rs
#[derive(Clone, Debug, Copy)] pub enum Event { /// The size of the window has changed. Resized(u32, u32), /// The position of the window has changed. Moved(i32, i32), /// The window has been closed. Closed, /// The window received a unicode character. ReceivedCharacter(char), ///...
{ Pressed, Released, } #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum MouseButton { Left, Right, Middle, Other(u8), } #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum VirtualKeyCode { /// The '1' key over the letters. Key1, /// The '2' key over the letters....
ElementState
identifier_name
events.rs
#[derive(Clone, Debug, Copy)] pub enum Event { /// The size of the window has changed. Resized(u32, u32), /// The position of the window has changed. Moved(i32, i32), /// The window has been closed. Closed, /// The window received a unicode character. ReceivedCharacter(char), ///...
G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, /// The Escape key, next to F1. Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, ...
C, D, E, F,
random_line_split
mod.rs
use std::default::Default; use std::fs::File;
use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn run() -> i32 { let mut container: String = "".to_string(); let mut setti...
use std::path::Path;
random_line_split
mod.rs
use std::default::Default; use std::fs::File; use std::path::Path; use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn run() -> i32 ...
Err(e) => { error!("Error writing hash: {}", e); return 1; } } return 0; } pub fn main() { let val = run(); exit(val); }
{}
conditional_block
mod.rs
use std::default::Default; use std::fs::File; use std::path::Path; use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn run() -> i32
pub fn main() { let val = run(); exit(val); }
{ let mut container: String = "".to_string(); let mut settings: Settings = Default::default(); { let mut ap = ArgumentParser::new(); ap.set_description(" A tool which versions containers "); ap.refer(&mut container) .add_argument("container", Store, ...
identifier_body
mod.rs
use std::default::Default; use std::fs::File; use std::path::Path; use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn
() -> i32 { let mut container: String = "".to_string(); let mut settings: Settings = Default::default(); { let mut ap = ArgumentParser::new(); ap.set_description(" A tool which versions containers "); ap.refer(&mut container) .add_argument("container...
run
identifier_name
common.py
"""Elmax integration common classes and utilities.""" from __future__ import annotations from datetime import timedelta import logging from logging import Logger import async_timeout from elmax_api.exceptions import ( ElmaxApiError, ElmaxBadLoginError, ElmaxBadPinError, ElmaxNetworkError, ) from elmax...
except ElmaxBadPinError as err: raise ConfigEntryAuthFailed("Control panel pin was refused") from err except ElmaxBadLoginError as err: raise ConfigEntryAuthFailed("Refused username/password") from err except ElmaxApiError as err: raise UpdateFailed(f"Error c...
return status # Otherwise, return None. Listeners will know that this means the device is offline return None
random_line_split
common.py
"""Elmax integration common classes and utilities.""" from __future__ import annotations from datetime import timedelta import logging from logging import Logger import async_timeout from elmax_api.exceptions import ( ElmaxApiError, ElmaxBadLoginError, ElmaxBadPinError, ElmaxNetworkError, ) from elmax...
@property def panel_entry(self) -> PanelEntry | None: """Return the panel entry.""" return self._panel_entry def get_actuator_state(self, actuator_id: str) -> Actuator: """Return state of a specific actuator.""" if self._state_by_endpoint is not None: return se...
"""Instantiate the object.""" self._client = Elmax(username=username, password=password) self._panel_id = panel_id self._panel_pin = panel_pin self._panel_entry = None self._state_by_endpoint = None super().__init__( hass=hass, logger=logger, name=name, update...
identifier_body
common.py
"""Elmax integration common classes and utilities.""" from __future__ import annotations from datetime import timedelta import logging from logging import Logger import async_timeout from elmax_api.exceptions import ( ElmaxApiError, ElmaxBadLoginError, ElmaxBadPinError, ElmaxNetworkError, ) from elmax...
# Otherwise, return None. Listeners will know that this means the device is offline return None except ElmaxBadPinError as err: raise ConfigEntryAuthFailed("Control panel pin was refused") from err except ElmaxBadLoginError as err: raise ConfigE...
status = await self._client.get_panel_status( control_panel_id=panel.hash, pin=self._panel_pin ) # type: PanelStatus # Store a dictionary for fast endpoint state access self._state_by_endpoint = { k.endpoint_id...
conditional_block
common.py
"""Elmax integration common classes and utilities.""" from __future__ import annotations from datetime import timedelta import logging from logging import Logger import async_timeout from elmax_api.exceptions import ( ElmaxApiError, ElmaxBadLoginError, ElmaxBadPinError, ElmaxNetworkError, ) from elmax...
(self): """Return the current http client being used by this instance.""" return self._client async def _async_update_data(self): try: async with async_timeout.timeout(DEFAULT_TIMEOUT): # Retrieve the panel online status first panels = await self....
http_client
identifier_name
PackagePool.py
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- import string import copy import os import gzip import gtk import commands try: from backports import lzma except ImportError: from lzma import LZMAFile as lzma import singletons from common import * import common; _ = common._ from Source import * from Pack...
elif c != '\\': name += c prev_chr = c return name file = open('/etc/urpmi/urpmi.cfg') sources = [] word = '' flag0 = False flag1 = False name_flag = False while 1: c = file.read(1...
if prev_chr == '\\': name += ' ' else: break
conditional_block
PackagePool.py
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- import string import copy import os import gzip import gtk import commands try: from backports import lzma except ImportError: from lzma import LZMAFile as lzma import singletons from common import * import common; _ = common._ from Source import * from Pack...
(self): """Reinitialize the inner state of the package pool. Must be called in case of manipulating the package registry.""" self.initialized = False self.all_packages = [] self.package_name_pool = {} self.installed_package_names = {} singletons.application.D...
Init
identifier_name
PackagePool.py
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- import string import copy import os import gzip import gtk import commands try: from backports import lzma except ImportError: from lzma import LZMAFile as lzma import singletons from common import * import common; _ = common._ from Source import * from Pack...
name_flag = True elif name_flag == True and c not in ['\\', '\n']: word += c return sources def GetActiveSources(self, new=False): """Return the active Source objects.""" if new: all_sources = self.GetSources() else: ...
if flag1 == False: flag1 = True name_flag = True else:
random_line_split
PackagePool.py
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- import string import copy import os import gzip import gtk import commands try: from backports import lzma except ImportError: from lzma import LZMAFile as lzma import singletons from common import * import common; _ = common._ from Source import * from Pack...
file = open('/etc/urpmi/urpmi.cfg') sources = [] word = '' flag0 = False flag1 = False name_flag = False while 1: c = file.read(1) if c == '': break elif c == '{': if flag0 == False: ...
"""Extract the source name from the line of the file.""" prev_chr = line[0] name = line[0] for c in line[1:-1]: if c == ' ': if prev_chr == '\\': name += ' ' else: break ...
identifier_body
lumina-terminal_en_ZA.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="en_ZA"> <context> <name>TrayIcon</name> <message> <location filename="../TrayIcon.cpp" line="123"/> <source>Trigger Terminal</source> <translation type="unfinished"></translation> </message> <message...
<location filename="../TrayIcon.cpp" line="130"/> <source>Close Terminal</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TrayIcon.cpp" line="139"/> <source>Move To Monitor</source> <translation type="unfinished"><...
random_line_split
index.js
import React from 'react'; import { connect } from 'react-redux'; import { Modal, Button, Header, Form } from 'semantic-ui-react'; import copyToClipboard from 'copy-to-clipboard'; import { isModalOpen } from '../../store/selectors/viewModal'; import { selectData } from '../../store/selectors/edited'; import { closeModa...
> <Header content="JSON Data" /> <Modal.Content className="view-json-modal_content"> <Form size="large"> <Form.Group> <Form.TextArea width={16} disabled autoHeight ...
open={props.isModalOpen}
random_line_split
test_configexc.py
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Sof...
(): """Get a ConfigFileErrors object.""" err1 = configexc.ConfigErrorDesc("Error text 1", Exception("Exception 1")) err2 = configexc.ConfigErrorDesc("Error text 2", Exception("Exception 2"), "Fake traceback") return configexc.ConfigFileErrors("config.py", [err1, err2...
errors
identifier_name
test_configexc.py
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Sof...
@pytest.fixture def errors(): """Get a ConfigFileErrors object.""" err1 = configexc.ConfigErrorDesc("Error text 1", Exception("Exception 1")) err2 = configexc.ConfigErrorDesc("Error text 2", Exception("Exception 2"), "Fake traceback") return configexc.ConfigFileEr...
"""Test ConfigErrorDesc.with_text.""" old = configexc.ConfigErrorDesc("Error text", Exception("Exception text")) new = old.with_text("additional text") assert str(new) == 'Error text (additional text): Exception text'
identifier_body
test_configexc.py
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Sof...
configexc.NoOptionError('opt', deleted=True, renamed='foo') def test_backend_error(): e = configexc.BackendError(usertypes.Backend.QtWebKit) assert str(e) == "This setting is not available with the QtWebKit backend!" def test_desc_with_text(): """Test ConfigErrorDesc.with_text.""" old = conf...
random_line_split
RF_adult_income.py
# import libraries: dataframe manipulation, machine learning, os tools from pandas import Series, DataFrame import pandas as pd import numpy as np import os import matplotlib.pylab as plt from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import cl...
plt.cla() plt.plot(trees, accuracy)
classifier=RandomForestClassifier(n_estimators=idx + 1) classifier=classifier.fit(pred_train,tar_train) predictions=classifier.predict(pred_test) accuracy[idx]=sklearn.metrics.accuracy_score(tar_test, predictions)
conditional_block
RF_adult_income.py
# import libraries: dataframe manipulation, machine learning, os tools from pandas import Series, DataFrame import pandas as pd import numpy as np import os import matplotlib.pylab as plt from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import cl...
""" Running a different number of trees and see the effect of that on the accuracy of the prediction """ trees=range(25) accuracy=np.zeros(25) for idx in range(len(trees)): classifier=RandomForestClassifier(n_estimators=idx + 1) classifier=classifier.fit(pred_train,tar_train) predictions=classifier.predict...
max_val = np.where(model.feature_importances_ == max(model.feature_importances_)) min_val = np.where(model.feature_importances_ == min(model.feature_importances_)) print(max_val, min_val)
random_line_split
actorref.rs
///A reference to a spawned actorpub trait ActorRef { } pub trait ActorRef{ } ///Spawned actor reference with port and channel pub struct ActorRefWithStream<P2, C1> { port: P2, chan: C1, } impl <T1: Send, T2: Send, C1: GenericChan<T1>, P2: GenericPort<T2>> ActorRef for ActorRefWithStream<P2, C1> {} /...
<C1>{ chan: C1, } impl<T1: Send, C1: GenericChan<T1>> ActorRef for ActorRefWithChan<C1>{} ///Spawned actor reference with port pub struct ActorRefWithPort<P2>{ port: P2, } impl<T2: Send, P2: GenericPort<T2>> ActorRef for ActorRefWithPort<P2>{} ///Spawned actor reference with no port and channel pub struct ...
ActorRefWithChan
identifier_name
actorref.rs
///A reference to a spawned actorpub trait ActorRef { } pub trait ActorRef{ } ///Spawned actor reference with port and channel pub struct ActorRefWithStream<P2, C1> { port: P2, chan: C1,
} impl <T1: Send, T2: Send, C1: GenericChan<T1>, P2: GenericPort<T2>> ActorRef for ActorRefWithStream<P2, C1> {} ///Spawned actor reference with channel pub struct ActorRefWithChan<C1>{ chan: C1, } impl<T1: Send, C1: GenericChan<T1>> ActorRef for ActorRefWithChan<C1>{} ///Spawned actor reference with port...
random_line_split
error-handler.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { AppApi } from '../api/app.api'; const HandledErrors = ['HttpErrorResponse']; const DimissedErrors = ['popup_closed_by_user']; const isYoutubeApiError = error => error?.error?.error?....
const errorPayload = isString(sanitizedError) ? { message: error } : { message: `${error?.message}\n${error?.error?.error?.message}` }; appApi.notifyError(errorPayload); } } }
: error; console.error('There was an ERROR:', error);
random_line_split
error-handler.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { AppApi } from '../api/app.api'; const HandledErrors = ['HttpErrorResponse']; const DimissedErrors = ['popup_closed_by_user']; const isYoutubeApiError = error => error?.error?.error?....
}
{ const appApi = this.injector.get(AppApi); if (!DimissedErrors.includes(error.name)) { const sanitizedError = isYoutubeApiError(error) ? error.error.error.errors[0] : error; console.error('There was an ERROR:', error); const errorPayload = isString(sanitizedError) ? { message:...
identifier_body
error-handler.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { AppApi } from '../api/app.api'; const HandledErrors = ['HttpErrorResponse']; const DimissedErrors = ['popup_closed_by_user']; const isYoutubeApiError = error => error?.error?.error?....
(private injector: Injector) {} handleError(error: Error | HttpErrorResponse | any) { const appApi = this.injector.get(AppApi); if (!DimissedErrors.includes(error.name)) { const sanitizedError = isYoutubeApiError(error) ? error.error.error.errors[0] : error; console.error('There w...
constructor
identifier_name
error-handler.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { AppApi } from '../api/app.api'; const HandledErrors = ['HttpErrorResponse']; const DimissedErrors = ['popup_closed_by_user']; const isYoutubeApiError = error => error?.error?.error?....
} }
{ const sanitizedError = isYoutubeApiError(error) ? error.error.error.errors[0] : error; console.error('There was an ERROR:', error); const errorPayload = isString(sanitizedError) ? { message: error } : { message: `${error?.message}\n${error?.error?.error?.message}` }; appApi.not...
conditional_block
colour.js
/** * Visual Blocks Editor * * Copyright 2012 Google Inc. * http://blockly.googlecode.com/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICEN...
}; Blockly.Blocks['colour_blend'] = { // Blend two colours together. init: function() { this.setHelpUrl(Blockly.Msg.COLOUR_BLEND_HELPURL); this.setColour(20); this.appendValueInput('COLOUR1') .setCheck('Colour') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEN...
}
random_line_split
sub-app.ts
declare const faker: any; interface IDemoItem { firstLetter: string; name: string; color: string; phone: string; country: string; } export class MultipleListsDemoRoute { objectArray: IDemoItem[]; numberOfItems: number; isSelected: boolean; readonly parentElement: Element; constructor() { t...
removeItems(count: number) { this.objectArray.splice(0, count); } addItemLast() { this.objectArray.push(this.createItem()); } removeLast() { this.objectArray.pop(); } get itemsCount(): number { return this.objectArray.length; } get childrenCount(): number { return this.parentE...
addItemFirst() { this.objectArray.unshift(this.createItem()); }
random_line_split
sub-app.ts
declare const faker: any; interface IDemoItem { firstLetter: string; name: string; color: string; phone: string; country: string; } export class MultipleListsDemoRoute { objectArray: IDemoItem[]; numberOfItems: number; isSelected: boolean; readonly parentElement: Element; constructor() { t...
addItemLast() { this.objectArray.push(this.createItem()); } removeLast() { this.objectArray.pop(); } get itemsCount(): number { return this.objectArray.length; } get childrenCount(): number { return this.parentElement ? this.parentElement.children.length : 0; } click(item: IDemoI...
{ this.objectArray.splice(0, count); }
identifier_body
sub-app.ts
declare const faker: any; interface IDemoItem { firstLetter: string; name: string; color: string; phone: string; country: string; } export class MultipleListsDemoRoute { objectArray: IDemoItem[]; numberOfItems: number; isSelected: boolean; readonly parentElement: Element; constructor() { t...
() { this.objectArray.unshift(this.createItem()); } removeItems(count: number) { this.objectArray.splice(0, count); } addItemLast() { this.objectArray.push(this.createItem()); } removeLast() { this.objectArray.pop(); } get itemsCount(): number { return this.objectArray.length; ...
addItemFirst
identifier_name
sub-app.ts
declare const faker: any; interface IDemoItem { firstLetter: string; name: string; color: string; phone: string; country: string; } export class MultipleListsDemoRoute { objectArray: IDemoItem[]; numberOfItems: number; isSelected: boolean; readonly parentElement: Element; constructor() { t...
} addItemFirst() { this.objectArray.unshift(this.createItem()); } removeItems(count: number) { this.objectArray.splice(0, count); } addItemLast() { this.objectArray.push(this.createItem()); } removeLast() { this.objectArray.pop(); } get itemsCount(): number { return this.ob...
{ this.objectArray.push(this.createItem()); }
conditional_block
phantom-data-is-structurally-matchable.rs
// run-pass // This file checks that `PhantomData` is considered structurally matchable. use std::marker::PhantomData; fn main() { let mut count = 0; // A type which is not structurally matchable: struct NotSM; // And one that is: #[derive(PartialEq, Eq)] struct SM; // Check that SM is...
{ alpha: PhantomData<NotSM>, beta: PhantomData<SM>, } const CFOO: Foo = Foo { alpha: PhantomData, beta: PhantomData, }; match Foo::default() { CFOO => count += 1, }; // Final count must be 4 now if all assert_eq!(count, 4); }
Foo
identifier_name
phantom-data-is-structurally-matchable.rs
// run-pass // This file checks that `PhantomData` is considered structurally matchable. use std::marker::PhantomData; fn main()
{ let mut count = 0; // A type which is not structurally matchable: struct NotSM; // And one that is: #[derive(PartialEq, Eq)] struct SM; // Check that SM is #[structural_match]: const CSM: SM = SM; match SM { CSM => count += 1, }; // Check that PhantomData<T> is ...
identifier_body
phantom-data-is-structurally-matchable.rs
// run-pass // This file checks that `PhantomData` is considered structurally matchable. use std::marker::PhantomData; fn main() { let mut count = 0; // A type which is not structurally matchable: struct NotSM; // And one that is: #[derive(PartialEq, Eq)] struct SM; // Check that SM is...
alpha: PhantomData, beta: PhantomData, }; match Foo::default() { CFOO => count += 1, }; // Final count must be 4 now if all assert_eq!(count, 4); }
alpha: PhantomData<NotSM>, beta: PhantomData<SM>, } const CFOO: Foo = Foo {
random_line_split
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, e...
() { let module = r#" /// This is the test function let test x = x { test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![doc::Field { name: "test".to_string(), args: vec![doc::Argument { implicit:...
basic
identifier_name
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, e...
doc::generate_for_path(&new_vm(), "../std", out).unwrap_or_else(|err| panic!("{}", err)); let out = fs::canonicalize(out).unwrap(); let errors = cargo_deadlinks::unavailable_urls( &out, &cargo_deadlinks::CheckContext { check_http: true }, ) .collect::<Vec<_>>(); assert!(errors...
{ fs::remove_dir_all(out).unwrap_or_else(|err| panic!("{}", err)); }
conditional_block
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, e...
#[test] fn doc_hidden() { let module = r#" #[doc(hidden)] type Test = Int #[doc(hidden)] let test x = x { Test, test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![], }, ); } #[test] fn check_links() { let _ = env_logger::try_ini...
{ let module = r#" /// This is the test function let test x = x { test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![doc::Field { name: "test".to_string(), args: vec![doc::Argument { implicit: fa...
identifier_body
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, e...
#[test] fn check_links() { let _ = env_logger::try_init(); let out = Path::new("../target/doc_test"); if out.exists() { fs::remove_dir_all(out).unwrap_or_else(|err| panic!("{}", err)); } doc::generate_for_path(&new_vm(), "../std", out).unwrap_or_else(|err| panic!("{}", err)); let out ...
random_line_split
requests.rs
use std::slice::Iter; use super::{ Request }; pub struct Requests<'a> { request: Option<&'a Request>, requests: Iter<'a, Request>, } impl<'a> Requests<'a> { pub fn new(request: &'a Request, requests: &'a Vec<Request>) -> Requests<'a> { Requests { request: Some(request), requests: requests.iter()...
, (request, _) => request, } } fn size_hint(&self) -> (usize, Option<usize>) { match (self.request, self.requests.size_hint()) { (None, size_hint) => size_hint, (Some(_), (min, max)) => (min + 1, max.map(|max| max + 1)), } } }
{ self.request = None; request }
conditional_block
requests.rs
use std::slice::Iter; use super::{ Request };
} impl<'a> Requests<'a> { pub fn new(request: &'a Request, requests: &'a Vec<Request>) -> Requests<'a> { Requests { request: Some(request), requests: requests.iter(), } } } impl<'a> Iterator for Requests<'a> { type Item = &'a Request; fn next(&mut self) -> Option<&'a Request> { match ...
pub struct Requests<'a> { request: Option<&'a Request>, requests: Iter<'a, Request>,
random_line_split
requests.rs
use std::slice::Iter; use super::{ Request }; pub struct Requests<'a> { request: Option<&'a Request>, requests: Iter<'a, Request>, } impl<'a> Requests<'a> { pub fn
(request: &'a Request, requests: &'a Vec<Request>) -> Requests<'a> { Requests { request: Some(request), requests: requests.iter(), } } } impl<'a> Iterator for Requests<'a> { type Item = &'a Request; fn next(&mut self) -> Option<&'a Request> { match (self.requests.next(), self.request) { ...
new
identifier_name
AppModule1.js
/*----------------------------------------------------------------------------*/ /* (c) 2015 Ivan Reyné Ferrando */ /* */ /* http://ivanreyne.ninja ...
domConstruct, query, Globals) { return declare(null, { /* * scrb: Document: DevelopersGuide * scrb: Chapter: 2.3.2 Application Module1 * scrb: 3 */ /** ...
"app/Globals" ], function ( declare,
random_line_split
AppModule1.js
/*----------------------------------------------------------------------------*/ /* (c) 2015 Ivan Reyné Ferrando */ /* */ /* http://ivanreyne.ninja ...
} }); });
oWhereNode = oWhereNode[0]; domConstruct.place(this.sContent, oWhereNode, "only"); }
conditional_block
Entity.ts
import {EventEmitter} from 'events' import * as events from './events' export enum EntityType { hero, enemy, arrow, trap, home, hblock, vblock, } export enum EntityState { normal, home, die, } export enum Direction { up, right, down, left, } interface IEntityD...
(data: IEntityData) { super() this.i = data.i this.j = data.j this.dir = data.dir this.type = data.type this.state = EntityState.normal } destroy() { this.isDestroy = true this.emit(events.entity.destroy) this.removeAllListeners() } }
constructor
identifier_name
Entity.ts
import {EventEmitter} from 'events' import * as events from './events' export enum EntityType { hero, enemy, arrow, trap, home, hblock, vblock, } export enum EntityState { normal, home, die, } export enum Direction { up, right, down, left, } interface IEntityD...
destroy() { this.isDestroy = true this.emit(events.entity.destroy) this.removeAllListeners() } }
{ super() this.i = data.i this.j = data.j this.dir = data.dir this.type = data.type this.state = EntityState.normal }
identifier_body
Entity.ts
import {EventEmitter} from 'events' import * as events from './events' export enum EntityType { hero, enemy, arrow, trap, home, hblock, vblock, } export enum EntityState { normal, home, die, } export enum Direction { up, right, down, left, } interface IEntityD...
} }
} destroy() { this.isDestroy = true this.emit(events.entity.destroy) this.removeAllListeners()
random_line_split
newlambdas.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert_eq!(f(10, |a| a), 10); g(||{}); }
g(||());
random_line_split
newlambdas.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(f(10, |a| a), 10); g(||{}); }
main
identifier_name
newlambdas.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn g<G>(_g: G) where G: FnOnce() { } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(f(10, |a| a), 10); g(||{}); }
{ f(i) }
identifier_body
region_NF.py
"""Auto-generated file, do not edit by hand. NF metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_NF = PhoneMetadata(id='NF', country_code=672, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[13]\\d{5}', possible_number_pattern='\\...
NumberFormat(pattern='(\\d)(\\d{5})', format='\\1 \\2', leading_digits_pattern=['3'])])
number_format=[NumberFormat(pattern='(\\d{2})(\\d{4})', format='\\1 \\2', leading_digits_pattern=['1']),
random_line_split
zhanzhuanxc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'ByStudent' def zhanzhuanxc(p,q,e): def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def mod...
phi_n = (p - 1) * (q - 1) d = modinv(e, phi_n) return int(d) # print zhanzhuanxc(18443,49891,19)
gcd, x, y = egcd(a, m) if gcd != 1: return None # modular inverse does not exist else: return x % m
identifier_body
zhanzhuanxc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'ByStudent'
m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def modinv(a, m): gcd, x, y = egcd(a, m) if gcd != 1: return None # modular inverse does not exist else: return x % m phi_n = (p - 1) * (q - 1) ...
def zhanzhuanxc(p,q,e): def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a
random_line_split
zhanzhuanxc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'ByStudent' def zhanzhuanxc(p,q,e): def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def mod...
phi_n = (p - 1) * (q - 1) d = modinv(e, phi_n) return int(d) # print zhanzhuanxc(18443,49891,19)
return x % m
conditional_block
zhanzhuanxc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'ByStudent' def zhanzhuanxc(p,q,e): def
(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def modinv(a, m): gcd, x, y = egcd(a, m) if gcd != 1: return None # modular inverse d...
egcd
identifier_name
twitch.ts
export interface TwitchOAuthResponse {
access_token: string; refresh_token: string; expires_in: number; scope: string[]; token_type: string; } export interface HelixUsersData { id: string; login: string; display_name: string; type: string; broadcaster_type: string; description: string; profile_image_url: string; offline_image_url:...
random_line_split
setup.py
#!/usr/bin/python2 # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Nova Billing # Copyright (C) 2010-2012 Grid Dynamics Consulting Services, Inc # All Rights Reserved # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by t...
author_email='openstack@griddynamics.com', url='http://www.griddynamics.com/openstack', packages=find_packages(exclude=['bin', 'smoketests', 'tests']), entry_points={ 'console_scripts': [ 'nova-billing-heart = nova_billing.heart.main:main', 'nova-billing-os-amqp =...
setup(name='nova-billing', version=version_string(), license='GNU LGPL 2.1', description='cloud computing fabric controller', author='Alessio Ababilov, Ivan Kolodyazhny (GridDynamics Openstack Core Team, (c) GridDynamics)',
random_line_split
index.js
/* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */ /* * Copyright 2016, Joyent, Inc. */ var BINDING = require('./lockfd_binding'); function check_arg(pos, name, value, type) { if (typeof (value) !== type) { throw (new Error('argument #' + pos + ' (' + name + ') must be of type ' + type)); } } functi...
(fd, callback) { check_arg(1, 'fd', fd, 'number'); check_arg(2, 'callback', callback, 'function'); BINDING.lock_fd(fd, 'write', false, function (ret, errmsg, errno) { var err = null; if (ret === -1) { err = new Error('File Locking Error: ' + errmsg); err.code = errno; } setImmediate(callback, err); ...
lockfd
identifier_name
index.js
/* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */ /* * Copyright 2016, Joyent, Inc. */ var BINDING = require('./lockfd_binding'); function check_arg(pos, name, value, type)
function lockfd(fd, callback) { check_arg(1, 'fd', fd, 'number'); check_arg(2, 'callback', callback, 'function'); BINDING.lock_fd(fd, 'write', false, function (ret, errmsg, errno) { var err = null; if (ret === -1) { err = new Error('File Locking Error: ' + errmsg); err.code = errno; } setImmediate...
{ if (typeof (value) !== type) { throw (new Error('argument #' + pos + ' (' + name + ') must be of type ' + type)); } }
identifier_body
index.js
/* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */ /* * Copyright 2016, Joyent, Inc. */ var BINDING = require('./lockfd_binding'); function check_arg(pos, name, value, type) { if (typeof (value) !== type) { throw (new Error('argument #' + pos + ' (' + name + ') must be of type ' + type)); } } functi...
if (!cb_fired) { throw (new Error('lockfdSync: CALLBACK NOT FIRED')); } else if (err) { throw (err); } return (null); } function flock(fd, op, callback) { check_arg(1, 'fd', fd, 'number'); check_arg(2, 'op', op, 'number'); check_arg(3, 'callback', callback, 'function'); BINDING.flock(fd, op, false, funct...
random_line_split
PenStrokeCenter.js
define([ './_Node' , 'Atem-MOM/errors' , './validators' , './PenStrokeLeft' , './PenStrokeRight' ], function( Parent , errors , validators , PenStrokeLeft , PenStrokeRight ) { "use strict"; var DeprecatedError = errors.Deprecated; /** * This Element represents a point of a of ...
() { Parent.call(this); this.add(new PenStrokeLeft()); // 0 this.add(new PenStrokeRight()); // 1 Object.freeze(this._children); } var _p = PenStrokeCenter.prototype = Object.create(Parent.prototype); _p.constructor = PenStrokeCenter; //inherit from parent _p._cps_w...
PenStrokeCenter
identifier_name
PenStrokeCenter.js
define([ './_Node' , 'Atem-MOM/errors' , './validators' , './PenStrokeLeft' , './PenStrokeRight' ], function( Parent , errors , validators , PenStrokeLeft , PenStrokeRight ) { "use strict"; var DeprecatedError = errors.Deprecated; /** * This Element represents a point of a of ...
var _p = PenStrokeCenter.prototype = Object.create(Parent.prototype); _p.constructor = PenStrokeCenter; //inherit from parent _p._cps_whitelist = { left: 'left' , center: 'center' , right: 'right' }; //inherit from parent (function(source) { for(var k in source)...
{ Parent.call(this); this.add(new PenStrokeLeft()); // 0 this.add(new PenStrokeRight()); // 1 Object.freeze(this._children); }
identifier_body
PenStrokeCenter.js
define([ './_Node' , 'Atem-MOM/errors' , './validators'
, validators , PenStrokeLeft , PenStrokeRight ) { "use strict"; var DeprecatedError = errors.Deprecated; /** * This Element represents a point of a of a MoM PenStroke contour. * Its properties are the absolute coordinates of an on-curve point * of the centerline of a contour. * ...
, './PenStrokeLeft' , './PenStrokeRight' ], function( Parent , errors
random_line_split
mga-dialogs.py
#!/usr/bin/env python # vim: set et ts=4 sw=4: #coding:utf-8 ############################################################################# # # mga-dialogs.py - Show mga msg dialog and about dialog. # # License: GPLv3 # Author: Angelo Naselli <anaselli@linux.it> #######################################################...
main_gui = mainGui() main_gui.handleevent()
conditional_block
mga-dialogs.py
#!/usr/bin/env python # vim: set et ts=4 sw=4: #coding:utf-8 ############################################################################# # # mga-dialogs.py - Show mga msg dialog and about dialog. # # License: GPLv3 # Author: Angelo Naselli <anaselli@linux.it> #######################################################...
if __name__ == "__main__": main_gui = mainGui() main_gui.handleevent()
""" Event-handler for the 'widgets' demo """ while True: event = self.dialog.waitForEvent() if event.eventType() == yui.YEvent.CancelEvent: self.dialog.destroy() break if event.widget() == self.closebutton: info ...
identifier_body
mga-dialogs.py
#!/usr/bin/env python # vim: set et ts=4 sw=4: #coding:utf-8 ############################################################################# # # mga-dialogs.py - Show mga msg dialog and about dialog. # # License: GPLv3 # Author: Angelo Naselli <anaselli@linux.it> #######################################################...
appl = yui.YUI.application() appl.setApplicationTitle("Show dialogs example") ################# # class mainGui # ################# class Info(object): def __init__(self,title,richtext,text): self.title=title self.richtext=richtext self.text=text class mainGui(): """ Main class ...
log.setLogFileName("/tmp/debug.log") log.enableDebugLogging( True )
random_line_split
mga-dialogs.py
#!/usr/bin/env python # vim: set et ts=4 sw=4: #coding:utf-8 ############################################################################# # # mga-dialogs.py - Show mga msg dialog and about dialog. # # License: GPLv3 # Author: Angelo Naselli <anaselli@linux.it> #######################################################...
(self, info): yui.YUI.widgetFactory mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga")) dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO) dlg.setTitle(info.title) dlg.setText(info.text, info.richtext) dlg.set...
ask_YesOrNo
identifier_name
__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
del absolute_import del division del print_function
from tensorflow.contrib.keras.python.keras.applications.xception import preprocess_input from tensorflow.contrib.keras.python.keras.applications.xception import Xception
random_line_split
steps.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
(conn): q = self.db.model.steps.select(whereclause=wc) res = conn.execute(q) row = res.fetchone() rv = None if row: rv = self._stepdictFromRow(row) res.close() return rv return (yield self.db.pool.do(thd)) ...
thd
identifier_name
steps.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
if buildid is None: raise RuntimeError('must supply either stepid or buildid') if number is not None: wc = (tbl.c.number == number) elif name is not None: wc = (tbl.c.name == name) else: raise RuntimeError('m...
wc = (tbl.c.id == stepid) else:
random_line_split
steps.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
def thd(conn): tbl = self.db.model.steps wc = (tbl.c.id == stepid) q = sa.select([tbl.c.urls_json], whereclause=wc) res = conn.execute(q) row = res.fetchone() if _racehook is not None: _racehook(...
self.url_lock = defer.DeferredLock()
conditional_block
steps.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
yield self.db.pool.do(thd) # returns a Deferred that returns None def setStepStateString(self, stepid, state_string): def thd(conn): tbl = self.db.model.steps q = tbl.update(whereclause=(tbl.c.id == stepid)) conn.execute(q, state_string=state_string) ...
tbl = self.db.model.steps q = tbl.update(whereclause=(tbl.c.id == stepid)) conn.execute(q, started_at=started_at)
identifier_body
kiss-simple-infobox-hider.user.js
// ==UserScript== // @name Kiss Simple Infobox hider // @description Hides the infobox on kissanime.com, kisscartoon.me and kissasian.com player sites // @include https://kissanime.ru/Anime/*/* // @include https://kimcartoon.to/Cartoon/*/* // @include https://k...
() { var selector = JQ('#centerDivVideo') /* the div with the video */ .prev() /*a clear2 div*/ .prev() /*dropdown*/ .prev() /*a clear2 div*/ .prev(); /*the actual div*/ selector.remove(); } // load after 2 seconds setTimeout(hideInfobox, 2000);
hideInfobox
identifier_name
kiss-simple-infobox-hider.user.js
// ==UserScript== // @name Kiss Simple Infobox hider // @description Hides the infobox on kissanime.com, kisscartoon.me and kissasian.com player sites // @include https://kissanime.ru/Anime/*/* // @include https://kimcartoon.to/Cartoon/*/* // @include https://k...
// load after 2 seconds setTimeout(hideInfobox, 2000);
{ var selector = JQ('#centerDivVideo') /* the div with the video */ .prev() /*a clear2 div*/ .prev() /*dropdown*/ .prev() /*a clear2 div*/ .prev(); /*the actual div*/ selector.remove(); }
identifier_body
kiss-simple-infobox-hider.user.js
// @include https://kissanime.ru/Anime/*/* // @include https://kimcartoon.to/Cartoon/*/* // @include https://kissasian.sh/Drama/*/* // @author Playacem // @updateURL https://raw.githubusercontent.com/Playacem/KissScripts/master/kiss-simple-infobox-hider/kiss-si...
// ==UserScript== // @name Kiss Simple Infobox hider // @description Hides the infobox on kissanime.com, kisscartoon.me and kissasian.com player sites
random_line_split
mod.rs
pub mod query; mod counters; mod debug; mod graph; mod spans; #[cfg(test)] mod tests; use counters::CoverageCounters; use graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph}; use spans::{CoverageSpan, CoverageSpans}; use crate::transform::MirPass; use crate::util::pretty; use rustc_data_structures::...
<'tcx>(tcx: TyCtxt<'tcx>, hir_body: &'tcx rustc_hir::Body<'tcx>) -> u64 { let mut hcx = tcx.create_no_span_stable_hashing_context(); hash(&mut hcx, &hir_body.value).to_smaller_hash() } fn hash( hcx: &mut StableHashingContext<'tcx>, node: &impl HashStable<StableHashingContext<'tcx>>, ) -> Fingerprint { ...
hash_mir_source
identifier_name
mod.rs
pub mod query; mod counters; mod debug; mod graph; mod spans; #[cfg(test)] mod tests; use counters::CoverageCounters; use graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph}; use spans::{CoverageSpan, CoverageSpans}; use crate::transform::MirPass; use crate::util::pretty; use rustc_data_structures::...
self.bcb_leader_bb(bcb), Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)), ); } } /// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the /// counter from the `CoverageSpan`s `BasicCoverag...
); inject_statement( self.mir_body, counter_kind,
random_line_split
mod.rs
pub mod query; mod counters; mod debug; mod graph; mod spans; #[cfg(test)] mod tests; use counters::CoverageCounters; use graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph}; use spans::{CoverageSpan, CoverageSpans}; use crate::transform::MirPass; use crate::util::pretty; use rustc_data_structures::...
CoverageKind::Expression { .. } => { inject_intermediate_expression(self.mir_body, counter_kind) } _ => bug!("CoverageKind should be a counter"), } } } #[inline] fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> Basi...
{ let inject_to_bb = if let Some(from_bcb) = edge_from_bcb { // The MIR edge starts `from_bb` (the outgoing / last BasicBlock in // `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the // `target_bcb`; also ca...
conditional_block
codemap.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ filename: FileName, line: uint, col: CharPos, file: Option<@FileMap>, } // used to be structural records. Better names, anyone? pub struct FileMapAndLine {fm: @FileMap, line: uint} pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos} #[deriving(IterBytes)] pub enum MacroFormat { // e.g. #[...
LocWithOpt
identifier_name
codemap.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// used to be structural records. Better names, anyone? pub struct FileMapAndLine {fm: @FileMap, line: uint} pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos} #[deriving(IterBytes)] pub enum MacroFormat { // e.g. #[deriving(...)] <item> MacroAttribute, // e.g. `format!()` MacroBang } #[derivi...
filename: FileName, line: uint, col: CharPos, file: Option<@FileMap>, }
random_line_split
codemap.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Add<CharPos,CharPos> for CharPos { fn add(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() + rhs.to_uint()) } } impl Sub<CharPos,CharPos> for CharPos { fn sub(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() - rhs.to_uint()) } } /** Spans represent a region o...
{ let CharPos(n) = *self; n }
identifier_body
OcpLoginPage.ts
/********************************************************************* * Copyright (c) 2019 Red Hat, Inc. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifi...
() { Logger.debug('OcpLoginPage.openLoginPageOpenShift'); await this.driverHelper.navigateToUrl(TestConstants.TS_SELENIUM_BASE_URL); } async waitOpenShiftLoginPage() { Logger.debug('OcpLoginPage.waitOpenShiftLoginPage'); await this.driverHelper.waitVisibility(By.css(OcpLoginPa...
openLoginPageOpenShift
identifier_name
OcpLoginPage.ts
/********************************************************************* * Copyright (c) 2019 Red Hat, Inc. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifi...
async waitOpenShiftLoginPage() { Logger.debug('OcpLoginPage.waitOpenShiftLoginPage'); await this.driverHelper.waitVisibility(By.css(OcpLoginPage.LOGIN_PAGE_OPENSHIFT)); } async clickOnLoginWitnKubeAdmin() { Logger.debug('OcpLoginPage.clickOnLoginWitnKubeAdmin'); const lo...
{ Logger.debug('OcpLoginPage.openLoginPageOpenShift'); await this.driverHelper.navigateToUrl(TestConstants.TS_SELENIUM_BASE_URL); }
identifier_body
OcpLoginPage.ts
/********************************************************************* * Copyright (c) 2019 Red Hat, Inc. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifi...
async waitDisappearanceLoginPageOpenShift() { Logger.debug('OcpLoginPage.waitDisappearanceLoginPageOpenShift'); await this.driverHelper.waitDisappearance(By.css(OcpLoginPage.LOGIN_PAGE_OPENSHIFT)); } }
const loginButtonlocator: By = By.css('button[type=submit]'); await this.driverHelper.waitAndClick(loginButtonlocator); }
random_line_split
check_const.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ constants or functions"); } None => { v.tcx.sess.span_bug(e.span, "unbound path in const?!"); } } } ExprC...
Some(&DefStruct(_)) => { } Some(&def) => { debug!("(checking const) found bad def: {:?}", def);
random_line_split
check_const.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self, i: &Item, env: bool) { check_item(self, i, env); } fn visit_pat(&mut self, p: &Pat, env: bool) { check_pat(self, p, env); } fn visit_expr(&mut self, ex: &Expr, env: bool) { check_expr(self, ex, env); } } pub fn check_crate(krate: &Crate, tcx: &ty::ctxt) { vis...
visit_item
identifier_name
check_const.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
Some(&def) => { debug!("(checking const) found bad def: {:?}", def); v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ constants or functions"); } None => { v.tcx.sess.s...
{ }
conditional_block