file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
ast.js
<\\]/) : makeRegexParser(/^[^{}$<\\]/) const regularLiteralWithoutBar = wikilinks ? makeRegexParser(/^[^{}[\]$\\|]/) : makeRegexParser(/^[^{}$\\|]/) const regularLiteralWithoutSpace = wikilinks ? makeRegexParser(/^[^{}[\]$\s]/) : makeRegexParser(/^[^{}$\s]/) // There is a general pattern: // parse a thing; /...
const expr = result[1] // use a "CONCAT" operator if there are multiple nodes, // otherwise return the first node, raw. return expr.length > 1 ? ['CONCAT'].concat(expr) : expr[0] } function templateWithReplacement () { const result = sequence([templateName, colon, replacement]) return r...
{ return null }
conditional_block
capturehost.py
# Set the camera resolution # mode = (w, h, fps) @asyncio.coroutine def set_resolution(self, mode): yield from self._send("RES|%d:%d:%d~" % mode) yield from self._wait_for_ok("RES") # Take a single image (and store it as <name>) @asyncio.coroutine def take_image(self, name): yield from self._send("SAM|%...
yield from self._send("SET|%f~" % pos) yield from self._wait_for_ok("SET")
identifier_body
capturehost.py
@asyncio.coroutine def stop_stream(self): yield from self._send("STSTP|~") # Automatic camera parameters @asyncio.coroutine def param_auto(self): yield from self._send("CAP|~") yield from self._wait_for_ok("CAP") # Lock camera parameters to the current values @asyncio.coroutine def param_lock(self): y...
(client): #open socket listening_sock = socket.socket() listening_sock.bind(('0.0.0.0', 8000)) listening_sock.listen(0) #send msg to cam to start stream yield from client.start_stream() #accept connection from camera connection = listening_sock.accept()[0].makefile('rb') print("streaming connection opened")...
do_streaming
identifier_name
capturehost.py
@asyncio.coroutine def stop_stream(self): yield from self._send("STSTP|~") # Automatic camera parameters @asyncio.coroutine def param_auto(self): yield from self._send("CAP|~") yield from self._wait_for_ok("CAP") # Lock camera parameters to the current values @asyncio.coroutine def param_lock(self): y...
yield from take_client_images("/home/pi/flow.df/calib_%02d.jpg" % p) print("Returning marker to home position") yield from move_marker(0, 0) # Starts the stream on a given client (UNTESTED) @asyncio.coroutine def do_streaming(client): #open socket listening_sock = socket.socket() listening_sock.bind(('0.0.0....
print("Now start moving marker") for p in range(steps + 1): cur = p / float(steps) yield from move_marker(cur)
random_line_split
capturehost.py
im = Image.open(sampleFilename%(i+1)) im = im.transpose(Image.ROTATE_90) #im.show() images.append(im) new_im = Image.new('L', (5*1080, 1920)) x_offset = 0 for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0] new_im.save('/home/student/frejek/samples.png') s...
main(sys.argv)
conditional_block
lib.rs
5 6 5.757158112027513 3 1 7 8.1392602685723 4 3 8 12.483148228609206 5 0 9 25.589444117482433 6 ``` Another way to look at a dendrogram is to visualize it (the following image was created with matplotlib): ![dendrogram of Massachuset...
_method_chain(sel
identifier_name
lib.rs
, Debug, Eq, PartialEq)] pub enum Method { /// Assigns the minimum dissimilarity between all pairs of observations. /// /// Specifically, if `AB` is a newly merged cluster and `X` is every other /// cluster, then the pairwise dissimilarity between `AB` and `X` is /// computed by /// /// ```t...
self.into_method().sqrt(dend); } }
identifier_body
lib.rs
For example, "single" linkage corresponds to using the minimum dissimilarity between all pairs of observations between two clusters as the dissimilarity between those two clusters. It turns out that doing single linkage hierarchical clustering has a rough isomorphism to computing the minimum spanning tree, which means...
io::Error::new(io::ErrorKind::Other, err) } } /// A method for computing the dissimilarities between clusters. /// /// The method selected dictates how the dissimilarities are computed whenever /// a new cluster is formed. In particular, when clusters `a` and `b` are /// merged into a new cluster `ab`, the...
} impl From<Error> for io::Error { fn from(err: Error) -> io::Error {
random_line_split
mesh.rs
); } else { assert!( idx1 != idx2); self.pre_pairs[idx2].insert(idx1); } if idx1 < idx3 { self.pre_pairs[idx1].insert(idx3); } else { assert!( i...
if *idx == id {
random_line_split
mesh.rs
1 = vertex3.coord - vertex1.coord; let n = vec21.cross(&vec31).normalize(); // 法向量N let d = n.dot(&vertex1.coord) * -1.0; let k_p = Matrix4::from_fn(|r, c| { let src1 = if r > 2 { d } else { n[r] }; let src2 = if...
identifier_name
mesh.rs
2, } impl Mesh{ pub fn load(&mut self, file_path : &str) { let f = File::open(file_path).unwrap(); let file = BufReader::new(&f); let mut face_index = 0; for (_, line) in file.lines().enumerate() { let l = line.unwrap(); let args : Vec<&str> = l.split(' ').c...
new_v.coord.x = best_point.x; new_v.coord.y = best_point.y; new_v.coord.z = best_point.z; new_v.q_v = vertex1.q_v + vertex2.q_v; // 更新相关的面
self.vertices[second].clone(); let mut vertex1 = first_ptr.borrow_mut(); let mut vertex2 = second_ptr.borrow_mut(); // 回收旧顶点编号 self.trash.push(first); self.trash.push(second); let new_pos = self.trash.pop().unwrap(); // 获取用于存放新顶点的顶点实体 let temp_pos = se...
identifier_body
mesh.rs
2, } impl Mesh{ pub fn load(&mut self, file_path : &str) { let f = File::open(file_path).unwrap(); let file = BufReader::new(&f); let mut face_index = 0; for (_, line) in file.lines().enumerate() { let l = line.unwrap(); let args : Vec<&str> = l.split(' ').c...
self.pre_pairs[idx2].insert(idx1); } if idx1 < idx3 { self.pre_pairs[idx1].insert(idx3); } else { assert!( idx1 != idx3); self.pre_pairs[idx3].insert(idx1); ...
} else { assert!( idx1 != idx2);
conditional_block
main.rs
term::SizeInfo; use alacritty::tty; use pancurses::colorpair::ColorPair; use pancurses::Input; use pancurses::ToChtype; use pancurses::Window; const OS_IO_ERROR: i32 = 5; fn main() { let win = pancurses::initscr(); // Characters are not rendered when they're typed, instead they're sent to // the underly...
(w: i32, h: i32) -> SizeInfo { SizeInfo { width: w as f32, height: h as f32, cell_width: 1.0, cell_height: 1.0, padding_x: 0.0, padding_y: 0.0, } } fn render_term_to_win(term: &Term, win: &Window, border_char: char) -> RenderResult { win.clear(); let (y,...
new_size_info
identifier_name
main.rs
use alacritty::term::SizeInfo; use alacritty::tty; use pancurses::colorpair::ColorPair; use pancurses::Input; use pancurses::ToChtype; use pancurses::Window; const OS_IO_ERROR: i32 = 5; fn main() { let win = pancurses::initscr(); // Characters are not rendered when they're typed, instead they're sent to ...
use alacritty::cli::Options; use alacritty::config::Config; use alacritty::index::{Point, Line, Column}; use alacritty::Term;
random_line_split
main.rs
term::SizeInfo; use alacritty::tty; use pancurses::colorpair::ColorPair; use pancurses::Input; use pancurses::ToChtype; use pancurses::Window; const OS_IO_ERROR: i32 = 5; fn main() { let win = pancurses::initscr(); // Characters are not rendered when they're typed, instead they're sent to // the underly...
fn new_size_info(w: i32, h: i32) -> SizeInfo { SizeInfo { width: w as f32, height: h as f32, cell_width: 1.0, cell_height: 1.0, padding_x: 0.0, padding_y: 0.0, } } fn render_term_to_win(term: &Term, win: &Window, border_char: char) -> RenderResult { win.cle...
{ for i in 1..COLOUR_INDEXES.len()-1 { if c == COLOUR_INDEXES[i] { return i } } 0 }
identifier_body
main.go
goland:noinspection GoPrintFunctions to make my IDE not shit itself fmt.Println(" _______ _____ _ \n" + " |__ __| / ____| | \n" + " | | ___ _ __ ___ _ __ | | | |__ __ _ _ __ \n" + " | |/ _ \\ '_ ` _ \\| '_ \\| | | '_ \\ / _...
s.ChannelMessageSend(m.ChannelID, "Deleting all channels currently in database.") channelrows, err := DB.Query("SELECT * from channels") if err != nil { s.ChannelMessageSend(m.ChannelID, "Error! Was unable to get data from database.") fmt.Println(err) } var channel = Channel{} for channelrows.Next() ...
re all messages created by the bot itself // This isn't required in this specific example but it's a good practice. if m.Author.ID == s.State.User.ID { return } if strings.Contains(m.Content, "iOS") { _, err := s.ChannelMessageSend(m.ChannelID, "> " + m.Content + "\n" + m.Author.Mention() + " Its `Ios` Not `i...
identifier_body
main.go
goland:noinspection GoPrintFunctions to make my IDE not shit itself fmt.Println(" _______ _____ _ \n" + " |__ __| / ____| | \n" + " | | ___ _ __ ___ _ __ | | | |__ __ _ _ __ \n" + " | |/ _ \\ '_ ` _ \\| '_ \\| | | '_ \\ / _...
make a command framework? if strings.HasPrefix(m.Content, Config.Prefix + "cc ") { tempchan, err := s.ChannelMessageSend(m.ChannelID, "Creating temporay channels for you...") //Create the first category first. channelCategory, err := s.GuildChannelCreate(m.GuildID, strings.Trim(m.Content, Config.Prefix + "cc ...
elMessageSend(m.ChannelID, "Error missing channel name!") } //todo:
conditional_block
main.go
goland:noinspection GoPrintFunctions to make my IDE not shit itself fmt.Println(" _______ _____ _ \n" + " |__ __| / ____| | \n" + " | | ___ _ __ ___ _ __ | | | |__ __ _ _ __ \n" + " | |/ _ \\ '_ ` _ \\| '_ \\| | | '_ \\ / _...
go.Session, m *discordgo.MessageCreate) { // Ignore all messages created by the bot itself // This isn't required in this specific example but it's a good practice. if m.Author.ID == s.State.User.ID { return } if strings.Contains(m.Content, "iOS") { _, err := s.ChannelMessageSend(m.ChannelID, "> " + m.Conte...
te(s *discord
identifier_name
main.go
the json file because for some fucking reason it doesnt want to work and error out. //db, err := sql.Open("mysql", Config.database_user + ":" + Config.database_password + "@tcp(" + Config.database_host + ":" + Config.database_port + ")/" + Config.database_table) db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:...
if err != nil {
random_line_split
fetch_github_projects.py
stdout, _ = process.communicate() hash = stdout.decode().strip('\n') return hash def get_git_commit_count(path): """ Gets the number of commits without merges from a Git repository. """ process = subprocess.Popen(['git', 'rev-list', 'HEAD', '--count', '--no-merges'], cwd=path, stdout=subprocess.PIPE) ...
if count < per_page: hasResults = False except urllib.error.HTTPError as e: #if e.code == 422: # print('reached page limit ' + str(page)) # hasResults = False if e.code == 403: ...
if not exists(project[str("html_url")]): insert_project_entry(project)
conditional_block
fetch_github_projects.py
stdout, _ = process.communicate() hash = stdout.decode().strip('\n') return hash def get_git_commit_count(path): """ Gets the number of commits without merges from a Git repository. """ process = subprocess.Popen(['git', 'rev-list', 'HEAD', '--count', '--no-merges'], cwd=path, stdout=subprocess.PIPE) ...
def insert_project_entry(data): github_url = data[str("html_url")] dirname = download_project(github_url) dirs = dirname.rstrip(os.sep).split(os.sep) commit_count = get_git_commit_count(dirname) committers_count = get_git_commiter_count(dirname) (first_date, last_date) ...
query = """select COUNT(*) FROM GithubProjectUnfiltered WHERE GITHUB_URL = ? """ return c.execute(query, (url,)).fetchone()[0] == 1
identifier_body
fetch_github_projects.py
stdout, _ = process.communicate() hash = stdout.decode().strip('\n') return hash def get_git_commit_count(path): """ Gets the number of commits without merges from a Git repository. """ process = subprocess.Popen(['git', 'rev-list', 'HEAD', '--count', '--no-merges'], cwd=path, stdout=subprocess.PIPE) ...
(url): """ Extracts owner and project name from a Github URL. For example, for https://github.com/graalvm/sulong it returns the tuple (graalvm, sulong). """ if not re.match('https://github.com/([a-zA-Z0-9-_]*)/[a-zA-Z0-9-_]*', url): print(str(url) + "is not a valid url!") exit(-1) el...
owner_project_from_github_url
identifier_name
fetch_github_projects.py
_h_assembly_loc(path): """ Gets the LOC of header and C files using cloc. """ try: process = subprocess.Popen(['cloc', '.'], cwd=path, stdout=subprocess.PIPE) except FileNotFoundError: print("Failed to call cloc (see https://github.com/AlDanial/cloc), please install.") exit(-1) s...
random_line_split
partition_fsm.go
return } resp = mp.fsmUnlinkInode(ino) case opFSMUnlinkInodeBatch: inodes, err := InodeBatchUnmarshal(msg.V) if err != nil { return nil, err } resp = mp.fsmUnlinkInodeBatch(inodes) case opFSMExtentTruncate: ino := NewInode(0, 0) if err = ino.Unmarshal(msg.V); err != nil { return } resp = mp...
if err == nil { mp.uploadApplyID(index) } }() // change memory status var ( updated bool ) switch confChange.Type { case raftproto.ConfAddNode: req := &proto.AddMetaPartitionRaftMemberRequest{} if err = json.Unmarshal(confChange.Context, req); err != nil { return } updated, err = mp.confAddNod...
// ApplyMemberChange apply changes to the raft member. func (mp *metaPartition) ApplyMemberChange(confChange *raftproto.ConfChange, index uint64) (resp interface{}, err error) { defer func() {
random_line_split
partition_fsm.go
.getDentryTree() extendTree := mp.extendTree.GetTree() multipartTree := mp.multipartTree.GetTree() msg := &storeMsg{ command: opFSMStoreTick, applyIndex: index, inodeTree: inodeTree, dentryTree: dentryTree, extendTree: extendTree, multipartTree: multipartTree, } mp.storeCh...
{ exporter.Warning(fmt.Sprintf("metaPartition(%v) changeLeader to (%v)", mp.config.PartitionId, leader)) if mp.config.NodeId == leader { conn, err := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", serverPort), time.Second) if err != nil { log.LogErrorf(fmt.Sprintf("HandleLeaderChange serverPort not exsit...
identifier_body
partition_fsm.go
(command []byte, index uint64) (resp interface{}, err error) { msg := &MetaItem{} defer func() { if err == nil { mp.uploadApplyID(index) } }() if err = msg.UnmarshalJson(command); err != nil { return } switch msg.Op { case opFSMCreateInode: ino := NewInode(0, 0) if err = ino.Unmarshal(msg.V); err !...
Apply
identifier_name
partition_fsm.go
} resp = mp.fsmUnlinkInode(ino) case opFSMUnlinkInodeBatch: inodes, err := InodeBatchUnmarshal(msg.V) if err != nil { return nil, err } resp = mp.fsmUnlinkInodeBatch(inodes) case opFSMExtentTruncate: ino := NewInode(0, 0) if err = ino.Unmarshal(msg.V); err != nil { return } resp = mp.fsmExt...
err = mp.fsmSetXAttr(extend) case opFSMRemoveXAttr: var extend *Extend if extend, err = NewExtendFromBytes(msg.V); err != nil { return } err = mp.fsmRemoveXAttr(extend) case opFSMCreateMultipart: var multipart *Multipart multipart = MultipartFromBytes(msg.V) resp = mp.fsmCreateMultipart(multipart)...
{ return }
conditional_block
options.rs
tab-width") .long("tab-width") .takes_value(true) .value_name("NUM_SPACES") .long_help("Treat a tab as this many spaces.") .env("DFT_TAB_WIDTH") .default_value(formatcp!("{}", DEFAULT_TAB_WIDTH)) .validator(|...
fn relative_to_current(path: &Path) -> PathBuf { if let Ok(current_path) = std::env::current_dir() { let path = try_canonicalize(path); let current_path = try_canonicalize(&current_path); if let Ok(rel_path) = path.strip_prefix(current_path) { return rel_path.into(); }...
{ path.canonicalize().unwrap_or_else(|_| path.into()) }
identifier_body
options.rs
/// argument. pub fn from_cli_argument(arg: &OsStr) -> Self { if arg == "/dev/null" { FileArgument::DevNull } else if arg == "-" { FileArgument::Stdin } else { FileArgument::NamedPath(PathBuf::from(arg)) } } /// Return a `FileArgument...
.value_of("parse-error-limit") .expect("Always present as we've given clap a default") .parse::<usize>() .expect("Value already validated by clap");
random_line_split
options.rs
true; } } Err(e) => { eprintln!("Invalid glob syntax '{}'", glob_str); eprintln!("Glob parsing error: {}", e.msg); invalid_syntax = true; } } } else { eprintln...
test_detect_display_width
identifier_name
CLIEngine.js
current working directory. * @property {boolean} useConfigFiles False disables use of .npmpackagejsonlintrc.json files, npmpackagejsonlint.config.js files, and npmPackageJsonLintConfig object in package.json file. * @property {Object<string,*>} rules An object of rules to use. */ /** * A lint issue. It could ...
(results) { const filtered = []; results.forEach(result => { const filteredIssues = result.issues.filter(isIssueAnError); if (filteredIssues.length > noIssues) { const filteredResult = {
getErrorResults
identifier_name
CLIEngine.js
working directory. * @property {boolean} useConfigFiles False disables use of .npmpackagejsonlintrc.json files, npmpackagejsonlint.config.js files, and npmPackageJsonLintConfig object in package.json file. * @property {Object<string,*>} rules An object of rules to use. */ /** * A lint issue. It could be an er...
else { // string trailing /* (Any number of *s) newPath = newPath.replace(/[/][*]+$/, '') + suffix; } return newPath; }); const files = []; const addedFiles = new Set(); const ignorer = getIgnorer(cwd, options); globPatterns.forEach(pattern => { const file = path.resolve(cwd, patte...
{ const fileStats = fs.statSync(resolvedPath); if (fileStats.isFile()) { if (resolvedPath.endsWith(`${path.sep}package.json`)) { newPath = resolvedPath; } else { throw new Error(`Pattern, ${pattern}, is a file, but isn't a package.json file.`); } } else if ...
conditional_block
CLIEngine.js
current working directory. * @property {boolean} useConfigFiles False disables use of .npmpackagejsonlintrc.json files, npmpackagejsonlint.config.js files, and npmPackageJsonLintConfig object in package.json file. * @property {Object<string,*>} rules An object of rules to use. */ /** * A lint issue. It could ...
* @private */ const isIssueAnError = issue => { return issue.severity === 'error'; }; /** * Generates ignorer based on ignore file content. * * @param {String} cwd Current work directory. * @param {CLIEngineOptions} options CLIEngineOptions object. * @returns {Object} Ignorer */ cons...
* Checks if the given issue is an error issue. * * @param {LintIssue} issue npm-package-json-lint issue * @returns {boolean} True if error, false if warning.
random_line_split
init.go
1 { // Switch image / instance names name = image remote = iremote image = "" iremote = "" } } d, err := conf.GetInstanceServer(remote) if err != nil { return nil, "", err } if c.flagTarget != "" { d = d.UseTarget(c.flagTarget) } // Overwrite profiles. if c.flagProfile != nil { profile...
checkNetwork
identifier_name
init.go
i18n.G("Profile to apply to the new instance")+"``") cmd.Flags().StringArrayVarP(&c.flagDevice, "device", "d", nil, i18n.G("New key/value to apply to a specific device")+"``") cmd.Flags().BoolVarP(&c.flagEphemeral, "ephemeral", "e", false, i18n.G("Ephemeral instance")) cmd.Flags().StringVarP(&c.flagNetwork, "networ...
// Check to see if any of the overridden devices are for devices that are not yet defined in the // local devices (and thus maybe expected to be coming from profiles). profileDevices := make(map[string]map[string]string) needProfileExpansion := false for deviceName := range deviceOverrides { _, isLocalDevice :...
{ return nil, "", err }
conditional_block
init.go
, i18n.G("Profile to apply to the new instance")+"``") cmd.Flags().StringArrayVarP(&c.flagDevice, "device", "d", nil, i18n.G("New key/value to apply to a specific device")+"``") cmd.Flags().BoolVarP(&c.flagEphemeral, "ephemeral", "e", false, i18n.G("Ephemeral instance")) cmd.Flags().StringVarP(&c.flagNetwork, "netwo...
profiles = []string{} } if !c.global.flagQuiet { if name == "" { fmt.Printf(i18n.G("Creating the instance") + "\n") } else { fmt.Printf(i18n.G("Creating %s")+"\n", name) } } if len(stdinData.Devices) > 0 { devicesMap = stdinData.Devices } else { devicesMap = map[string]map[string]string{} } ...
if c.flagProfile != nil { profiles = c.flagProfile } else if c.flagNoProfiles {
random_line_split
init.go
cmd.Flags().BoolVar(&c.flagNoProfiles, "no-profiles", false, i18n.G("Create the instance with no profiles applied")) cmd.Flags().BoolVar(&c.flagEmpty, "empty", false, i18n.G("Create an empty instance")) cmd.Flags().BoolVar(&c.flagVM, "vm", false, i18n.G("Create a virtual machine")) return cmd } func (c *cmdInit)...
{ cmd := &cobra.Command{} cmd.Use = usage("init", i18n.G("[<remote>:]<image> [<remote>:][<name>]")) cmd.Short = i18n.G("Create instances from images") cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(`Create instances from images`)) cmd.Example = cli.FormatSection("", i18n.G(`lxc init images:ubuntu/22.04...
identifier_body
generate_conv_gan.py
= Convolution1D(500, 3, border_mode='valid')(x) x = Activation('relu')(x) x = BatchNormalization()(x) x = Convolution1D(500, 3, border_mode='valid')(x) x = Activation('relu')(x) x = BatchNormalization()(x) x = Convolution1D(500, 3, border_mode='valid')(x) x = Activation('relu')(x) x = B...
(pose_size): in_shape = (SEQ_LENGTH, pose_size) x = in_layer = Input(shape=in_shape) x = Convolution1D(128, 7, border_mode='valid')(x) x = LeakyReLU(0.2)(x) x = BatchNormalization()(x) x = Convolution1D(128, 7, border_mode='valid')(x) x = LeakyReLU(0.2)(x) x = BatchNormalization()(x) ...
make_discriminator
identifier_name
generate_conv_gan.py
0.2)(x) x = BatchNormalization()(x) x = Convolution1D(1, 7, border_mode='valid')(x) x = Flatten()(x) out_layer = Activation('sigmoid')(x) model = Model(input=[in_layer], output=[out_layer]) return model class GANTrainer: noise_dim = NOISE_DIM seq_length = SEQ_LENGTH seq_pad = SEQ...
filenames = glob('h36m-3d-poses/expmap_*.txt.gz') train_X_blocks = [] test_X_blocks = [] with Pool() as pool: for subj_id, X in pool.map(mapper, filenames): if subj_id == 5: # subject 5 is for testing test_X_blocks.append(X) else: ...
identifier_body
generate_conv_gan.py
def __init__(self, pose_size, d_lr=0.0002, g_lr=0.00002): self.discriminator = make_discriminator(pose_size) # Copy is read-only; it doesn't get compiled self.discriminator_copy = make_discriminator(pose_size) self.discriminator_copy.trainable = False disc_opt = Adam(lr=d_lr, be...
print('Loading data') train_X, val_X, mean, std = load_data() print('Data loaded') model = train_model(train_X, val_X, mean, std)
conditional_block
generate_conv_gan.py
= Convolution1D(500, 3, border_mode='valid')(x) x = Activation('relu')(x) x = BatchNormalization()(x) x = Convolution1D(500, 3, border_mode='valid')(x) x = Activation('relu')(x) x = BatchNormalization()(x) x = Convolution1D(500, 3, border_mode='valid')(x) x = Activation('relu')(x) x = B...
"""Input noise for generator""" return np.random.randn(num, self.seq_length + 2 * self.seq_pad, self.noise_dim) def gen_train_step(self, batch_size): """Train the generator to fool the discriminator.""" self.discriminator.trainable = False labe...
def make_noise(self, num):
random_line_split
branch.go
2/github" "github.com/rs/zerolog/log" ) const configFile = "branch_protection.yaml" const polName = "Branch Protection" // OrgConfig is the org-level config definition for Branch Protection. type OrgConfig struct { // OptConfig is the standard org-level opt in/out config, RepoOverride applies to all // BP config. ...
pass := true text := "" ds := make(map[string]details) for _, b := range allBranches { p, rsp, err := rep.GetBranchProtection(ctx, owner, repo, b) if err != nil { if rsp != nil && rsp.StatusCode == http.StatusNotFound { // Branch not protected pass = false text = text + fmt.Sprintf("No protectio...
{ return &policydef.Result{ Enabled: enabled, Pass: true, NotifyText: "No branches configured for enforcement in policy", Details: nil, }, nil }
conditional_block
branch.go
// See the License for the specific language governing permissions and // limitations under the License. // Package branch implements the Branch Protection security policy. package branch import ( "context" "fmt" "net/http" "path" "github.com/ossf/allstar/pkg/config" "github.com/ossf/allstar/pkg/config/operato...
random_line_split
branch.go
2/github" "github.com/rs/zerolog/log" ) const configFile = "branch_protection.yaml" const polName = "Branch Protection" // OrgConfig is the org-level config definition for Branch Protection. type OrgConfig struct { // OptConfig is the standard org-level opt in/out config, RepoOverride applies to all // BP config. ...
func getConfig(ctx context.Context, c *github.Client, owner, repo string) (*OrgConfig, *RepoConfig) { oc := &OrgConfig{ // Fill out non-zero defaults Action: "log", EnforceDefault: true, RequireApproval: true, ApprovalCount: 1, DismissStale: true, BlockForce: true,
{ oc, rc := getConfig(ctx, c, owner, repo) mc := mergeConfig(oc, rc, repo) return mc.Action }
identifier_body
branch.go
2/github" "github.com/rs/zerolog/log" ) const configFile = "branch_protection.yaml" const polName = "Branch Protection" // OrgConfig is the org-level config definition for Branch Protection. type OrgConfig struct { // OptConfig is the standard org-level opt in/out config, RepoOverride applies to all // BP config. ...
(ctx context.Context, c *github.Client, owner, repo string) string { oc, rc := getConfig(ctx, c, owner, repo) mc := mergeConfig(oc, rc, repo) return mc.Action } func getConfig(ctx context.Context, c *github.Client, owner, repo string) (*OrgConfig, *RepoConfig) { oc := &OrgConfig{ // Fill out non-zero defaults Ac...
GetAction
identifier_name
data_mining_project3.py
except KeyError: pass return True else : return False def on_error(self, status): print('error : ', status) def printss(): print("Hello") ''' Given a list of strings, the follwoing subroutine outputs the freque...
return(dictionary) ''' This subroutine calculates the total number of different words in the dictionary. input: dictionary output: count, which is an int variable. ''' def totalNumberOfDifferentWords(dictionary): count = 0 for i in dictionary.values(): count = count + int(i) return count ''...
i = regex.sub('', i) if i not in dictionary.keys(): dictionary[i] = 1 else: dictionary[i] += 1
conditional_block
data_mining_project3.py
except KeyError: pass return True else : return False def on_error(self, status): print('error : ', status) def printss(): print("Hello") ''' Given a list of strings, the follwoing subroutine outputs the freque...
return(result) ''' The following program sorts results of a 2d array based on a parameter. ''' def sortResult(result, parameter): sortedTweets = sorted(result, key=lambda x: x[parameter], reverse=True) return(sortedTweets) ### Authentication details. consumer_key = 'uAJx6MwKhYDMKamBrarSiGUTd' consumer_...
result = [] regex = re.compile('[^a-zA-Z$]') tempCount = 0 for i in arrayTestData: testString = str(i) probEthnicity = classifierForPolarity(dictEthnicity, sizeOfEthnicity, differentWordsInEthnicity, testString) probReligion = classifierForPolarity(dictReligion, sizeOfReligion, diff...
identifier_body
data_mining_project3.py
(tweepy.StreamListener): def on_data(self, data): global n ### Since we have to use this variable in main function, we set it as global varible. if (n < count): #print (data) status = json.loads(data) try: ...
listener
identifier_name
data_mining_project3.py
except KeyError: pass return True else : return False def on_error(self, status): print('error : ', status) def printss(): print("Hello") ''' Given a list of strings, the follwoing subroutine outputs the freque...
neutralTweet = [] for i,j in enumerate(arrayData): if j[1] == 1: ethnicity.append(j[0]) elif j[1] == 2: religion.append(j[0]) elif j[1] == 3: sexualOrientation.append(j[0]) elif j[1] == 4: otherRacialBias.append(j[0]) for i,j in enumerate(arrayData): if j[2] == 0: ...
religion = [] sexualOrientation = [] otherRacialBias = [] positiveTweet = [] negativeTweet = []
random_line_split
client.go
if c.client == nil { logger.Errorf("Error: SDK client is nil!!!\n") return nil, errors.New(errors.GeneralError, "SDK client is nil") } //put client into cache cachedClient[channelID] = c return c, nil } //initializeCache used to initialize client cache func (c *clientImpl) initializeCache() { once.Do(func(...
{ logger.Errorf("Error initializing client: %s\n", err) return nil, errors.Wrap(errors.GeneralError, err, "error initializing fabric client") }
conditional_block
client.go
endorsements from %s, on channel %s", endorseRequest.ChaincodeID, channel.Name()) request := apitxn.ChaincodeInvokeRequest{ Targets: processors, Fcn: endorseRequest.Args[0], Args: utils.GetByteArgs(endorseRequest.Args[1:]), TransientMap: endorseRequest.TransientData, ChaincodeID: e...
random_line_split
client.go
client: %s\n", err) return nil, errors.Wrap(errors.GeneralError, err, "error initializing fabric client") } if c.client == nil { logger.Errorf("Error: SDK client is nil!!!\n") return nil, errors.New(errors.GeneralError, "SDK client is nil") } //put client into cache cachedClient[channelID] = c return c, n...
(channel sdkApi.Channel, responses []*apitxn.TransactionProposalResponse, registerTxEvent bool) error { c.RLock() defer c.RUnlock() transaction, err := channel.CreateTransaction(responses) if err != nil { return errors.WithMessage(errors.GeneralError, err, "Error creating transaction") } logger.Debugf("Sendin...
CommitTransaction
identifier_name
client.go
Interval()) } } if len(peers) == 0 { logger.Errorf("No suitable endorsers found for transaction.") return nil, errors.New(errors.GeneralError, "no suitable endorsers found for transaction") } } else { peers = endorseRequest.Targets } for _, peer := range peers { logger.Debugf("Target peer %v", p...
{ //Get cryptosuite provider name from name from peerconfig cryptoProvider, err := c.config.GetCryptoProvider() if err != nil { return err } sdk, err := fabsdk.New(config.FromRaw(sdkConfig, "yaml"), fabsdk.WithContextPkg(&factories.CredentialManagerProviderFactory{CryptoPath: c.config.GetMspConfigPath()}), ...
identifier_body
main.go
() { if runtime.GOOS == "windows" { //lol goos //can't use color.Error, because *nix etc don't have that for some reason :( librecursebuster.InitLogger(color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output) } else { librecurseb...
main
identifier_name
main.go
Blacklist: make(map[string]bool), } globalState.Hosts.Init() cfg.Version = version totesTested := uint64(0) globalState.TotalTested = &totesTested showVersion := true flag.BoolVar(&cfg.ShowAll, "all", false, "Show, and write the result of all checks") flag.BoolVar(&cfg.AppendDir, "appendslash", false, "App...
flag.StringVar(&cfg.Cookies, "cookies", "", "Any cookies to include with requests. This is smashed into the cookies header, so copy straight from burp I guess.") flag.BoolVar(&cfg.Debug, "debug", false, "Enable debugging") flag.IntVar(&cfg.MaxDirs, "dirs", 1, "Maximum directories to perform busting on concurrently N...
flag.StringVar(&cfg.Canary, "canary", "", "Custom value to use to check for wildcards") flag.BoolVar(&cfg.CleanOutput, "clean", false, "Output clean URLs to the output file for easy loading into other tools and whatnot.")
random_line_split
main.go
totesTested := uint64(0) globalState.TotalTested = &totesTested showVersion := true flag.BoolVar(&cfg.ShowAll, "all", false, "Show, and write the result of all checks") flag.BoolVar(&cfg.AppendDir, "appendslash", false, "Append a / to all directory bruteforce requests (like extension, but slash instead of .yourthi...
{ if runtime.GOOS == "windows" { //lol goos //can't use color.Error, because *nix etc don't have that for some reason :( librecursebuster.InitLogger(color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output, color.Output) } else { librecursebust...
identifier_body
main.go
Blacklist: make(map[string]bool), } globalState.Hosts.Init() cfg.Version = version totesTested := uint64(0) globalState.TotalTested = &totesTested showVersion := true flag.BoolVar(&cfg.ShowAll, "all", false, "Show, and write the result of all checks") flag.BoolVar(&cfg.AppendDir, "appendslash", false, "App...
} if cfg.WhitelistLocation != "" { readerChan := make(chan string, 100) go librecursebuster.LoadWords(cfg.WhitelistLocation, readerChan, printChan) for x := range readerChan { globalState.Whitelist[x] = true } } if cfg.Wordlist != "" && cfg.MaxDirs == 1 { zerod := uint32(0) globalState.DirbProgre...
{ globalState.Blacklist[x] = true }
conditional_block
upload.js
POST', data : videoData, on : { success : function (id,o) { data = Y.JSON.parse(o.responseText); if(data.info=='add success'){ uploading.addClass('hidden'); videoInfo.addClass('hidden'); uploadFinish.addClass('hidden'); videoForm.addClass('hidden');...
tion (e) { e.preventDefault(); window.onbeforeunload=null; window.location.reload(); }, '.errorUploadY'); mask.setStyle('display', 'block'); errorUploadOl.centered(); errorUploadOl.show(); } }); uploader.on('uploaderror',function(e){ Y.log(e); }); /...
} else { Y.on('click', func
conditional_block
upload.js
selectFileBtn = Y.one('#selectFileBtn'), //选择按钮 fileInput = Y.one('#fileInput'), uploading = Y.one("#uploading"), //上传进度box uploadProgess = Y.one('#uploadProgess'), //进度条 //uploadRate = Y.one('#uploadRate'), //速度 timeRemaining = Y.one('#timeRemaining'), //剩余时间 uploadFinish = Y.one('#uploadFin...
}).use('uploader', 'overlay', "json-parse",function (Y) { if (logined) { if (Y.Uploader.TYPE != "none") { var selectFile = Y.one('#selectFile'), //浏览
random_line_split
upload.js
contentWindow.Y.io('http://so.v.163.com/ugc/addvideoasync.do', { method : 'POST', data : videoData, on : { success : function (id,o) { data = Y.JSON.parse(o.responseText); if(data.info=='add success'){ uploading.addClass('hidden'); videoInfo.addClass('hidden');...
rossdomain').
identifier_name
upload.js
', data : videoData, on : { success : function (id,o) { data = Y.JSON.parse(o.responseText); if(data.info=='add success'){ uploading.addClass('hidden'); videoInfo.addClass('hidden'); uploadFinish.addClass('hidden'); videoForm.addClass('hidden'); ...
function cutString(str,num){ var strReg = /[^x00-xff]/g, strLen = str.replace(strReg, 'aa').length, newStr, fullWi dthNum=num/2; if (strLen > num) { for (i = fullWidthNum; i < strLen; i++) { newStr = str.substr(0, i).replace(strReg, "aa"); if (newStr.length >= num) { ...
{ m = Math.floor((scd - h * 3600) / 60); if (scd - h * 3600 - m * 60 > 0) { s = scd - h * 3600 - m * 60; } }; resultString = h + '\u5c0f\u65f6' + m + '\u5206' + s + '\u79d2'; } else if (scd >= 60) { m = Math.floor(scd / 60); if (scd - m * 60 > 0) { s = s...
identifier_body
salt.go
//读返回信息 body, err := ioutil.ReadAll(respon.Body) if !tools.CheckERR(err, "ReadALL response Body Failed") { return saltinfo } //反序列化 err = json.Unmarshal(body, &saltinfo) if !tools.CheckERR(err, "Json Unmarshal Returninfo Failed") { return saltinfo } //fmt.Println(saltinfo) return saltinfo } //异步执行指定的模块 fu...
DB minion Address,Please check request!") } //log.Printf("JWT=%s,retruninfo=%s,error=%s\n",token,retruninfo,err.Error()) return retruninfo.Data.IPgroup, err } //salt-minion存活检测 func (s *SaltController) ActiveSalt(address string) (bool, string) { //获取token信息 token, err := s.Check() fmt.Println("请求进来了", address, "...
etruninfo.Code != 00000 { return "", errors.New("Dont's Get CM
conditional_block
salt.go
odata=", result) return result } //公共的POST整理 func pulicPost(token string, para *conf.JobRunner) (response *http.Response) { //构建json参数 cmd := &conf.JobRunner{ Client: para.Client, Tgt: para.Tgt, Fun: para.Fun, Arg: para.Arg, Expr_form: para.Expr_form, } //Object序列化 data, err := jso...
//构建json参数 cmd := &conf.JobRunner{ Client: "local",
random_line_split
salt.go
//读返回信息 body, err := ioutil.ReadAll(respon.Body) if !tools.CheckERR(err, "ReadALL response Body Failed") { return saltinfo } //反序列化 err = json.Unmarshal(body, &saltinfo) if !tools.CheckERR(err, "Json Unmarshal Returninfo Failed") { return saltinfo } //fmt.Println(saltinfo) return saltinfo } //异步执行指定的模块 fu...
token, err := s.Check() fmt.Println("请求进来了", address, "", token, err) if !tools.CheckERR(err, "获取token失败") { return false, fmt.Sprintf("内部获取token失败,ERROR=%s", err) } fmt.Println("请求进来了", token) //构建json参数 cmd := &conf.JobRunner{ Client: "local", Tgt: address, Fun: "test.ping", } fmt.Printf("token...
CMDB Request URL IS Failed") //设置request req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "JWT"+" "+token) //请求连接等待返回 client := http.Client{} repon, err := client.Do(req) tools.CheckERR(err, "Request CMDB IS Failed") info, _ := ioutil.ReadAll(repon.Body) json.Unmarshal(info, &...
identifier_body
salt.go
turninfo) { /* 如果是带有HTTPs的则还需要传递TLS进Client中 */ //配置请求信息 info := &conf.Info{ Username: conf.Config.Conf.Saltauth[0].Username, Password: conf.Config.Conf.Saltauth[0].Password, Eauth: conf.Config.Conf.Saltauth[0].Eauth, } //序列化 buf, err := json.Marshal(info) if !tools.CheckERR(err, "Json Marshal is Fai...
conf.Re
identifier_name
dbStateManager.go
s FBlock = %x \n", str, ds.FactoidBlock.GetHash().Bytes()[:5]) str = fmt.Sprintf("%s ECBlock = %x \n", str, ds.EntryCreditBlock.GetHash().Bytes()[:5]) } return str } func (list *DBStateList) GetHighestRecordedBlock() uint32 { ht := uint32(0) for i, dbstate := range list.DBStates { if dbs...
random_line_split
dbStateManager.go
n" } else if ds.DirectoryBlock == nil { str = " Directory Block = <nil>\n" } else { str = fmt.Sprintf("%s DBlk Height = %v\n", str, ds.DirectoryBlock.GetHeader().GetDBHeight()) str = fmt.Sprintf("%s DBlock = %x \n", str, ds.DirectoryBlock.GetHash().Bytes()[:5]) str = fmt.Sprintf("%s ...
{ return 1 }
conditional_block
dbStateManager.go
Height) begin = int(dbsHeight + 1) end = int(plHeight - 1) } else { return } } list.Lastreq = begin end2 := begin + 400 if end < end2 { end2 = end } msg := messages.NewDBStateMissing(list.State, uint32(begin), uint32(end2)) if msg != nil { list.State.NetworkOutMsgQueue() <- msg list.State....
{ i := int(height) - int(list.Base) if i < 0 || i >= len(list.DBStates) { return nil } return list.DBStates[i] }
identifier_body
dbStateManager.go
&& ds.DirectoryBlock != nil { list.State.DBMutex.Lock() dblk, _ := list.State.DB.FetchDBlockByHash(ds.DirectoryBlock.GetKeyMR()) list.State.DBMutex.Unlock() if dblk != nil { rec = "R" } if ds.Saved { rec = "S" } } if last != "" { str = last } str = fmt.Sprintf("%s %1s-DState\n ...
() (progress bool) { list.Catchup() for i, d := range list.DBStates { // Must process blocks in sequence. Missing a block says we must stop. if d == nil { return } if d.Saved { continue } // Make sure the directory block is properly synced up with the prior block, if there // is one. list...
UpdateState
identifier_name
table.go
Username: p.User(), DescriptorIDs: tableIDs, Details: jobspb.SchemaChangeDetails{ DroppedSchemas: schemasToDrop, DroppedTables: tableDropDetails, DroppedTypes: typeIDs, DroppedDatabaseID: databaseID, FormatVersion: jobspb.DatabaseJobFormatVersion, }, Progress: jobspb.S...
writeTableDescToBatch
identifier_name
table.go
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc" "github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc" "github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry" "github.com/cockroachdb/cockroach/pkg/util/log" "github.com/cockroachdb/errors" ) func (p *planner) getVirtualTabler() VirtualTabler { r...
if p.extendedEvalCtx.ExecCfg.TestingKnobs.RunAfterSCJobsCacheLookup != nil { p.extendedEvalCtx.ExecCfg.TestingKnobs.RunAfterSCJobsCacheLookup(job) } var spanList []jobspb.ResumeSpanList jobExists := job != nil if jobExists { spanList = job.Details().(jobspb.SchemaChangeDetails).ResumeSpanList } span := ta...
{ job = cachedJob }
conditional_block
table.go
" "github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc" "github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc" "github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry" "github.com/cockroachdb/cockroach/pkg/util/log" "github.com/cockroachdb/errors" ) func (p *planner) getVirtualTabler() VirtualTabler { ...
ctx context.Context, databaseID descpb.ID, jobDesc string, ) error { jobRecord := jobs.Record{ Description: jobDesc, Username: p.User(), Details: jobspb.SchemaChangeDetails{ DescID: databaseID, FormatVersion: jobspb.DatabaseJobFormatVersion, }, Progress: jobspb.SchemaChangeProgress{}, ...
// don't queue multiple jobs for the same database. func (p *planner) createNonDropDatabaseChangeJob(
random_line_split
table.go
" "github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc" "github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc" "github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry" "github.com/cockroachdb/cockroach/pkg/util/log" "github.com/cockroachdb/errors" ) func (p *planner) getVirtualTabler() VirtualTabler { ...
FormatVersion: jobspb.DatabaseJobFormatVersion, }, Progress: jobspb.SchemaChangeProgress{}, NonCancelable: true, } newJob, err := p.extendedEvalCtx.QueueJob(ctx, jobRecord) if err != nil { return err } log.Infof(ctx, "queued new drop database job %d for database %d", newJob.ID(), databaseID) r...
{ // TODO (lucy): This should probably be deleting the queued jobs for all the // tables being dropped, so that we don't have duplicate schema changers. tableIDs := make([]descpb.ID, 0, len(tableDropDetails)) for _, d := range tableDropDetails { tableIDs = append(tableIDs, d.ID) } typeIDs := make([]descpb.ID, 0...
identifier_body
Script.js
.getElementById("lb_DocTitles").innerText += LocalizedString('Message2'); v_data[11] = "V_DOCS_TOBO_IN"; } if (args.type == '1') { document.getElementById("lb_DocTitles").innerText += LocalizedString('Message3'); v_data[11] = "V_DOCS_USER_IN"; } ...
} else location.replace("dialog.aspx?type=err"); return false; } return true; } //Продублировать документ function CreateSameDocument() { //location.replace("/barsroot/docinput/docinput.aspx?tt=" + escape(selectedRow.tt) + "&refDoc=" + selectedRowId); ...
identifier_body
Script.js
innerText += LocalizedString('Message2'); v_data[11] = "V_DOCS_TOBO_OUT_NOTVIP"; } } if (args.par.charAt(1) == '2') { document.getElementById("lb_DocTitles").innerText = LocalizedString('Message4'); if (args.type == '0') { document.getElementById("lb_DocTit...
function editSelectedSumsArray(elem) { var amount = +$(elem).attr('data-sum'); var sum = 0; if ($(elem).prop('checked')) { selectedSumsArray.push(amount); for (var i = 0; i < selectedSumsArray.length; i++) { sum += selectedSumsArray[i]; } } else { var...
random_line_split
Script.js
innerText += LocalizedString('Message2'); v_data[11] = "V_DOCS_TOBO_OUT_NOTVIP"; } } if (args.par.charAt(1) == '2') { document.getElementById("lb_DocTitles").innerText = LocalizedString('Message4'); if (args.type == '0') { document.getElementById("lb_DocTit...
lectedSumsArray(elem) { var amount = +$(elem).attr('data-sum'); var sum = 0; if ($(elem).prop('checked')) { selectedSumsArray.push(amount); for (var i = 0; i < selectedSumsArray.length; i++) { sum += selectedSumsArray[i]; } } else { var num = -1; ...
Cookie.substring(start, end); value = unescape(value); return value; } } /*******************************/ var arrayForPrint = new Array();//масив з референсами відмічених документів var selectedSumsArray = new Array(); function editSe
conditional_block
Script.js
] + " : "; } } var obj = new Object(); obj.v_serviceObjName = 'webService'; obj.v_serviceName = 'Service.asmx'; obj.v_serviceMethod = 'GetData'; obj.v_serviceFuncAfter = "LoadDocuments"; var menu = new Array(); menu[LocalizedString('Message8')] = "OpenDoc()"; ...
cordsAmount = Numbe
identifier_name
validator.go
} httpPort = portNumber } // search for issuer iss := os.Getenv("OAUTH_ISSUER") if iss != "" { issuer = iss } // read backend search options opt, err := parseSearchOptions() if err != nil { klog.Errorf("failed to configure search options: %v", err) os.Exit(1) } searchOpt = opt aud := os.Getenv("O...
backendsService := gcpBackendsAPIService{backendServicesService: computeService.BackendServices} // TODO: use a backoff strategy tick := time.NewTicker(retryInterval) defer tick.Stop() for { klog.V(3).Info("begin call to get the project number") projectNumber, err := getProjectNumber(projectsService) if e...
klog.Fatalf("cannot create compute api service") }
random_line_split
validator.go
} httpPort = portNumber } // search for issuer iss := os.Getenv("OAUTH_ISSUER") if iss != "" { issuer = iss } // read backend search options opt, err := parseSearchOptions() if err != nil { klog.Errorf("failed to configure search options: %v", err) os.Exit(1) } searchOpt = opt aud := os.Getenv("O...
func getBackendServiceID(backendServices backendsAPIService) (string, error) { // Get only the backends where IAP is enabled backends, err := backendServices.List("iap.enabled=true") if err != nil { return "", err } var foundBackend *compute.BackendService for _, backend := range backends { klog.V(1).Info...
{ klog.V(3).Infof("begin call to projects api") project, err := projectsService.Get(searchOpt.projectID) if err != nil { return "", err } if klog.V(3).Enabled() { klog.Infof("project: %+v", project) } return strconv.FormatInt(project.ProjectNumber, 10), nil }
identifier_body
validator.go
} httpPort = portNumber } // search for issuer iss := os.Getenv("OAUTH_ISSUER") if iss != "" { issuer = iss } // read backend search options opt, err := parseSearchOptions() if err != nil { klog.Errorf("failed to configure search options: %v", err) os.Exit(1) } searchOpt = opt aud := os.Getenv("O...
() (*searchOptions, error) { options := &searchOptions{} options.projectID = os.Getenv("PROJECT_ID") if options.projectID == "" { return nil, fmt.Errorf("invalid configuration, PROJECT_ID variable not found") } options.oauthClientID = os.Getenv("OAUTH_CLIENT_ID") options.serviceName = os.Getenv("SERVICE_NAME") ...
parseSearchOptions
identifier_name
validator.go
} httpPort = portNumber } // search for issuer iss := os.Getenv("OAUTH_ISSUER") if iss != ""
// read backend search options opt, err := parseSearchOptions() if err != nil { klog.Errorf("failed to configure search options: %v", err) os.Exit(1) } searchOpt = opt aud := os.Getenv("OAUTH_AUDIENCE") if aud != "" { audience = aud } else { // search for audience go getRequiredClaims() } // set...
{ issuer = iss }
conditional_block
streamer.rs
default_true")] path_style_access: bool, } // Defaults for the config. impl Config { fn fivembs() -> usize { MORE_THEN_FIVEMBS } fn normalize(&mut self, alias: &Alias) { if self.buffer_size < MORE_THEN_FIVEMBS { warn!("[Connector::{alias}] Setting `buffer_size` up to minimu...
{ if let Some(location) = out.location() { debug!("{ctx} Finished upload {upload_id} for {location}"); } else { debug!("{ctx} Finished upload {upload_id} for {object_id}"); } // the duration of handling in the sink i...
conditional_block
streamer.rs
pub(crate) struct Config { aws_region: Option<String>, url: Option<Url<HttpsDefaults>>, /// optional default bucket bucket: Option<String>, #[serde(default = "Default::default")] mode: Mode, #[serde(default = "Config::fivembs")] buffer_size: usize, /// Enable path-style access ...
random_line_split
streamer.rs
#[serde(default = "Config::fivembs")] buffer_size: usize, /// Enable path-style access /// So e.g. creating a bucket is done using: /// /// PUT http://<host>:<port>/<bucket> /// /// instead of /// /// PUT http://<bucket>.<host>:<port>/ /// /// Set this to `true` for accessi...
( &self, id: &Alias, _: &ConnectorConfig, config: &Value, _kill_switch: &KillSwitch, ) -> Result<Box<dyn Connector>> { let mut config = Config::new(config)?; config.normalize(id); Ok(Box::new(S3Connector { config })) } } struct S3Connector { c...
build_cfg
identifier_name
streamer.rs
<ReplySender>, } impl ObjectStorageCommon for S3ObjectStorageSinkImpl { fn default_bucket(&self) -> Option<&String> { self.config.bucket.as_ref() } fn connector_type(&self) -> &str { CONNECTOR_TYPE } } impl S3ObjectStorageSinkImpl { pub(crate) fn yolo(config: Config) -> Self { ...
{ &self.object_id }
identifier_body
puzzleGenerator.py
mv = moves[direction] x, y = findGap(board) x2, y2 = nextPos(x, y, mv) return isPositionLegal(board, x2, y2) # def canMove(board): # x, y = findGap(board) # # for mv in moves: # x2, y2 = nextPos(x, y, mv) # if isPositionLegal(board, x2, y2): # return True # # re...
random_line_split
puzzleGenerator.py
(board, x2, y2): # return True # # return False def possibleMoves(board): global moves x, y = findGap(board) res = [] for mv in moves: x2, y2 = nextPos(x, y, mv) if isPositionLegal(board, x2, y2): res.append(mv) return res def moveGap(board, move): ...
(board): print("") for row in board: row_str = "" for cell in row: row_str += str(cell) + " " print(row_str) def translateMoveToLetter(move): m1,m2 = move if m1 == -1 and m2 == 0: return 'U' if m1 == 0 and m2 == 1: return 'R' if m1 ==...
printBoard
identifier_name
puzzleGenerator.py
(board, x2, y2): # return True # # return False def possibleMoves(board): global moves x, y = findGap(board) res = [] for mv in moves: x2, y2 = nextPos(x, y, mv) if isPositionLegal(board, x2, y2): res.append(mv) return res def moveGap(board, move): ...
def translateMoveToLetter(move): m1,m2 = move if m1 == -1 and m2 == 0: return 'U' if m1 == 0 and m2 == 1: return 'R' if m1 == 1 and m2 == 0: return 'D' if m1 ==0 and m2 == -1: return 'L' def manhattanDistance(board): distance = 0 l ...
print("") for row in board: row_str = "" for cell in row: row_str += str(cell) + " " print(row_str)
identifier_body
puzzleGenerator.py
) x2, y2 = nextPos(x, y, move) tmp = board[x][y] board[x][y] = board[x2][y2] board[x2][y2] = tmp def findGap(board): for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == 0: return i,j return -1, -1 def printBoard(board): print("...
n = int(sys.argv[1]) k = int(sys.argv[2]) out_file = open(sys.argv[3], 'w')
conditional_block
conn_write.rs
::HttpStreamCommand; use crate::common::stream::HttpStreamCommon; use crate::common::stream::HttpStreamData; use crate::common::types::Types; use crate::common::window_size::StreamOutWindowReceiver; use crate::data_or_headers::DataOrHeaders; use crate::data_or_headers_with_flag::DataOrHeadersWithFlag; use crate::solici...
else { debug!("sending frame {:?}", frame.debug_no_data()); } self.queued_write.queue_not_goaway(frame); return; } let mut pos = 0; while pos < data.len() { let end = cmp::min(data.len(), pos + max_frame_size); let ...
{ debug!("sending frame {:?}", frame); }
conditional_block
conn_write.rs
::HttpStreamCommand; use crate::common::stream::HttpStreamCommon; use crate::common::stream::HttpStreamData; use crate::common::types::Types; use crate::common::window_size::StreamOutWindowReceiver; use crate::data_or_headers::DataOrHeaders; use crate::data_or_headers_with_flag::DataOrHeadersWithFlag; use crate::solici...
let mut pos = 0; while pos < data.len() { let end = cmp::min(data.len(), pos + max_frame_size); let end_stream_in_frame = if end == data.len() && end_stream == EndStream::Yes { EndStream::Yes } else { EndStream::No }; ...
{ let max_frame_size = self.peer_settings.max_frame_size as usize; // if client requested end of stream, // we must send at least one frame with end stream flag if end_stream == EndStream::Yes && data.len() == 0 { let mut frame = DataFrame::with_data(stream_id, Bytes::new())...
identifier_body
conn_write.rs
::HttpStreamCommand; use crate::common::stream::HttpStreamCommon; use crate::common::stream::HttpStreamData; use crate::common::types::Types; use crate::common::window_size::StreamOutWindowReceiver; use crate::data_or_headers::DataOrHeaders; use crate::data_or_headers_with_flag::DataOrHeadersWithFlag; use crate::solici...
self.process_stream_enqueue(stream_id, part) } CommonToWriteMessage::Pull(stream_id, stream, out_window_receiver) => { self.process_stream_pull(stream_id, stream, out_window_receiver) } CommonToWriteMessage::IncreaseInWindow(stream_id, incr...
CommonToWriteMessage::StreamEnqueue(stream_id, part) => {
random_line_split
conn_write.rs
::HttpStreamCommand; use crate::common::stream::HttpStreamCommon; use crate::common::stream::HttpStreamData; use crate::common::types::Types; use crate::common::window_size::StreamOutWindowReceiver; use crate::data_or_headers::DataOrHeaders; use crate::data_or_headers_with_flag::DataOrHeadersWithFlag; use crate::solici...
(&mut self, stream_id: StreamId, part: HttpStreamCommand) { match part { HttpStreamCommand::Data(data, end_stream) => { self.write_part_data(stream_id, data, end_stream); } HttpStreamCommand::Headers(headers, end_stream) => { self.write_part_he...
write_part
identifier_name
parseschema2.py
THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE ...
(self, name): """ Returns a CamelCasedName version of attribute.case.names. """ return "".join([n[0].upper() + n[1:] for n in name.split(".")]) def getattdocs(self, aname): """ returns the documentation string for element name, or an empty string if there is none.""" dsc = s...
cc
identifier_name
parseschema2.py
TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR T...
p.add_argument("-o", "--outdir", default="output", help="output directory") p.add_argument("-l", "--lang", default=["python"], help="Programming language or languages to output. To output multiple languages at once, list desired languages separated by a space after -l. For example: python parseschema2.py [compi...
exclusive_group = p.add_mutually_exclusive_group() exclusive_group.add_argument("compiled", help="A compiled ODD file", nargs="?") # Due to nargs="?", "compiled" will appear as optional and not positional
random_line_split
parseschema2.py
Parser(resolve_entities=True) self.schema = etree.parse(oddfile, parser) # self.customization = etree.parse(customization_file) self.active_modules = [] # the modules active in the resulting output self.element_structure = {} # the element structure. self.attribute_group_struc...
lg.debug("Removing old Manuscript output directory") shutil.rmtree(output_directory)
conditional_block
parseschema2.py
THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE ...
def getattdocs(self, aname): """ returns the documentation string for element name, or an empty string if there is none.""" dsc = self.schema.xpath("//tei:attDef[@ident=$name]/tei:desc/text()", name=aname, namespaces=TEI_NS) if dsc: return re.sub('[\s\t]+', ' ', dsc[0]) # stri...
""" Returns a CamelCasedName version of attribute.case.names. """ return "".join([n[0].upper() + n[1:] for n in name.split(".")])
identifier_body
views.py
SetNewPasswordSerializer, PhoneNumberSerializer, OtpSerializer) from rest_framework.response import Response from .models import User, Customer, Admin from django.db import transaction from django.contrib.auth import logout from rest_framework_simplejwt.tokens import RefreshToken from .utils i...
serializer_class = LogoutSerializer def post(self, request): logout(request) data = {'Success': 'Logout Successful'} return Response(data=data, status=status.HTTP_200_OK) class RequestPasswordEmailView(generics.GenericAPIView): serializer_class = ResetPasswordSerializer def p...
class LogoutView(generics.GenericAPIView):
random_line_split
views.py
SetNewPasswordSerializer, PhoneNumberSerializer, OtpSerializer) from rest_framework.response import Response from .models import User, Customer, Admin from django.db import transaction from django.contrib.auth import logout from rest_framework_simplejwt.tokens import RefreshToken from .utils i...
user.otp_code = otp user.phone_number = phone_number expiry = timezone.now() + timedelta(minutes=30) user.otp_code_expiry = expiry user.save() try: client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) message_to_broadcast = ...
otp = generate_otp()
conditional_block
views.py
SetNewPasswordSerializer, PhoneNumberSerializer, OtpSerializer) from rest_framework.response import Response from .models import User, Customer, Admin from django.db import transaction from django.contrib.auth import logout from rest_framework_simplejwt.tokens import RefreshToken from .utils i...
user.otp_code_expiry = expiry user.save() try: client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) message_to_broadcast = f'Your OgaTailor Verification code is {otp}' client.messages.create(to=phone_number, from_=settings.TWILIO_NUMBER, ...
serializer_class = PhoneNumberSerializer otp = None @transaction.atomic() def post(self, request, otp=None): data = request.data email = data['email'] user = User.objects.get(email=email) phone_number_valid = PhoneNumberSerializer(data=data) if not phone_number_valid...
identifier_body