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
shared_util.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 applicab...
def sample_categorical(log_scores): """Use Gumbel-max trick to sample from categorical distribution.""" in_shape = log_scores.get_shape() noised = log_scores + gumbel_noise(in_shape) indices = tf.to_int32(tf.argmax(noised, 1)) ret_sample = tf.one_hot(indices, in_shape[1]) ret_indices = tf.expand_dims(ind...
"""Return tensor of samples from Gumbel random variable.""" uniform_noise = tf.random_uniform(shape, 0.0, 1.0) neg_log_uniform_noise = -tf.log(uniform_noise) neg_log_neg_log_uniform_noise = -tf.log(neg_log_uniform_noise) return neg_log_neg_log_uniform_noise
identifier_body
shared_util.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 applicab...
(t, dim): """Like reduce_sum, but broadcasts sum out to every entry in reduced dim.""" t_shape = t.get_shape() rank = t.get_shape().ndims return tf.tile( tf.expand_dims(tf.reduce_sum(t, dim), dim), [1] * dim + [t_shape[dim].value] + [1] * (rank - dim - 1)) def normalize_all_reduce(vec): """Like ...
all_reduce_sum
identifier_name
shared_util.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 applicab...
return n / safe_denom def normalize(vec): """Length-normalize vec, passing through length-0 inputs unchanged.""" # just return zeros if incoming vec equals zeros z = tf.expand_dims(tf.reduce_sum(vec, 1), 1) return safe_divide(vec, z), z def safe_log(t): """Logarithm that returns 0 for log(0), for easy m...
zeros_d = tf.zeros_like(d) ones_d = tf.ones_like(d) safe_denom = tf.select(tf.equal(d, zeros_d), ones_d, d)
random_line_split
isbn_verifier_test.py
import unittest from isbn_verifier import is_valid # Tests adapted from `problem-specifications//canonical-data.json` class IsbnVerifierTest(unittest.TestCase): def test_valid_isbn(self): self.assertIs(is_valid("3-598-21508-8"), True) def test_invalid_isbn_check_digit(self): self.assertIs(i...
unittest.main()
conditional_block
isbn_verifier_test.py
import unittest from isbn_verifier import is_valid # Tests adapted from `problem-specifications//canonical-data.json` class IsbnVerifierTest(unittest.TestCase):
def test_isbn_without_separating_dashes_and_x_as_check_digit(self): self.assertIs(is_valid("359821507X"), True) def test_isbn_without_check_digit_and_dashes(self): self.assertIs(is_valid("359821507"), False) def test_too_long_isbn_and_no_dashes(self): self.assertIs(is_valid("35982...
def test_valid_isbn(self): self.assertIs(is_valid("3-598-21508-8"), True) def test_invalid_isbn_check_digit(self): self.assertIs(is_valid("3-598-21508-9"), False) def test_valid_isbn_with_a_check_digit_of_10(self): self.assertIs(is_valid("3-598-21507-X"), True) def test_check_digi...
identifier_body
isbn_verifier_test.py
import unittest from isbn_verifier import is_valid # Tests adapted from `problem-specifications//canonical-data.json` class IsbnVerifierTest(unittest.TestCase): def test_valid_isbn(self): self.assertIs(is_valid("3-598-21508-8"), True) def test_invalid_isbn_check_digit(self): self.assertIs(i...
(self): self.assertIs(is_valid("3-598-2X507-9"), False) def test_valid_isbn_without_separating_dashes(self): self.assertIs(is_valid("3598215088"), True) def test_isbn_without_separating_dashes_and_x_as_check_digit(self): self.assertIs(is_valid("359821507X"), True) def test_isbn_wi...
test_x_is_only_valid_as_a_check_digit
identifier_name
isbn_verifier_test.py
import unittest from isbn_verifier import is_valid # Tests adapted from `problem-specifications//canonical-data.json` class IsbnVerifierTest(unittest.TestCase): def test_valid_isbn(self): self.assertIs(is_valid("3-598-21508-8"), True) def test_invalid_isbn_check_digit(self): self.assertIs(i...
def test_isbn_without_separating_dashes_and_x_as_check_digit(self): self.assertIs(is_valid("359821507X"), True) def test_isbn_without_check_digit_and_dashes(self): self.assertIs(is_valid("359821507"), False) def test_too_long_isbn_and_no_dashes(self): self.assertIs(is_valid("35982...
self.assertIs(is_valid("3-598-2X507-9"), False) def test_valid_isbn_without_separating_dashes(self): self.assertIs(is_valid("3598215088"), True)
random_line_split
wrapExternalDocumentWriter.ts
import { Document, Element, Node } from '../types/Types'; import IDocumentWriter from './IDocumentWriter'; class WrappingDocumentWriter implements IDocumentWriter { private _externalDocumentWriter: IDocumentWriter; constructor(externalDocumentWriter: IDocumentWriter) { this._externalDocumentWriter = externalDocume...
{ return new WrappingDocumentWriter(externalDocumentWriter); }
identifier_body
wrapExternalDocumentWriter.ts
import { Document, Element, Node } from '../types/Types'; import IDocumentWriter from './IDocumentWriter'; class WrappingDocumentWriter implements IDocumentWriter { private _externalDocumentWriter: IDocumentWriter;
(externalDocumentWriter: IDocumentWriter) { this._externalDocumentWriter = externalDocumentWriter; } public insertBefore(parent: Element | Document, newNode: Node, referenceNode: Node) { return this._externalDocumentWriter['insertBefore'](parent, newNode, referenceNode); } public removeAttributeNS(node: Eleme...
constructor
identifier_name
wrapExternalDocumentWriter.ts
import { Document, Element, Node } from '../types/Types'; import IDocumentWriter from './IDocumentWriter'; class WrappingDocumentWriter implements IDocumentWriter { private _externalDocumentWriter: IDocumentWriter; constructor(externalDocumentWriter: IDocumentWriter) {
} public insertBefore(parent: Element | Document, newNode: Node, referenceNode: Node) { return this._externalDocumentWriter['insertBefore'](parent, newNode, referenceNode); } public removeAttributeNS(node: Element, namespace: string, name: string) { return this._externalDocumentWriter['removeAttributeNS'](nod...
this._externalDocumentWriter = externalDocumentWriter;
random_line_split
schulze_helper.py
# Copyright (C) 2009, Brad Beattie # # This program 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, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in ...
self.actions.append({'nodes': candidates_to_remove}) for candidate in candidates_to_remove: self.graph.del_node(candidate) # If none exist, remove the weakest edges else: edge_weights = self.edge_weights(self.graph) ...
candidates_to_remove |= (set(access[candidate]) - set(mutual_access[candidate])) # Remove nodes at the end of non-cycle paths if len(candidates_to_remove) > 0:
random_line_split
schulze_helper.py
# Copyright (C) 2009, Brad Beattie # # This program 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, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in ...
(CondorcetHelper): def condorcet_completion_method(self): self.schwartz_set_heuristic() def schwartz_set_heuristic(self): # Iterate through using the Schwartz set heuristic self.actions = [] while len(self.graph.edges()) > 0: access = accessibility(self.graph) ...
SchulzeHelper
identifier_name
schulze_helper.py
# Copyright (C) 2009, Brad Beattie # # This program 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, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in ...
def proportional_completion(self, candidate, other_candidates): profile = dict(zip(self.completed_patterns, [0] * len(self.completed_patterns))) # Obtain an initial tally from the ballots for ballot in self.ballots: pattern = [] for other_candidate in other_candida...
self.completed_patterns.append(tuple(pattern))
conditional_block
schulze_helper.py
# Copyright (C) 2009, Brad Beattie # # This program 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, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in ...
def proportional_completion(self, candidate, other_candidates): profile = dict(zip(self.completed_patterns, [0] * len(self.completed_patterns))) # Obtain an initial tally from the ballots for ballot in self.ballots: pattern = [] for other_candidate in other_candida...
self.completed_patterns = [] for i in range(0, self.required_winners + 1): for pattern in unique_permutations( [PREFERRED_LESS] * (self.required_winners - i) + [PREFERRED_MORE] * (i) ): self.completed_patterns.append(tuple(pattern))
identifier_body
pageView.js
define([ 'underscore', 'backbone', 'App', // Views 'searchView', 'listView', 'itemView', 'menuView', 'libraryView' ], function(_, Backbone, App, searchView, listView, itemView, menuView, libraryView) { var pageView = Backbone.View.extend({ el: 'body', /** * Init. */ init: f...
// Libary view if (!App.libraryView) { App.libraryView = new libraryView(); App.libraryView.init().render(); // Add the list view to the views array App.contentViews.push(App.libraryView); } // Search if (!App.searchView) { App.searchV...
{ App.listView = new listView(); App.listView.init().render(); // Add the list view to the views array App.contentViews.push(App.listView); }
conditional_block
pageView.js
define([ 'underscore', 'backbone', 'App', // Views 'searchView', 'listView', 'itemView', 'menuView', 'libraryView' ], function(_, Backbone, App, searchView, listView, itemView, menuView, libraryView) { var pageView = Backbone.View.extend({ el: 'body', /** * Init. */ init: f...
return this; }, /** * Hide item and list views. * @returns {object} This view. */ hideContentViews: function() { _.each(App.contentViews, function(view, i) { view.$el.hide(); }); return this; } }); return pageView; });
}
random_line_split
test_utils.py
""" Tests for SGA utility functions """ import pytest import pytz from edx_sga.tests.common import is_near_now from edx_sga.utils import is_finalized_submission, utcnow @pytest.mark.parametrize( "submission_data,expected_value", [ ({"answer": {"finalized": True}}, True), ({"answer": {"filena...
({"answer": {"finalized": False}}, False), ({"answer": None}, False), ({}, False), ], ) def test_is_finalized_submission(submission_data, expected_value): """Test for is_finalized_submission""" assert is_finalized_submission(submission_data) is expected_value def test_utcnow(): ...
({"answer": {}}, True),
random_line_split
test_utils.py
""" Tests for SGA utility functions """ import pytest import pytz from edx_sga.tests.common import is_near_now from edx_sga.utils import is_finalized_submission, utcnow @pytest.mark.parametrize( "submission_data,expected_value", [ ({"answer": {"finalized": True}}, True), ({"answer": {"filena...
(): """ tznow should return a datetime object in UTC """ now = utcnow() assert is_near_now(now) assert now.tzinfo.zone == pytz.utc.zone
test_utcnow
identifier_name
test_utils.py
""" Tests for SGA utility functions """ import pytest import pytz from edx_sga.tests.common import is_near_now from edx_sga.utils import is_finalized_submission, utcnow @pytest.mark.parametrize( "submission_data,expected_value", [ ({"answer": {"finalized": True}}, True), ({"answer": {"filena...
""" tznow should return a datetime object in UTC """ now = utcnow() assert is_near_now(now) assert now.tzinfo.zone == pytz.utc.zone
identifier_body
data-share-a.component.ts
import { AfterViewChecked, Component, ElementRef, OnDestroy, OnInit } from '@angular/core'; // subscribe を保持するための Subscription を import import { Subscription } from 'rxjs'; // サービスを登録するための import // アプリ全体でのサービスの共有、コンポーネント単位でのサービスの共有に関わらず、ここの import は必要 import { DataShareService } from '../../../service/data-share/dat...
conditional_block
data-share-a.component.ts
import { AfterViewChecked, Component, ElementRef, OnDestroy, OnInit } from '@angular/core'; // subscribe を保持するための Subscription を import import { Subscription } from 'rxjs'; // サービスを登録するための import // アプリ全体でのサービスの共有、コンポーネント単位でのサービスの共有に関わらず、ここの import は必要 import { DataShareService } from '../../../service/data-share/dat...
identifier_body
data-share-a.component.ts
import { AfterViewChecked, Component, ElementRef, OnDestroy, OnInit } from '@angular/core'; // subscribe を保持するための Subscription を import import { Subscription } from 'rxjs'; // サービスを登録するための import // アプリ全体でのサービスの共有、コンポーネント単位でのサービスの共有に関わらず、ここの import は必要 import { DataShareService } from '../../../service/data-share/dat...
*/ onClicSendMessage() { // DataShareService のデータ更新を行う console.log('[Component-A] onClicSendMessage fired.'); this.dataShareService.onNotifySharedDataChanged('Updated by Component-A.'); } }
} } /** * ボタンクリック時のイベントハンドラ
random_line_split
data-share-a.component.ts
import { AfterViewChecked, Component, ElementRef, OnDestroy, OnInit } from '@angular/core'; // subscribe を保持するための Subscription を import import { Subscription } from 'rxjs'; // サービスを登録するための import // アプリ全体でのサービスの共有、コンポーネント単位でのサービスの共有に関わらず、ここの import は必要 import { DataShareService } from '../../../service/data-share/dat...
を保持するための Subscription * * @private * @type {Subscription} */ private subscription!: Subscription; /** * サービスで共有するデータが更新されたかをチェックするためのデータ * * @type {string} */ private preData: string = this.serviceProp; /** * コンストラクタ. ServiceSample1Component のインスタンスを生成する * * @param dataShareS...
/** * subscribe
identifier_name
logarithmInformation.py
''' Created on 13.09.2016 @author: mkennert ''' from kivy.properties import StringProperty from materialLawEditor.ainformation import AInformation from ownComponents.design import Design from ownComponents.numpad import Numpad from ownComponents.ownButton import OwnButton from ownComponents.ownLabel import...
''' create the gui of the information, where you can change the properties of the quadratic-function ''' def create_information(self): self.create_btns() self.add_widget(OwnLabel(text=self.functionStr)) self.add_widget(self.btnExponential) s...
super(LogarithmInformation, self).__init__(**kwargs) self.cols, self.spacing = 2, Design.spacing self.create_information() # create the numpad self.numpad = Numpad(sign=True, p=self) self.popupNumpad = OwnPopup(content=self.numpad)
identifier_body
logarithmInformation.py
''' Created on 13.09.2016 @author: mkennert ''' from kivy.properties import StringProperty from materialLawEditor.ainformation import AInformation from ownComponents.design import Design from ownComponents.numpad import Numpad from ownComponents.ownButton import OwnButton from ownComponents.ownLabel import...
the method finished_numpad close the numpad_popup ''' def finished_numpad(self): v = float(self.numpad.lblTextinput.text) if self.focusBtn == self.aBtn: if v > 0: self.editor.a = v else: return elif self.focusBtn ...
random_line_split
logarithmInformation.py
''' Created on 13.09.2016 @author: mkennert ''' from kivy.properties import StringProperty from materialLawEditor.ainformation import AInformation from ownComponents.design import Design from ownComponents.numpad import Numpad from ownComponents.ownButton import OwnButton from ownComponents.ownLabel import...
self.editor.view.update_graph_sizeproperties() self.focusBtn.text = str(v) self.popupNumpad.dismiss() self.numpad.reset_text() ''' open the numpad popup ''' def show_popup(self, btn): self.focusBtn = btn if self.focusBtn == self.aBtn...
return
conditional_block
logarithmInformation.py
''' Created on 13.09.2016 @author: mkennert ''' from kivy.properties import StringProperty from materialLawEditor.ainformation import AInformation from ownComponents.design import Design from ownComponents.numpad import Numpad from ownComponents.ownButton import OwnButton from ownComponents.ownLabel import...
(self): v = float(self.numpad.lblTextinput.text) if self.focusBtn == self.aBtn: if v > 0: self.editor.a = v else: return elif self.focusBtn == self.bBtn: if v != 0: self.editor.b = v else: ...
finished_numpad
identifier_name
mainController.js
angular.module('mainController',[]) .controller('mainController', function($rootScope, $location, Auth){ var vm = this; vm.loggedIn = Auth.isLoggedIn(); // o rootscope é usado para detectar alterações na rota // quando acontecer uma troca de rota (requisicao para outra pagina) verifica se tem um usuário logado...
vm.processing = true; //variavel para mostrar q ta fazendo alguma coisa Auth.login(vm.loginData.username, vm.loginData.password) .success(function(data){ vm.processing = false; if (data.success) $location.path('/users'); //se conseguiu logar, manda pra página de usuários else vm.error = data.me...
}); // gerenciar o form de login vm.doLogin = function() {
random_line_split
rainx-monitor.py
#!/usr/bin/python import sys import urllib2 RAINX_STAT_KEYS = [ ("rainx.reqpersec", "total_reqpersec"), ("rainx.reqputpersec", "put_reqpersec"), ("rainx.reqgetpersec", "get_reqpersec"), ("rainx.avreqtime", "total_avreqtime"), ("rainx.avputreqtime", "put_avreqtime"), ("rainx.avgetreqtime", "get_avreqtime"), ] ...
(stream): data = {} for line in stream.readlines(): parts = line.split() if len(parts) > 1: # try to cast value to int or float try: value = int(parts[1]) except ValueError: try: value = float(parts[1]) ...
parse_info
identifier_name
rainx-monitor.py
#!/usr/bin/python import sys import urllib2 RAINX_STAT_KEYS = [ ("rainx.reqpersec", "total_reqpersec"), ("rainx.reqputpersec", "put_reqpersec"), ("rainx.reqgetpersec", "get_reqpersec"), ("rainx.avreqtime", "total_avreqtime"), ("rainx.avputreqtime", "put_avreqtime"), ("rainx.avgetreqtime", "get_avreqtime"), ] ...
if __name__ == "__main__": main(sys.argv)
ip_port = args[1].split("|")[2] stats_url = "http://%s/stat" % ip_port for stat in get_stat_lines(stats_url, RAINX_STAT_KEYS): print stat
identifier_body
rainx-monitor.py
#!/usr/bin/python import sys import urllib2 RAINX_STAT_KEYS = [ ("rainx.reqpersec", "total_reqpersec"), ("rainx.reqputpersec", "put_reqpersec"), ("rainx.reqgetpersec", "get_reqpersec"), ("rainx.avreqtime", "total_avreqtime"), ("rainx.avputreqtime", "put_avreqtime"), ("rainx.avgetreqtime", "get_avreqtime"), ] ...
return data def get_stat_lines(url, stat_keys): stream = urllib2.urlopen(url) data = parse_info(stream) stream.close() stats = [("stat.%s = %s" % (k[1], str(data[k[0]]))) for k in stat_keys if k[0] in data] return stats def main(args): ip_port = args[1].split("|")[2] stats...
data[parts[0]] = None
conditional_block
rainx-monitor.py
#!/usr/bin/python import sys import urllib2 RAINX_STAT_KEYS = [ ("rainx.reqpersec", "total_reqpersec"), ("rainx.reqputpersec", "put_reqpersec"), ("rainx.reqgetpersec", "get_reqpersec"), ("rainx.avreqtime", "total_avreqtime"), ("rainx.avputreqtime", "put_avreqtime"), ("rainx.avgetreqtime", "get_avreqtime"), ] ...
value = int(parts[1]) except ValueError: try: value = float(parts[1]) except ValueError: value = parts[1] data[parts[0]] = value else: data[parts[0]] = None return data def get_stat_l...
parts = line.split() if len(parts) > 1: # try to cast value to int or float try:
random_line_split
__init__.py
### # Copyright (c) 2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditi...
# Use this for the version of this plugin. You may wish to put a CVS keyword # in here if you're keeping the plugin in CVS or some similar system. __version__ = "%%VERSION%%" # XXX Replace this with an appropriate author or supybot.Author instance. __author__ = supybot.authors.jemfinch # This is a dictionary mappin...
import supybot import supybot.world as world
random_line_split
__init__.py
### # Copyright (c) 2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditi...
Class = plugin.Class configure = config.configure # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
from . import test
conditional_block
state.ts
import { SongNode, SongTree, NoteSongNode, SongTransformationCollection } from '../song-tree' export type SongState = { songNodeStates: SongNodeState[]; } export type SongNodeState = { childrenIds: number[]; songNode: SongNode; } // Start with one item with id 0, it will be the root SongNode. export const ini...
/** * Transforms the flat redux-friendly SongState into a SongTree. */ export function toSongTree(state: SongState) : SongTree { let songNodeStates = state.songNodeStates; // Clone all the SongNodes so we can mutate them within this function. songNodeStates = songNodeStates.map((state) => { let songNode = ...
random_line_split
state.ts
import { SongNode, SongTree, NoteSongNode, SongTransformationCollection } from '../song-tree' export type SongState = { songNodeStates: SongNodeState[]; } export type SongNodeState = { childrenIds: number[]; songNode: SongNode; } // Start with one item with id 0, it will be the root SongNode. export const ini...
(state: SongState) : SongTree { let songNodeStates = state.songNodeStates; // Clone all the SongNodes so we can mutate them within this function. songNodeStates = songNodeStates.map((state) => { let songNode = state.songNode.clone(); return { ...state, songNode: songNode }; }); // G...
toSongTree
identifier_name
state.ts
import { SongNode, SongTree, NoteSongNode, SongTransformationCollection } from '../song-tree' export type SongState = { songNodeStates: SongNodeState[]; } export type SongNodeState = { childrenIds: number[]; songNode: SongNode; } // Start with one item with id 0, it will be the root SongNode. export const ini...
return new SongTree(songNodeStates[0].songNode); }
{ let songNodeStates = state.songNodeStates; // Clone all the SongNodes so we can mutate them within this function. songNodeStates = songNodeStates.map((state) => { let songNode = state.songNode.clone(); return { ...state, songNode: songNode }; }); // Get rid of the ids and actually...
identifier_body
suggestions.rs
use app::App; // Third Party #[cfg(feature = "suggestions")] use strsim; // Internal use fmt::Format; /// Produces a string from a given list of possible values which is similar to /// the passed in value `v` with a certain confidence. /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yi...
<'z, T, I>( arg: &str, args_rest: &'z [&str], longs: I, subcommands: &'z [App], ) -> (String, Option<&'z str>) where T: AsRef<str> + 'z, I: IntoIterator<Item = &'z T>, { if let Some(candidate) = did_you_mean(arg, longs) { let suffix = format!( "\n\tDid you mean {}{}?", ...
did_you_mean_flag_suffix
identifier_name
suggestions.rs
use app::App; // Third Party #[cfg(feature = "suggestions")] use strsim; // Internal use fmt::Format; /// Produces a string from a given list of possible values which is similar to /// the passed in value `v` with a certain confidence. /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yi...
subcommands .into_iter() .filter_map(|subcommand| { let opts = subcommand .p .flags .iter() .filter_map(|f| f.s.long) .chain(subcommand.p.opts.iter().filter_map(|o| o.s.long)); let candidate = ...
{ let suffix = format!( "\n\tDid you mean {}{}?", Format::Good("--"), Format::Good(candidate) ); return (suffix, Some(candidate)); }
conditional_block
suggestions.rs
use app::App; // Third Party #[cfg(feature = "suggestions")] use strsim; // Internal use fmt::Format; /// Produces a string from a given list of possible values which is similar to /// the passed in value `v` with a certain confidence. /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yi...
/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase #[cfg_attr(feature = "lints", allow(needless_lifetimes))] pub fn did_you_mean_flag_suffix<'z, T, I>( arg: &str, args_rest: &'z [&str], longs: I, subcommands: &'z [App], ) -> (String, Option<&'z str>) where T: AsRef<st...
{ None }
identifier_body
suggestions.rs
use app::App; // Third Party #[cfg(feature = "suggestions")] use strsim; // Internal use fmt::Format; /// Produces a string from a given list of possible values which is similar to /// the passed in value `v` with a certain confidence. /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yi...
I: IntoIterator<Item = &'a T>, { None } /// Returns a suffix that can be empty, or is the standard 'did you mean' phrase #[cfg_attr(feature = "lints", allow(needless_lifetimes))] pub fn did_you_mean_flag_suffix<'z, T, I>( arg: &str, args_rest: &'z [&str], longs: I, subcommands: &'z [App], ) -> ...
pub fn did_you_mean<'a, T: ?Sized, I>(_: &str, _: I) -> Option<&'a str> where T: AsRef<str> + 'a,
random_line_split
attr.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use std::ops::Deref; use string_cache::{Atom, Namespace}; use util::str::{DOMString, LengthOr...
pub fn from_atomic(string: DOMString) -> AttrValue { // FIXME(ajeffrey): convert directly from DOMString to Atom let value = Atom::from(&*string); AttrValue::Atom(value) } pub fn from_legacy_color(string: DOMString) -> AttrValue { let parsed = parse_legacy_color(&string).ok...
AttrValue::UInt(string, result) }
random_line_split
attr.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use std::ops::Deref; use string_cache::{Atom, Namespace}; use util::str::{DOMString, LengthOr...
(string: DOMString) -> AttrValue { let parsed = parse_legacy_color(&string).ok(); AttrValue::Color(string, parsed) } pub fn from_dimension(string: DOMString) -> AttrValue { let parsed = parse_length(&string); AttrValue::Dimension(string, parsed) } /// Assumes the `AttrV...
from_legacy_color
identifier_name
attr.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use std::ops::Deref; use string_cache::{Atom, Namespace}; use util::str::{DOMString, LengthOr...
// https://html.spec.whatwg.org/multipage/#reflecting-content-attributes-in-idl-attributes:idl-unsigned-long pub fn from_u32(string: DOMString, default: u32) -> AttrValue { let result = parse_unsigned_integer(string.chars()).unwrap_or(default); let result = if result > UNSIGNED_LONG_MAX { ...
{ // TODO(ajeffrey): effecient conversion of Vec<Atom> to DOMString let tokens = DOMString::from(str_join(&atoms, "\x20")); AttrValue::TokenList(tokens, atoms) }
identifier_body
runner.ts
import {Injector, bind, provide, Provider} from 'angular2/src/core/di'; import {isPresent, isBlank} from 'angular2/src/core/facade/lang'; import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async'; import {Sampler, SampleState} from './sampler'; import {ConsoleReporter} from './reporter/console_reporter'; ...
/** * The Runner is the main entry point for executing a sample run. * It provides defaults, creates the injector and calls the sampler. */ export class Runner { private _defaultBindings: Provider[]; constructor(defaultBindings: Provider[] = null) { if (isBlank(defaultBindings)) { defaultBindings = [];...
import {Metric} from './metric'; import {Options} from './common_options';
random_line_split
runner.ts
import {Injector, bind, provide, Provider} from 'angular2/src/core/di'; import {isPresent, isBlank} from 'angular2/src/core/facade/lang'; import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async'; import {Sampler, SampleState} from './sampler'; import {ConsoleReporter} from './reporter/console_reporter'; ...
return PromiseWrapper .all([adapter.capabilities(), adapter.executeScript('return window.navigator.userAgent;')]) .then((args) => { var capabilities = args[0]; var userAgent = args[1]; // This might still create instances twice. We are creating a new injector with all ...
{ var sampleBindings = [ _DEFAULT_PROVIDERS, this._defaultBindings, bind(Options.SAMPLE_ID).toValue(id), bind(Options.EXECUTE).toValue(execute) ]; if (isPresent(prepare)) { sampleBindings.push(bind(Options.PREPARE).toValue(prepare)); } if (isPresent(microMetrics)) { ...
identifier_body
runner.ts
import {Injector, bind, provide, Provider} from 'angular2/src/core/di'; import {isPresent, isBlank} from 'angular2/src/core/facade/lang'; import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async'; import {Sampler, SampleState} from './sampler'; import {ConsoleReporter} from './reporter/console_reporter'; ...
this._defaultBindings = defaultBindings; } sample({id, execute, prepare, microMetrics, bindings}): Promise<SampleState> { var sampleBindings = [ _DEFAULT_PROVIDERS, this._defaultBindings, bind(Options.SAMPLE_ID).toValue(id), bind(Options.EXECUTE).toValue(execute) ]; if (isP...
{ defaultBindings = []; }
conditional_block
runner.ts
import {Injector, bind, provide, Provider} from 'angular2/src/core/di'; import {isPresent, isBlank} from 'angular2/src/core/facade/lang'; import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async'; import {Sampler, SampleState} from './sampler'; import {ConsoleReporter} from './reporter/console_reporter'; ...
{ private _defaultBindings: Provider[]; constructor(defaultBindings: Provider[] = null) { if (isBlank(defaultBindings)) { defaultBindings = []; } this._defaultBindings = defaultBindings; } sample({id, execute, prepare, microMetrics, bindings}): Promise<SampleState> { var sampleBindings =...
Runner
identifier_name
unsized7.rs
// Copyright 2014 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 ...
trait T {} // I would like these to fail eventually. // impl - bounded trait T1<Z: T> { } struct S3<Y: ?Sized>; impl<X: ?Sized + T> T1<X> for S3<X> { //~^ ERROR `core::marker::Sized` is not implemented for the type `X` } fn main() { }
// option. This file may not be copied, modified, or distributed // except according to those terms. // Test sized-ness checking in substitution in impls.
random_line_split
unsized7.rs
// Copyright 2014 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 ...
() { }
main
identifier_name
unsized7.rs
// Copyright 2014 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 ...
{ }
identifier_body
clause.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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, either version 3 of the License, or // (at your option) any later ver...
} write!(formatter, " }}") } }
{ try!(write!(formatter, ", ")); }
conditional_block
clause.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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, either version 3 of the License, or // (at your option) any later ver...
} /// Set the ID of the clause. /// The IDs should be unique so care must be taken. pub fn set_id(&mut self, new_id: u64) { self.id = Some(new_id); } /// Get the ID of the clause. pub fn get_id(&self) -> u64 { self.id.expect("ID should always exist") } } impl In...
/// Calculates the symbol count with given weights to function and variable symbols. pub fn symbol_count(&self, f_value: u64, v_value: u64) -> u64 { self.iter().fold(0, |acc, l| acc + l.symbol_count(f_value, v_value))
random_line_split
clause.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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, either version 3 of the License, or // (at your option) any later ver...
(&mut self, index: usize) -> Literal { self.literals.swap_remove(index) } /// Add the literal to the clause (without checking for duplicates). pub fn add_literal(&mut self, l: Literal) { self.literals.push(l); } /// Add the literals in a given clause to this clause (without checkin...
swap_remove
identifier_name
clause.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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, either version 3 of the License, or // (at your option) any later ver...
} impl Index<usize> for Clause { type Output = Literal; fn index(&self, index: usize) -> &Literal { &self.literals[index] } } impl Debug for Clause { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { try!(write!(formatter, "{{ ")); for (i, l) in self.iter().enum...
{ self.id.expect("ID should always exist") }
identifier_body
lru.rs
use std::time::*; use std::hash::Hash; use lru_cache::LruCache; // A cache that allows for per-value timeout invalidation pub enum LRUEntry<T> { Present(T), Expired, Vacant, } pub struct LRU<'a, K: 'a + Hash + Eq, T> { cache: LruCache<&'a K, (T, Instant, Duration)>, hits: u128, misses: u128, ...
fn is_timed_out(then: Instant, dur: Duration) -> bool { let age = then.elapsed(); if age >= dur { false } else { true } } }
{ let (val, then, lifespan) = match self.cache.get_mut(key) { Some(&mut (ref val, then, lifespan)) => (val as *const T, then, lifespan), None => { self.misses += 1; return LRUEntry::Vacant; } }; if Self::is_timed_out(then, life...
identifier_body
lru.rs
use std::time::*; use std::hash::Hash; use lru_cache::LruCache; // A cache that allows for per-value timeout invalidation pub enum LRUEntry<T> { Present(T), Expired, Vacant, } pub struct
<'a, K: 'a + Hash + Eq, T> { cache: LruCache<&'a K, (T, Instant, Duration)>, hits: u128, misses: u128, exp_misses: u128, } impl<'a, K, T> LRU<'a, K, T> where K: Hash + Eq { pub fn new(limit: usize) -> LRU<'a, K, T> { LRU { cache: LruCache::new(limit), hits: 1, ...
LRU
identifier_name
lru.rs
use std::time::*; use std::hash::Hash; use lru_cache::LruCache; // A cache that allows for per-value timeout invalidation pub enum LRUEntry<T> { Present(T), Expired, Vacant, } pub struct LRU<'a, K: 'a + Hash + Eq, T> { cache: LruCache<&'a K, (T, Instant, Duration)>, hits: u128, misses: u128, ...
} fn is_timed_out(then: Instant, dur: Duration) -> bool { let age = then.elapsed(); if age >= dur { false } else { true } } }
{ self.hits += 1; LRUEntry::Present(unsafe { &*val }) }
conditional_block
lru.rs
use std::time::*; use std::hash::Hash; use lru_cache::LruCache; // A cache that allows for per-value timeout invalidation pub enum LRUEntry<T> { Present(T), Expired, Vacant, } pub struct LRU<'a, K: 'a + Hash + Eq, T> { cache: LruCache<&'a K, (T, Instant, Duration)>, hits: u128, misses: u128, ...
if Self::is_timed_out(then, lifespan) { self.cache.remove(key); self.exp_misses += 1; LRUEntry::Expired } else { self.hits += 1; LRUEntry::Present(unsafe { &*val }) } } fn is_timed_out(then: Instant, dur: Duration) -> bool { ...
random_line_split
hostList.js
Template.HostList.events({ }); Template.HostList.helpers({ // Get list of Hosts sorted by the sort field.
}); Template.HostList.rendered = function () { // Make rows sortable/draggable using Jquery-UI. this.$('#sortable').sortable({ stop: function (event, ui) { // Define target row items. target = ui.item.get(0); before = ui.item.prev().get(0); after = ui.item.next().get(0); // Cha...
hosts: function () { return Hosts.find({}, {sort: {sort: 1}}); }
random_line_split
hostList.js
Template.HostList.events({ }); Template.HostList.helpers({ // Get list of Hosts sorted by the sort field. hosts: function () { return Hosts.find({}, {sort: {sort: 1}}); } }); Template.HostList.rendered = function () { // Make rows sortable/draggable using Jquery-UI. this.$('#sortable').sortable({ ...
else if (!after) { newSort = Blaze.getData(before).sort + 1; // Get value of prev and next elements // to determine new target sort value. } else { newSort = (Blaze.getData(after).sort + Blaze.getData(before).sort) / 2; } // Update the database with new ...
{ newSort = Blaze.getData(after).sort - 1; // If target is now last, add 1 to sort value. }
conditional_block
Hotkey.tsx
import { useEffect } from 'react' export interface KeyDefinition { /** Description */ children?: string /** Key assignment */ keyName: string /** HotKey 定義 */ title?: string } export interface KeyAction { (event: KeyboardEvent): void } export interface HotkeyProps extends KeyDefinition { action: KeyA...
export const Hotkey = ({ action, disabled, keyName }: HotkeyProps) => { useEffect(() => { if (disabled) return return attach(keyName, action) }) return null } export const getHotkeyHint = ({ children, keyName, title }: KeyDefinition) => `${children}(${title || keyName.toUpperCase()})`
} }
random_line_split
sl-ls.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USER...
ffset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next s...
h_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, o
identifier_body
sl-ls.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USER...
r""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # ----------------------------------------...
t of SoftLayer_User_Custome
conditional_block
sl-ls.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USER...
# for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCI...
# Virtual guest OSes
random_line_split
sl-ls.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USER...
self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() ...
identifier_name
queued.rs
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 USE OR OTHER ...
fn get_brand(&self) -> usize {
random_line_split
queued.rs
to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ...
let _ = waiter.send(()); } this.borrow_mut().promise_to_drive = ForkedPromise::new(Promise::ok(())); } } pub struct PipelineInnerSender { inner: Option<Weak<RefCell<PipelineInner>>>, } impl Drop for PipelineInnerSender { fn drop(&mut self) { if let Some(weak_queued) =...
{ let clienthook = pipeline.get_pipelined_cap_move(ops); ClientInner::resolve(&client, Ok(clienthook)); }
conditional_block
queued.rs
NOT LIMITED 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...
get_brand
identifier_name
queued.rs
to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ...
fn call(&self, interface_id: u64, method_id: u16, params: Box<ParamsHook>, results: Box<ResultsHook>) -> Promise<(), Error> { if let Some(ref client) = self.inner.borrow().redirect { return client.call(interface_id, method_id, params, results) } let inner_clone = se...
{ ::capnp::capability::Request::new( Box::new(local::Request::new(interface_id, method_id, size_hint, self.add_ref()))) }
identifier_body
dispatcher.js
'use strict'; var _ = require('lodash'); var Bacon = require('baconjs'); var logger = require('./logger'); var bus = new Bacon.Bus(); var dirtyStores = []; var dispatching = false; function dispatch(type, payload) { if (dispatching)
return new Promise(function (resolve, reject) { dispatching = true; logger.logMessage(type, payload); try { bus.push({type: type, payload: payload}); pushChanges(); resolve(); } finally { logger.logMessageEnd(); dispatching = false; } }); } function input(type) { ...
{ return Promise.reject('Cascading dispatches are prohibited. Fix your flux.'); }
conditional_block
dispatcher.js
'use strict'; var _ = require('lodash'); var Bacon = require('baconjs'); var logger = require('./logger'); var bus = new Bacon.Bus(); var dirtyStores = []; var dispatching = false; function dispatch(type, payload) { if (dispatching) { return Promise.reject('Cascading dispatches are prohibited. Fix your flux.')...
logger.logDirtyStores(dirtyStores, also); pushChangesOnce(); also = true; } } module.exports = { dispatch: dispatch, input: input, markStoreAsDirty: markStoreAsDirty };
return; } var also = false; while(dirtyStores.length > 0) {
random_line_split
dispatcher.js
'use strict'; var _ = require('lodash'); var Bacon = require('baconjs'); var logger = require('./logger'); var bus = new Bacon.Bus(); var dirtyStores = []; var dispatching = false; function
(type, payload) { if (dispatching) { return Promise.reject('Cascading dispatches are prohibited. Fix your flux.'); } return new Promise(function (resolve, reject) { dispatching = true; logger.logMessage(type, payload); try { bus.push({type: type, payload: payload}); pushChanges(); ...
dispatch
identifier_name
dispatcher.js
'use strict'; var _ = require('lodash'); var Bacon = require('baconjs'); var logger = require('./logger'); var bus = new Bacon.Bus(); var dirtyStores = []; var dispatching = false; function dispatch(type, payload) { if (dispatching) { return Promise.reject('Cascading dispatches are prohibited. Fix your flux.')...
function pushChanges() { if (!dirtyStores.length) { logger.logNoDirtyStores(); return; } var also = false; while(dirtyStores.length > 0) { logger.logDirtyStores(dirtyStores, also); pushChangesOnce(); also = true; } } module.exports = { dispatch: dispatch, input: input, markStoreAs...
{ var stores = dirtyStores; dirtyStores = []; _.each(stores, function (store) { store.changes.push(store.output); }); }
identifier_body
doc.ts
/** * Dongo MD (AKA Doc AKA the (good) doctor) - Not entirely sure everything he can do, but for now he will just store the twins research for them */ // The doc brought his trusty pet - she's smarter than she looks, don't worry import * as Mango from "mongoose"; // Bot has taken a liking to the good doctor since h...
(id, location?: string) { super("Doc", id); // "Now where did Mango go off to today..." location = location || "mongodb://127.0.0.1:27017/DTND"; Mango.connect(location); this.db = Mango.connection; this.db.on('open', this.onMangoFound); this.db.on('err...
constructor
identifier_name
doc.ts
/** * Dongo MD (AKA Doc AKA the (good) doctor) - Not entirely sure everything he can do, but for now he will just store the twins research for them */ // The doc brought his trusty pet - she's smarter than she looks, don't worry import * as Mango from "mongoose"; // Bot has taken a liking to the good doctor since h...
* "Mango - would you go file this for me?" */ addDocumentToDataStore(message: Discord.Message) { new this.Models.Message({ server: message.guild, channel: message.channel, author: message.author, message: message.content, date: message.ti...
/**
random_line_split
vidstreamer.ts
Request?: boolean; modified?: Date; size?: number; end?: number; start?: number; path?: string; } const vidStreamer = function (req, res) { let stream; let stat; const info: StreamInfo = {}; let range = typeof req.headers.range === 'string' ? req.headers.range : undefined; const...
(res, info) { let code = 200; let header; // 'Connection':'close', // 'Cache-Control':'private', // 'Transfer-Encoding':'chunked' if (settings.forceDownload) { header = { Expires: 0, 'Cache-Control': 'must-revalidate, post-check=0, pre-check=0', //"C...
downloadHeader
identifier_name
vidstreamer.ts
Request?: boolean; modified?: Date; size?: number; end?: number; start?: number; path?: string; } const vidStreamer = function (req, res) { let stream; let stat; const info: StreamInfo = {}; let range = typeof req.headers.range === 'string' ? req.headers.range : undefined; const...
handler.emit('badRequest', res); return false; } } settings.getFile(info.path, function (filePath) { if (generatePlaylist === 'm3u8') { ff.ffprobe(filePath, (err, metadata) => { function writePlayList(frames?) { function fr...
} catch (exception) { // Can throw URI malformed exception.
random_line_split
vidstreamer.ts
Request?: boolean; modified?: Date; size?: number; end?: number; start?: number; path?: string; } const vidStreamer = function (req, res) { let stream; let stat; const info: StreamInfo = {}; let range = typeof req.headers.range === 'string' ? req.headers.range : undefined; const...
handler.on('badFile', function (res, e) { errorHeader(res, 404); res.end('<!DOCTYPE html><html lang="en">' + '<head><title>404 Not found</title></head>' + '<body>' + '<h1>Ooh dear</h1>' + '<p>Sorry, I can\'t find that file. Could you check again?</p>' + '</body></html>'...
{ let result = ''; let pos = 1; const len = arguments.length; for (; pos < len; pos++) { if (format[pos - 1] === 'N') { result += String.fromCharCode(arguments[pos] >> 24 & 0xFF); result += String.fromCharCode(arguments[pos] >> 16 & 0xFF); result += String.fr...
identifier_body
vidstreamer.ts
Request?: boolean; modified?: Date; size?: number; end?: number; start?: number; path?: string; } const vidStreamer = function (req, res) { let stream; let stat; const info: StreamInfo = {}; let range = typeof req.headers.range === 'string' ? req.headers.range : undefined; const...
} }); }; vidStreamer.settings = function (s) { Object.assign(settings, s); return vidStreamer; }; function downloadHeader(res, info) { let code = 200; let header; // 'Connection':'close', // 'Cache-Control':'private', // 'Transfer-Encoding':'chunked' if (settings.forceDo...
{ res.end(); }
conditional_block
table-overview-example.ts
import {Component, ElementRef, ViewChild} from '@angular/core'; import {DataSource} from '@angular/cdk'; import {MdPaginator, MdSort, SelectionModel} from '@angular/material'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/startWith'; import '...
}); } isAllSelected(): boolean { if (!this.dataSource) { return false; } if (this.selection.isEmpty()) { return false; } if (this.filter.nativeElement.value) { return this.selection.selected.length == this.dataSource.renderedData.length; } else { return this.selection.selected....
random_line_split
table-overview-example.ts
import {Component, ElementRef, ViewChild} from '@angular/core'; import {DataSource} from '@angular/cdk'; import {MdPaginator, MdSort, SelectionModel} from '@angular/material'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/startWith'; import '...
() { // Fill up the database with 100 users. for (let i = 0; i < 100; i++) { this.addUser(); } } /** Adds a new user to the database. */ addUser() { const copiedData = this.data.slice(); copiedData.push(this.createNewUser()); this.dataChange.next(copiedData); } /** Builds and returns a n...
constructor
identifier_name
table-overview-example.ts
import {Component, ElementRef, ViewChild} from '@angular/core'; import {DataSource} from '@angular/cdk'; import {MdPaginator, MdSort, SelectionModel} from '@angular/material'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/startWith'; import '...
if (this.isAllSelected()) { this.selection.clear(); } else if (this.filter.nativeElement.value) { this.dataSource.renderedData.forEach(data => this.selection.select(data.id)); } else { this.exampleDatabase.data.forEach(data => this.selection.select(data.id)); } } } /** Constants u...
{ return; }
conditional_block
table-overview-example.ts
import {Component, ElementRef, ViewChild} from '@angular/core'; import {DataSource} from '@angular/cdk'; import {MdPaginator, MdSort, SelectionModel} from '@angular/material'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/startWith'; import '...
/** Builds and returns a new User. */ private createNewUser() { const name = NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' + NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.'; return { id: (this.data.length + 1).toString(), name: name, p...
{ const copiedData = this.data.slice(); copiedData.push(this.createNewUser()); this.dataChange.next(copiedData); }
identifier_body
sub.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 ...
_ => { super_tys(self, a, b) } } } fn binders<T>(&self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> cres<'tcx, ty::Binder<T>> where T : Combineable<'tcx> { self.higher_ranked_sub(a, b) } }
{ Ok(self.tcx().types.err) }
conditional_block
sub.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 ...
<'a>(&'a self) -> Sub<'a, 'tcx> { Sub(self.fields.clone()) } fn lub<'a>(&'a self) -> Lub<'a, 'tcx> { Lub(self.fields.clone()) } fn glb<'a>(&'a self) -> Glb<'a, 'tcx> { Glb(self.fields.clone()) } fn contratys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> { Sub(self.fields.switch_expected(...
sub
identifier_name
sub.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 mts(&self, a: &ty::mt<'tcx>, b: &ty::mt<'tcx>) -> cres<'tcx, ty::mt<'tcx>> { debug!("mts({} <: {})", a.repr(self.tcx()), b.repr(self.tcx())); if a.mutbl != b.mutbl { return Err(ty::terr_mutability); } match b.mutbl { MutMut...
{ debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); self.infcx().region_vars.make_subregion(Subtype(self.trace()), a, b); Ok(a) }
identifier_body
sub.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 mts(&self, a: &ty::mt<'tcx>, b: &ty::mt<'tcx>) -> cres<'tcx, ty::mt<'tcx>> { debug!("mts({} <: {})", a.repr(self.tcx()), b.repr(self.tcx())); if a.mutbl != b.mutbl { return Err(ty::terr_mutability); } match b.mutbl { MutMutab...
b.repr(self.tcx())); self.infcx().region_vars.make_subregion(Subtype(self.trace()), a, b); Ok(a) }
random_line_split
attributes.rs
use std::collections::HashMap; use std::collections::hash_map::Iter; use super::attribute::Attribute; static dataPrefix: &'static str = "data-"; pub struct Attributes { attributes: HashMap<String, Attribute>, } impl Attributes { pub fn new() -> Attributes { Attributes { attributes: HashMap::<String, Attribute>:...
pub fn has_key(&self, key: &str) -> bool { self.attributes.contains_key(key) } pub fn size(&self) -> usize { self.attributes.len() } pub fn iter(&self) -> Iter<String, Attribute> { self.attributes.iter() } pub fn add_all(&mut self, attributes: &Attributes) { if attributes.size() > 0 { for (key, v...
{ self.attributes.remove(key); }
identifier_body
attributes.rs
use std::collections::HashMap; use std::collections::hash_map::Iter; use super::attribute::Attribute; static dataPrefix: &'static str = "data-"; pub struct Attributes { attributes: HashMap<String, Attribute>, } impl Attributes { pub fn new() -> Attributes { Attributes { attributes: HashMap::<String, Attribute>:...
} } impl Clone for Attributes { fn clone(&self) -> Attributes { Attributes { attributes: self.attributes.clone() } } }
{ for (key, value) in attributes.iter() { self.attributes.insert(key.to_string(), value.clone()); } }
conditional_block
attributes.rs
use std::collections::HashMap; use std::collections::hash_map::Iter; use super::attribute::Attribute; static dataPrefix: &'static str = "data-"; pub struct Attributes { attributes: HashMap<String, Attribute>, } impl Attributes { pub fn new() -> Attributes { Attributes { attributes: HashMap::<String, Attribute>:...
(&mut self, attribute: Attribute) { self.attributes.insert(attribute.get_value(), attribute.clone()); } pub fn remove(&mut self, key: &str) { self.attributes.remove(key); } pub fn has_key(&self, key: &str) -> bool { self.attributes.contains_key(key) } pub fn size(&self) -> usize { self.attributes.len()...
put_attribute
identifier_name
attributes.rs
use std::collections::HashMap; use std::collections::hash_map::Iter; use super::attribute::Attribute; static dataPrefix: &'static str = "data-"; pub struct Attributes { attributes: HashMap<String, Attribute>, } impl Attributes { pub fn new() -> Attributes { Attributes { attributes: HashMap::<String, Attribute>:...
self.attributes.get(key).unwrap().get_value() } pub fn put(&mut self, key: &str, value: &str) { self.attributes.insert(key.to_string(), Attribute::new(key, value)); } pub fn put_attribute(&mut self, attribute: Attribute) { self.attributes.insert(attribute.get_value(), attribute.clone()); } pub fn remove...
pub fn get(&self, key: &str) -> String { // TODO: validate key // validate.not_empty(key);
random_line_split
discrim-overflow-2.rs
// Copyright 2015 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 ...
enum A { Ok = u32::MAX - 1, Ok2, OhNo, //~ ERROR enum discriminant overflowed [E0370] } } fn f_i64() { #[repr(i64)] enum A { Ok = i64::MAX - 1, Ok2, OhNo, //~ ERROR enum discriminant overflowed [E0370] } } fn f_u64() { #[repr(u64)] enum A { ...
} fn f_u32() { #[repr(u32)]
random_line_split
discrim-overflow-2.rs
// Copyright 2015 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 ...
{ }
identifier_body
discrim-overflow-2.rs
// Copyright 2015 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 ...
{ Ok = i16::MAX - 1, Ok2, OhNo, //~ ERROR enum discriminant overflowed [E0370] } } fn f_u16() { #[repr(u16)] enum A { Ok = u16::MAX - 1, Ok2, OhNo, //~ ERROR enum discriminant overflowed [E0370] } } fn f_i32() { #[repr(i32)] enum A { Ok ...
A
identifier_name
userauth.py
""" @author: Geir Sporsheim @license: see LICENCE for details """ from twisted.internet import defer from twisted.conch.ssh.userauth import SSHUserAuthClient class AutomaticUserAuthClient(SSHUserAuthClient): """User Auth Client that automatically authenticate using stored credentials. """ def __init__(se...
return defer.succeed(self.password) def getPrivateKey(self): if self.privateKey: return defer.succeed(self.privateKey) return defer.fail(None) def getPublicKey(self): if not self.publicKey: return None return defer.succeed(self.publicKey)
return None # Return none to indicate we do not want to retry
conditional_block
userauth.py
""" @author: Geir Sporsheim @license: see LICENCE for details """ from twisted.internet import defer from twisted.conch.ssh.userauth import SSHUserAuthClient class AutomaticUserAuthClient(SSHUserAuthClient): """User Auth Client that automatically authenticate using stored credentials. """ def __init__(se...
def getPrivateKey(self): if self.privateKey: return defer.succeed(self.privateKey) return defer.fail(None) def getPublicKey(self): if not self.publicKey: return None return defer.succeed(self.publicKey)
if not self.password: return None # Return none to indicate we do not want to retry return defer.succeed(self.password)
identifier_body
userauth.py
""" @author: Geir Sporsheim @license: see LICENCE for details """ from twisted.internet import defer from twisted.conch.ssh.userauth import SSHUserAuthClient class AutomaticUserAuthClient(SSHUserAuthClient): """User Auth Client that automatically authenticate using stored credentials. """ def
(self, user, connection, password=None, privateKey=None, publicKey=None): SSHUserAuthClient.__init__(self, user, connection) self.password = password self.privateKey = privateKey self.publicKey = publicKey def getGenericAnswers(self, name, instruction, prompts): ...
__init__
identifier_name
userauth.py
""" @author: Geir Sporsheim @license: see LICENCE for details """ from twisted.internet import defer from twisted.conch.ssh.userauth import SSHUserAuthClient class AutomaticUserAuthClient(SSHUserAuthClient): """User Auth Client that automatically authenticate using stored credentials. """
self.publicKey = publicKey def getGenericAnswers(self, name, instruction, prompts): """Called when the server requests keyboard interactive authentication """ responses = [] for prompt, _echo in prompts: password = self.getPassword(prompt) responses.a...
def __init__(self, user, connection, password=None, privateKey=None, publicKey=None): SSHUserAuthClient.__init__(self, user, connection) self.password = password self.privateKey = privateKey
random_line_split
permissions.py
#encoding=utf8 from rest_framework import permissions from django.contrib import messages from copy import deepcopy from rest_framework.permissions import * def own_object_permission(field_name): class P(permissions.BasePermission): def has_object_permission(self, request, view, obj): print h...
return P def custom_perms_map(perms_map): perms = deepcopy(DjangoModelPermissionsOrAnonReadOnly.perms_map) perms.update(perms_map) class P(DjangoModelPermissionsOrAnonReadOnly): perms_map = perms return P def custom_perm(perm): class P(BasePermission): def has_permissio...
def has_object_permission(self, request, view, obj): if request.user.is_superuser or hasattr(obj, field_name) and getattr(obj, field_name) == request.user: return True else: return False
identifier_body