query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
r"""apply tensor divergence and return result as a field
def divergence( self, bc: Optional[BoundariesData], out: Optional[VectorField] = None, **kwargs ) -> VectorField: return self.apply_operator("tensor_divergence", bc=bc, out=out, **kwargs) # type: ignore
[ "def tensor_divergence(arr: np.ndarray, out: np.ndarray) -> None:\n # assign aliases\n arr_rr, arr_rθ, arr_rφ = arr[0, 0, :], arr[0, 1, :], arr[0, 2, :]\n arr_θr, arr_θθ, arr_θφ = arr[1, 0, :], arr[1, 1, :], arr[1, 2, :]\n arr_φr, arr_φθ, arr_φφ = arr[2, 0, :], arr[2, 1, :], arr[2, 2, :]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the trace of the tensor field as a scalar field
def trace(self, label: Optional[str] = "trace") -> ScalarField: return self.to_scalar(scalar="trace", label=label)
[ "def __tf_tracing_type__(self, _):\n return ScalarizerTraceType(self)", "def _scalar_field_default(self):\n matrix = self.matrix\n scalar_field = None\n\n if self.coreSym == 4:\n # Quarter core\n matrix = np.fliplr(matrix)\n scalar_field = mlab.pipeline.scalar_field(\n matrix,\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates a numpy array from a hdu_list from astropy it skips all strings and keeps just number like coloums
def generate_array(hdulist, features, targets): '''extract data''' astro_data = hdulist[1].data '''get all float like and feature matching data''' data_float = np.array([astro_data.field(0)]) for x in range(0, len(astro_data[0])): ''' Remove type-Check sth. is broken here ...
[ "def readHlist(filepath):\n\n #Check to see how many fields in hlist\n with open(filepath, 'r') as fp:\n\n l = fp.readline()\n ls = l.split(' ')\n nfields = len(ls)\n print('Number of fields in hlist {0}: {1}'.format(filepath, nfields))\n\n if nfields == 66:\n dtype = np....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute the channel commands by validating and finding their respective methods Returns list(str) a list of messages in response the command validation and execution
def run(self): try: # List of subcommands mapped the command methods switcher = { 'help': self.help, 'list': self.revision_list, 'l': self.revision_list, 'name': self.name, 'n': self.name, 'd...
[ "def run(self):\n\n try:\n # List of subcommands mapped the command methods\n switcher = {\n 'help': self.help,\n 'roll': self.roll,\n 'r': self.roll,\n 'reroll': self.roll,\n 're': self.roll,\n 'c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display and create a new Revision by name
def name(self, args): if not self.can_edit: raise Exception('You do not have permission to add revision text') messages = [] rev_name = ' '.join(args[1:]) if args[1] == 'rename': if len(args) < 4: raise Exception('syntax: ```css\n.d revision renam...
[ "def post_creation(self):\n new_page = VersionedText(revision_number = self.revision_number,\n content = \"Empty page\",\n author = getActiveDatabaseUser().get_active_user(),\n comment = \"Initial revision\")\n new_page.put()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display a dialog for viewing revisions
def revision_list(self, args): messages = [] def canceler(cancel_args): if cancel_args[0].lower() in ['revision','rev']: return RevisionCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else:...
[ "def test_view(self):\n url = self.get_url(revision_id=self.revision.id)\n response = self.client.get(url)\n\n self.assertRedirects(\n response,\n reverse('wagtailadmin_pages:revisions_view', args=(self.page.id, self.revision.id)),\n target_status_code=302\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Radio is empty and it will be error message for this option after attempt to add product to cart.
def test_radio_option_is_not_selected(self) -> None: if self.product_page.available_options.radio.which_option_is_chosen() is None: self.product_page.available_options.click_add_to_cart_button() expected_result = 'Radio required!' assert self.product_page.available_options.radio.erro...
[ "def test_checkbox_option_is_not_selected(self) -> None:\n if self.product_page.available_options.checkbox.which_option_is_chosen() == []:\n self.product_page.available_options.click_add_to_cart_button()\n expected_result = 'Checkbox required!'\n assert self.product_page.available_op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Radio is selected and it will be this option after attempt to add product to cart.
def test_radio_option_is_selected(self, radio_option, expected_result) -> None: if self.product_page.available_options.radio.which_option_is_chosen() is None: self.product_page.available_options.radio.choose_radio_button_option(radio_option) self.product_page.available_options.click_add_...
[ "def test_radio_option_is_not_selected(self) -> None:\n if self.product_page.available_options.radio.which_option_is_chosen() is None:\n self.product_page.available_options.click_add_to_cart_button()\n expected_result = 'Radio required!'\n assert self.product_page.available_options.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Checkbox is empty and it will be error message for this option after attempt to add product to cart.
def test_checkbox_option_is_not_selected(self) -> None: if self.product_page.available_options.checkbox.which_option_is_chosen() == []: self.product_page.available_options.click_add_to_cart_button() expected_result = 'Checkbox required!' assert self.product_page.available_options.che...
[ "def test_radio_option_is_not_selected(self) -> None:\n if self.product_page.available_options.radio.which_option_is_chosen() is None:\n self.product_page.available_options.click_add_to_cart_button()\n expected_result = 'Radio required!'\n assert self.product_page.available_options.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Checkbox is selected and it will be this option after attempt to add product to cart.
def test_checkbox_option_is_selected(self, checkbox_option, expected_result) -> None: self.product_page.available_options.checkbox.choose_checkbox_option(checkbox_option) self.product_page.available_options.click_add_to_cart_button() assert self.product_page.available_options.checkbox.which_opti...
[ "def test_checkbox_option_is_not_selected(self) -> None:\n if self.product_page.available_options.checkbox.which_option_is_chosen() == []:\n self.product_page.available_options.click_add_to_cart_button()\n expected_result = 'Checkbox required!'\n assert self.product_page.available_op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Color is empty and it will be error message for this option after attempt to add product to cart.
def test_color_is_not_selected(self) -> None: initial_state = ' --- Please Select --- ' if self.product_page.available_options.select.which_option_is_chosen() == initial_state: self.product_page.available_options.click_add_to_cart_button() expected_result = 'Color required!' ...
[ "def testOption(self, QColorDialog_ColorDialogOption): # real signature unknown; restored from __doc__\n return False", "def test_radio_option_is_not_selected(self) -> None:\n if self.product_page.available_options.radio.which_option_is_chosen() is None:\n self.product_page.available_opti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functionality test for checking if color select option is working.
def test_color_option_is_selected(self, color_option, expected_result) -> None: self.product_page.available_options.select.choose_dropdown_option(color_option) self.product_page.available_options.click_add_to_cart_button() option_list = self.product_page.available_options.select.which_option_is_...
[ "def test_color_is_not_selected(self) -> None:\n initial_state = ' --- Please Select --- '\n if self.product_page.available_options.select.which_option_is_chosen() == initial_state:\n self.product_page.available_options.click_add_to_cart_button()\n expected_result = 'Color required!'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Date is empty and it will be error message for this option after attempt to add product to cart.
def test_date_field_is_not_filled(self) -> None: self.product_page.available_options.data_field.clear_and_fill_input_field('') self.product_page.available_options.click_add_to_cart_button() expected_result = 'Date required!' assert self.product_page.available_options.data_field.error_mes...
[ "def test_checkbox_option_is_not_selected(self) -> None:\n if self.product_page.available_options.checkbox.which_option_is_chosen() == []:\n self.product_page.available_options.click_add_to_cart_button()\n expected_result = 'Checkbox required!'\n assert self.product_page.available_op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Date field is filled with invalid data that consists invalid format, letters or symbols and it will be error message for this option after attempt to add product to cart.
def test_date_field_is_filled_invalid_data(self, date_field_input: str) -> None: self.product_page.available_options.data_field.clear_and_fill_input_field(date_field_input) self.product_page.available_options.click_add_to_cart_button() expected_result = 'Date does not appear to be valid. Date fo...
[ "def test_form_validation_invalid_date_provided(self) -> None:\n data = {'date': '08-05-2020'}\n form = ExpenseSearchForm(data=data)\n self.assertFalse(form.is_valid())", "def test_invalid_date_format(self):\n form = ApplicationForm({'school_program':1,\n 's...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Date field is filled with wrong date that consists date of today, yesterday or previous days it will be error message for this option after attempt to add product to cart.
def test_date_field_is_filled_wrong_date(self) -> None: today = str(datetime.date.today()) self.product_page.available_options.data_field.clear_and_fill_input_field(today) self.product_page.available_options.click_add_to_cart_button() expected_result = 'You can choose only tomorrow\'s da...
[ "def test_form_validation_invalid_date_provided(self) -> None:\n data = {'date': '08-05-2020'}\n form = ExpenseSearchForm(data=data)\n self.assertFalse(form.is_valid())", "def test_bad_checkout_date(self):\n items = Item.objects.all()\n # use the class's due_date variable which ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Date field is filled with valid data that consists date of tomorrow, yesterday or subsequent days it will be no error message for this option after attempt to add product to cart.
def test_date_field_is_filled_valid_data(self) -> None: today = datetime.date.today() tomorrow = str(today + datetime.timedelta(days=1)) self.product_page.available_options.data_field.clear_and_fill_input_field(tomorrow) self.product_page.available_options.click_add_to_cart_button() ...
[ "def validate_date(self, avail_date):\n if avail_date.weekday() in (5, 6):\n raise ValidationError(\"Sundays and Saturdays are holidays.\")\n if not (\n self.uploaded_at.date()\n <= avail_date\n <= timedelta(days=7) + self.uploaded_at.date()\n ):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Time is empty and it will be error message for this option after attempt to add product to cart.
def test_time_field_is_not_filled(self) -> None: self.product_page.available_options.time.clear_and_fill_input_field('') self.product_page.available_options.click_add_to_cart_button() expected_result = 'Time required!' assert self.product_page.available_options.time.error_message.get_err...
[ "def check_time_correct(self):\r\n if self.get_hour() == '' or self.get_min() == '' or len(str(self.get_hour())+str(self.get_min())) != 4:\r\n messagebox.showerror(\"Ok\", \"Please enter a valid time. Use the format HH:MM\")\r\n self.refresh()\r\n else:\r\n if int(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Time field is filled with invalid data that consists invalid format, letters or symbols and it will be error message for this option after attempt to add product to cart.
def test_time_field_is_filled_invalid_data(self, time_field_input: str) -> None: self.product_page.available_options.time.clear_and_fill_input_field(time_field_input) self.product_page.available_options.click_add_to_cart_button() expected_result = 'Time does not appear to be valid. Time format: ...
[ "def check_time_correct(self):\r\n if self.get_hour() == '' or self.get_min() == '' or len(str(self.get_hour())+str(self.get_min())) != 4:\r\n messagebox.showerror(\"Ok\", \"Please enter a valid time. Use the format HH:MM\")\r\n self.refresh()\r\n else:\r\n if int(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Text is empty. There will be error message for this option after attempt to add product to cart.
def test_text_field_not_filled(self) -> None: self.product_page.available_options.text_field.clear_and_fill_input_field('') self.product_page.available_options.click_add_to_cart_button() expected_result = 'Text required!' assert self.product_page.available_options.text_field.error_messag...
[ "def test_checkbox_option_is_not_selected(self) -> None:\n if self.product_page.available_options.checkbox.which_option_is_chosen() == []:\n self.product_page.available_options.click_add_to_cart_button()\n expected_result = 'Checkbox required!'\n assert self.product_page.available_op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Text is filled with text string that is longer than 40 characters. There should be error message 'Text must be between 1 and 40 characters!' for this option after attempt to add product to cart.
def test_text_field_is_filled_invalid_data(self) -> None: text_field_input = 'testtesttesttesttesttesttesttesttesttestt' self.product_page.available_options.text_field.clear_and_fill_input_field(text_field_input) self.product_page.available_options.click_add_to_cart_button() expected_res...
[ "def test_check_field_length(self):\n form = EditCouponForm(data={\n 'headline': 'This headline is over twenty-five characters'})\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors['headline'][0], \n 'Please limit this field to 25 characters')", "def chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for checking if available option Quantity field is empty. There will be error message for this option after attempt to add product to cart.
def test_quantity_field_not_filled(self) -> None: self.product_page.available_options.quantity.clear_and_fill_input_field('') self.product_page.available_options.click_add_to_cart_button() expected_result = 'Quantity required!' assert self.product_page.available_options.quantity.error_me...
[ "def clean(self):\n cleaned_data = super(VenteCreateForm,self).clean()\n quantity = cleaned_data.get(\"quantity\", \"\")\n if len(str(quantity)) > 0:\n quantity = cleaned_data[\"quantity\"]\n product_id = cleaned_data[\"product_id\"]\n product_type = cleaned_dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check correct work of clicking on 'Add to Cart' button by filling all required fields.
def test_add_to_cart_button_with_all_selected_available_options(self) -> None: today = datetime.date.today() tomorrow = str(today + datetime.timedelta(days=1)) self.product_page.available_options.radio.choose_radio_button_option('Medium') self.product_page.available_options.checkbox.cho...
[ "def test_cart_basic(self):\n ### NOTE: the functionality realted to the cart pop-up will not be\n ### tested or implemented now, it will be done a later time (if needed).\n\n # It's 7:46 AM and Jaceon just woke up. He's sad that Lakers lost by 30\n # last night, but he has a day in fron...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check correct work of clicking on 'Compare this product' button.
def test_click_compare_button(self) -> None: self.product_page.click_compare_this_product_button() info_message = 'Success: You have added Apple Cinema 30" to your product comparison!' assert info_message in self.product_page.catch_info_message.get_success_message()
[ "def equalButton():\n\n\t#we only want to calculate expression if there are two numbers and a math operation in it\n\n\tscreenString = getScreenString()\n\n\tif getCountOfNumbers(screenString) == 2:\n\t\tresult = getEqualString(screenString)\n\t\tcleanWindow(result)", "def test2_compareForm(self):\n pass",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check correct work of clicking 'Add to Wish List' button.
def test_click_add_to_wish_list_as_not_logged_user(self): self.product_page.click_add_to_wish_list_button() info_message = 'You must login or create an account to save Apple Cinema 30" to your wish list!' assert info_message in self.product_page.catch_info_message.get_success_message()
[ "def add_to_wishlist(request, product_id):\n redirect_url = request.POST.get('redirect_url')\n\n user = get_object_or_404(UserProfile, user=request.user)\n wishlist = Wishlist.objects.get_or_create(user=user)\n wishlist_user = wishlist[0]\n\n product = Product.objects.get(pk=product_id)\n if reque...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test save matrix_product_state for instruction
def test_save_matrix_product_state(self): SUPPORTED_METHODS = ['matrix_product_state'] # Target mps structure target_qreg = [] target_qreg.append((np.array([[1, 0]], dtype=complex), np.array([[0, 1]], dtype=complex))) target_qreg.append((np.array([[1], [0]], dtype=complex), np....
[ "def test_save_load_state_dict(self):\n\n for qengine in supported_qengines:\n with override_quantized_engine(qengine):\n model = TwoLayerLinearModel()\n model = torch.ao.quantization.QuantWrapper(model)\n model.qconfig = torch.ao.quantization.get_defau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the fuel depletion in a nuclear reactor. Using cumulative fission yields and cross sections estimated with a thermal neutron spectrum the fission processes of relevant nuclides are calculated. Relevant decay constants are used to take nuclear decay into account. The fuel is depleted for a specified period of ...
def FuelDep(P, Time, Enrichment, Deltat, FuelMass): # Cross-sections: sf238U = 16.83e-30 sc238U = 2.690e-24 sf235U = 582.6e-24 sc235U = 98.8e-24 sf239Pu = 748.1e-24 sc239Pu = 269.3e-24 sf240Pu = 37.84e-27 sc240Pu = 289.5e-24 sf239Np = 29.06e-27 sc239Np = 68e-24 sa83...
[ "def DMFluxneuDet(flavor,Enu,ch,DMm,DMsig,body,param,osc): \n ##B From Arxiv: 0506298 ec. 21 & 24\n #DM_annihilation_rate_Earth = 1.0e14*(100*param.GeV/DMm)**2/param.sec #[annhilations/s]\n #DM_annihil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculation of the duration as the time it takes to decline below the threshold.
def _get_duration( time_course: np.ndarray, below_threshold: float = 0.5, ) -> int: if not 0.0 < below_threshold < 1.0: raise ValueError("below_threshold must lie within (0.0, 1.0).") maximum_value = np.max(time_course) t_max = np.argmax(time_course) time_course = time_course - b...
[ "def duration(self) -> float:\n return (self.stopTime - self.startTime).total_seconds()", "def duration(self):\n return self._t_stop - self._t_start", "def duration(self) -> float:\n if self._n_analyze and not self._duration:\n if self.data:\n return self._n_analyz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Give the best sample (and loglikelihood) Returns
def best_sample_logL(self): logLs = self.logLs_trunc() i_best = np.argmax(logLs) return self.samples[i_best], logLs[i_best]
[ "def find_best_overall():\n imgs, gts = gi.load_all_images('data/training/')\n X, Y = gi.produce_XY(imgs, gts)\n\n find_best_LogisticRegression(X, Y)\n find_best_BayesianRidge(X, Y)\n find_best_Ridge(X, Y)", "def get_best(self, dataset, sample_size): # always according to accuracy\n # creat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate a function on all samples This exploits that (if the sample data type is e.g. a userdefined class) many samples will actually be identical and we have to evaluate the function significantly fewer than ``len(samples)`` times.
def evaluate(self, fun): last_val = fun(self.samples[0]) last_sample = self.samples[0] out = [last_val] for sample in self.samples[1:]: if sample is not last_sample: last_sample = sample last_val = fun(sample) out.append(last_val) ...
[ "def eval(self):\n logger.info(f\"Evaluating generated samples with scores: {self.scores.keys()}\")\n scores_dict = self.scores\n n_loops = self.training_params[\"eval_size\"] // self.eval_batch_size\n results = dict(zip(scores_dict.keys(), [None] * len(scores_dict)))\n for score ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback to enable early stopping This function will be called at welldefined intervals to check whether sampling should abort. Judgement is to be made based on the data so far, which is handed over as the `!myrun` argument. This is an `MCMCRun` object.
def callback_stopping(self, myrun): pass # pragma: no cover
[ "def test_stop_runs(self):\n pass", "def test_stop_run(self):\n pass", "def stop_next_run(msg=u'Case run was stopped by user'):\n with open(os.getcwd() + '/.stop','w') as file:\n file.write(msg + newline)\n BuiltIn().log(\"Do not run the test on next round\")", "def iterRun_stop(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receive auction parameters from client and request its storage in the repository server
def create_auction(self, msg, addr): try: self.mylogger.log(INFO, "Receiving auction request") id = msg['payload']['auction']['id'] self.clients_address[id] = addr self.current_dynamic_code = msg['payload']['dynamic_code'] auction = msg['payload']['...
[ "def auction(self):\n pass # TODO", "def get_auction_kwargs(self, params):\n timestamp = int(params[0])\n user_id = int(params[1])\n item = params[3]\n reserve_price = float(params[4])\n close_time = int(params[5])\n\n return {\n 'timestamp': timestamp,\n 'user_id': user_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate a bid, as a request of the repository server Here, the function for the execution of the dynamic code is called, returning True or False if the bid is valid or not.
def validate_bid(self, data, addr): try: self.mylogger.log(INFO, "Validating bid") valid = False for auction in self.active_auctions: if str(auction['serial']) == str(data['bid']['serial']): encrypted_key = base64.b64decode(data['bid']['...
[ "def valid_bid_check(self, bid):\n self.logger.info('Function called to validate bid: {0}'.format(bid))\n is_valid = False\n #check if there is a list of items to bid for\n if self.all_listed_items:\n self.logger.info('There are items currently listed')\n self.logge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the file of a closed auction and compute the winner, which is the client with the higher amount. The outcome is stored on the file and then loaded into a linked list (blockchain) by the repository server
def get_winner(self, data): try: self.mylogger.log(INFO, "Computing winner of the auction") winner_dict = {} result = [] serial = 0 print("> auction ended") with open(data['end']) as f: lines = f.readlines() a...
[ "def parse(self, file_path):\n with open(file_path) as input_file:\n # Dictionary that keeps track of all the auctions.\n # An auction can be accessed via the auction item.\n auction_items = {}\n last_heartbeat = None\n\n for line in input_file:\n line_params = line.split('|')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compile all requirements into one requirements.txt
def compile_requirements(ctx): if WINDOWS: ctx.config.run.shell = "C:\\Windows\\System32\\cmd.exe" requirements = glob("supervisr/**/requirements.txt", recursive=True) requirements_dev = glob("supervisr/**/requirements-dev.txt", recursive=True) with open('requirements.txt', 'w') as _reqs: ...
[ "def requirements():\n\n run('pip install -r {req}'.format(req=REQUIREMENTS))", "def build_requirements(name):\n utils.print_subtitle(\"Building\")\n filename = os.path.join(REQ_DIR, 'requirements-{}.txt-raw'.format(name))\n host_python = get_host_python(name)\n\n with open(filename, 'r', encoding=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify sentry of new release version
def notify_sentry(ctx): print(requests.post(os.environ.get('SENTRY_RELEASE_URL'), json={'version': supervisr.__version__}))
[ "def sentry_release():\n with cd(env.home):\n version = run('sentry-cli releases propose-version')\n run('sentry-cli releases new --finalize --project {project} {version}'.format(\n project=env.repo, version=version\n ))\n run('sentry-cli releases set-commits --auto {versio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run bumpversion, update changelog from git commits and open editor
def bumpversion(ctx, level): context = {} bump_out = ctx.run('bumpversion --allow-dirty --dry-run --list %s' % level, hide=True).stdout # Convert string of `a=b` to dictionary {'a': 'b'} (trim out last line cause it is blank) bump = {line.split('=')[0]: line.split('=')[1] for line in bump_out.split('\n'...
[ "def postversion():\n # load version after bump\n from importlib import reload\n\n reload(__version__)\n new_version = __version__.__version__\n\n # ##########################\n # # GET TAG INFO FROM GIT\n # ##########################\n completed_process = subprocess.run([\"git\", \"describe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that request validation does parameter validation. This is largely a smoke test to ensure that parameter validation is wired into request validation correctly.
def test_request_parameter_validation(): from django.core.exceptions import ValidationError schema = SchemaFactory( paths={ '/get/{id}/': { 'parameters': [ { 'name': 'id', 'in': PATH, ...
[ "def test_validator(self) -> None:\n # `/users/me/subscriptions` doesn't require any parameters\n validate_request(\"/users/me/subscriptions\", \"get\", {}, {}, False, \"200\")\n with self.assertRaises(SchemaError):\n # `/messages` POST does not work on an empty response\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the matplotlib backend to PDF. This is necessary to render high resolution figures.
def set_matplotlib_pdf_backend(): global plt if plt is not None: return try: import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt except ValueError: warnings.warn( """Couldn't set the PDF matplotlib backend, positioner plots may be l...
[ "def output_pdf(fig):\n # If height is explicitly set on the plot, remove it before generating\n # a pdf. Needs to be reset at the end of the function.\n height = None\n if fig.layout.height is not None:\n height = fig.layout.pop('height')\n\n try:\n pdf = base64.a85encode(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot one fiber positioner which has invalid angles.
def plot_positioner_invalid(ax, patrol_rad, loc, center, color="k", linewidth=0.2, fontpt=2.0): set_matplotlib_pdf_backend() patrol = plt.Circle((center[0], center[1]), radius=patrol_rad, fc=color, ec="none", alpha=0.1) ax.add_artist(patrol) xtxt = ce...
[ "def plot_euler_error(df):\n plt.title('euler angle errors')\n np.rad2deg(df.t_vehicle_attitude_0__f_roll_error).plot(\n label='roll error', style='r-')\n np.rad2deg(df.t_vehicle_attitude_0__f_pitch_error).plot(\n label='pitch error', style='g-')\n np.rad2deg(df.t_vehicle_attitude_0__f_yaw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing PatchBaseline resource's state with the given name, id, and optional extra properties used to qualify the lookup.
def get(resource_name, id, opts=None, approval_rules=None, approved_patches=None, approved_patches_compliance_level=None, description=None, global_filters=None, name=None, operating_system=None, rejected_patches=None, tags=None): opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) ...
[ "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n approval_rules: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PatchBaselineApprovalRuleArgs']]]]] = None,\n approved_patches: Optional[pulumi.Input[Seq...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the given URL into a legal URL by escaping unsafe characters according to RFC3986. If a bytes URL is given, it is first converted to `str` using the given encoding (which defaults to 'utf8'). 'utf8' encoding is used for URL path component (unless overriden by path_encoding), and given encoding is used for query...
def safe_url_string(url, encoding='utf8', path_encoding='utf8'): # Python3's urlsplit() chokes on bytes input with non-ASCII chars, # so let's decode (to Unicode) using page encoding: # - it is assumed that a raw bytes input comes from a document # encoded with the supplied encoding (or UTF8 by de...
[ "def url_encode(text):\n return urllib.quote(text)", "def escape_url(raw):\n return html.escape(quote(html.unescape(raw), safe=\"/#:()*?=%@+,&\"))", "def encode_url_path(url):\n return six.moves.urllib.parse.quote(url)", "def urldecode(value):\n return urllib.unquote(urllib.unquote(value)).dec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add or remove a parameter to a given url >>> import w3lib.url >>> w3lib.url.add_or_replace_parameter(hhttps, 'arg', 'v')
def add_or_replace_parameter(url, name, new_value): parsed = urlsplit(url) args = parse_qsl(parsed.quhttps keep_blank_values=True) new_args = [] found = False for name_, value_ in args: if name_ == name: new_args.append((name_, new_value)) found = True else: ...
[ "def add_params(original_url, params):\n querydict = get_querydict(original_url)\n querydict.update(params)\n qs = urlencode(querydict)\n components = urlparse.urlsplit(original_url)\n new_url = urlparse.urlunsplit((components[0], components[1], components[2], qs, components[4]))\n return new_url"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the debits of this TrialBalanceMovement.
def debits(self, debits): self._debits = debits
[ "def deposit_disabled(self, deposit_disabled):\n\n self._deposit_disabled = deposit_disabled", "def debit(self, amount):\n if self._is_asset_or_expenses:\n self.balance += amount\n else:\n self.balance -= amount", "def SetDeclividade(self, decliv):\r\n self.Iado...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the credits of this TrialBalanceMovement.
def credits(self, credits): self._credits = credits
[ "def credits_used(self, credits_used):\n\n self._credits_used = credits_used", "def credits_granted(self, credits_granted):\n\n self._credits_granted = credits_granted", "def credits_purchased(self, credits_purchased):\n\n self._credits_purchased = credits_purchased", "def free_credits(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the movement of this TrialBalanceMovement.
def movement(self, movement): self._movement = movement
[ "def movement_number(self, movement_number):\n\n self._movement_number = movement_number", "def set_movement(self, direction, speed):\n self._direction = direction\n self._speed = speed", "def move(self, movement, steering):\n # type: (Movement, Steering) -> None\n rospy.logde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the signed_movement of this TrialBalanceMovement.
def signed_movement(self, signed_movement): self._signed_movement = signed_movement
[ "def set_movement(self, direction, speed):\n self._direction = direction\n self._speed = speed", "def movement_number(self, movement_number):\n\n self._movement_number = movement_number", "def add_movement(self, movement):\r\n self.current_slider_pos += movement.distance_delta * self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get remote by name. name may be None. _get_remote_or_bail(Repo, str) > Remote
def _get_remote_or_bail(repo, name): remote_name = name if not remote_name: # Default to origin since it's the convention. remote_name = "origin" try: return repo.remote(remote_name) except ValueError as e: if not name and len(repo.remotes) == 1: # Should be ...
[ "def get_remote(repo):\n if repo and repo.remotes:\n if len(repo.remotes) == 1:\n return repo.remotes[0].name, repo.remotes[0].url\n elif repo.active_branch.tracking_branch():\n name = repo.active_branch.tracking_branch().remote_name\n return name, repo.remotes[name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find where the includeable module starts. _find_src_module_path(str, str, function) > str
def _find_src_module_path(path, root_marker, should_include_fn): first_includeable = [] for dirpath, dirs, files in os.walk(path, topdown=True): markers = [dirpath for f in files if f == root_marker] if markers: return markers[0] if not first_includeable: first_in...
[ "def _GetSrcRelativePath(path):\n assert path.startswith(_GetToolsParentDir())\n return expand_owners.SRC + path[len(_GetToolsParentDir()) + 1:]", "def GOPATH_src_rel(p):\n for gopath in os.environ['GOPATH'].split(os.pathsep):\n root = os.path.realpath(os.path.join(gopath, 'src'))\n if os.path.isdir(root...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If there's only a single file in 'path', rename it to new_name. _rename_if_single_file(str, str) > None
def _rename_if_single_file(path, new_name, include_re): file = None for dirpath, dirs, files in os.walk(path, topdown=True): if include_re: files = [f for f in files if include_re.fullmatch(f)] has_relevant_dirs = any(["test" not in d and d != ".git" for d in dirs]) if not ha...
[ "def rename(self, p_str, p_str_1=None): # real signature unknown; restored from __doc__ with multiple overloads\n return False", "def rename(file, newFileName):\n\ttry:\n\t\tos.rename(translatePath(file), translatePath(newFileName))\n#\t\tshutil.move(file, newFileName)\n\t\treturn True\n\texcept:\n\t\tretu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Like the function returned by _build_should_include, but matches every file.
def _include_all(dirpath, f): return True
[ "def test_includes_files(self):\n # Test for Bug 1624725\n # https://bugs.launchpad.net/duplicity/+bug/1624725\n self.root = Path(\"testfiles/select2/1/1sub1\")\n self.ParseTest([(\"--include\", \"testfiles/select2/1/1sub1/1sub1sub1\"),\n (\"--exclude\", \"**\")],\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the gtk0 of this GroupTransientKeys.
def gtk0(self, gtk0): self._gtk0 = gtk0
[ "def gtk1(self, gtk1):\n\n self._gtk1 = gtk1", "def gtk3(self, gtk3):\n\n self._gtk3 = gtk3", "def gtk2(self, gtk2):\n\n self._gtk2 = gtk2", "def setK0(self, K0):\n return _core.CFixedCF_setK0(self, K0)", "def doZeroGroup(self,connect=True):\n\ti_group = validateObjArg(self.doGro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the gtk1 of this GroupTransientKeys.
def gtk1(self, gtk1): self._gtk1 = gtk1
[ "def gtk3(self, gtk3):\n\n self._gtk3 = gtk3", "def gtk0(self, gtk0):\n\n self._gtk0 = gtk0", "def gtk2(self, gtk2):\n\n self._gtk2 = gtk2", "def SetKey1(self, *args):\n return _TColStd.TColStd_IndexedMapNodeOfIndexedMapOfReal_SetKey1(self, *args)", "def setGroupDependent(self, v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the gtk2 of this GroupTransientKeys.
def gtk2(self, gtk2): self._gtk2 = gtk2
[ "def gtk1(self, gtk1):\n\n self._gtk1 = gtk1", "def gtk3(self, gtk3):\n\n self._gtk3 = gtk3", "def SetKey2(self, *args):\n return _TColStd.TColStd_IndexedDataMapNodeOfIndexedDataMapOfTransientTransient_SetKey2(self, *args)", "def gtk0(self, gtk0):\n\n self._gtk0 = gtk0", "def Set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the gtk3 of this GroupTransientKeys.
def gtk3(self, gtk3): self._gtk3 = gtk3
[ "def set_i3():\n\n set_config(\n yaml.load(\n get_wm_settings(\n window_manager_name='i3',\n show_desktop_icons=False)))", "def _3(self, _3):\n\n self.__3 = _3", "def set_3d_group_flags(self, group_num, flags):\n self._set_3d_group_flags(group_num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a checkpoint for the model
def write_checkpoint(self, checkpoint_id): assert self.output_dir is not None checkpoint_dir = os.path.join(self.output_dir, 'checkpoints') checkpoint_file = 'model_checkpoint_%03i.pth.tar' % checkpoint_id os.makedirs(checkpoint_dir, exist_ok=True) torch.save(dict(model=self.mode...
[ "def save_ckpt(self, epoch):\n save_path = self.manager.save()\n log.info(\"Saved checkpoint at: {}\".format(save_path))", "def save_checkpoint(self,\n checkpoint: dict,\n name: str):\n\n # Save the checkpoint in the pre-specified directory\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that confirmation block is unique (based on block_identifier)
def validate(self, data): block_identifier = data['block_identifier'] confirmation_block_queue = cache.get(CONFIRMATION_BLOCK_QUEUE) if confirmation_block_queue: existing_block_identifiers = {i['block_identifier'] for i in confirmation_block_queue} existing_confirmation...
[ "def verify_block(self, block):\n\t\tsha = hasher.sha256('a')\n\t\tsha.update(\n\t\t\t\tstr(block.block_id) +\n\t\t\t\tstr(block.miner_id) + \n\t\t\t\tstr(block.timestamp) + \n\t\t\t\tstr(block.data) + \n\t\t\t\tstr(block.previous_hash))\n\t\tverify_hashed = sha.hexdigest()\n\t\tif verify_hashed != block.hash:\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Node that this Knob belongs to is its parent item.
def node(self): return self.parentItem()
[ "def get_parent(self) -> 'Node':\n return self.parent", "def get_parent(self):\n return self.__return(self.node.parent())", "def parent(self, node):\n return node._parent", "def parentItem(self):\n return self._parentItem", "def get_parent_value(self): # pragma: no cover\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience method to connect this to another Knob. This creates an Edge and directly connects it, in contrast to the mouse events that first create an Edge temporarily and only connect if the user releases on a valid target Knob.
def connect_to(self, knob, orientation=0): if knob is self: return edge = Edge() edge.source = self edge.target = knob self.add_edge(edge) knob.add_edge(edge) edge.update_path(orientation)
[ "def _connect_signal( self, left_port, right_port ):\n\n # Can't connect a port to itself!\n assert left_port != right_port\n # Create the connection\n connection_edge = ConnectionEdge( left_port, right_port )\n\n # Add the connection to the Model's connection list\n if not connection_edge:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the given Edge to the internal tracking list. This is only one part of the Knob connection procedure. It enables us to later traverse the whole graph and to see how many connections there currently are. Also make sure it is added to the QGraphicsScene, if not yet done.
def add_edge(self, edge): self.edges.append(edge) scene = self.scene() if edge not in scene.items(): scene.addItem(edge)
[ "def add_edge(self, edge):\n\t\tedge = set(edge)\n\t\t(vertex, neighbor) = tuple(edge)\n\t\tif vertex not in self.g:\n\t\t\tself.g[vertex] = [neighbor]\n\t\telse:\n\t\t\tself.g[vertex].append(neighbor)\n\t\tprint \"Added Edge : {}\".format(edge)", "def addEdge(self,edge):\r\n self.adj.append(edge)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle the highlight color on/off. Store the old color in a new attribute, so it can be restored.
def highlight(self, toggle): if toggle: self._oldFillColor = self.fillColor self.fillColor = self.highlightColor else: self.fillColor = self._oldFillColor
[ "def switch_color(self):\n pass", "def SetHighlightColor(self, *args):\n return _Graphic3d.Graphic3d_Structure_SetHighlightColor(self, *args)", "def _highlight(self):\n if highlight_state():\n elem = self._find_element()\n\n def apply_style(style):\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove this Knob, its Edges and associations.
def destroy(self): print("destroy knob:", self) edges_to_delete = self.edges[::] # Avoid shrinking during deletion. for edge in edges_to_delete: edge.destroy() node = self.parentItem() if node: node.removeKnob(self) self.scene().removeItem(self) ...
[ "def removeFromCanvas(self):\n for circle, line in self.connectedCircle.items():\n self.scene().removeItem(line)\n circle.removeConnection(self)\n\n self.scene().removeItem(self)", "def remove(self):\n self.layers.pop()", "def remove(self):\n if self.guide_joint...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure the Edge direction is as described below. .source > .target OutputKnob > InputKnob
def ensure_edge_direction(edge): print("ensure edge direction") if isinstance(edge.target, OutputKnob): assert isinstance(edge.source, InputKnob) actualTarget = edge.source edge.source = edge.target edge.target = actualTarget else: assert isinstance(edge.source, Outpu...
[ "def test_edge_not_match_direction(self):\n e1 = ed.Edge(\"O\",\"B\")\n e2 = ed.Edge(\"O\",\"B\")\n self.assertFalse(e1.matches(e2))", "def test_set_invalid_direction(self):\n self._register_components()\n\n # Turn on fan\n common.turn_on(self.hass, _TEST_FAN)\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Associate a handler function and optional filter predicate function to a key. If the transform of the midi event matches the key, then the event is dispatched to the callback function given that the filter predicate function also returns true.
def SetHandler(self, key, callback_fn, filter_fn=None): def _default_true_fn(_): return True if filter_fn is None: filter_fn = _default_true_fn self._dispatch_map[key] = (callback_fn, filter_fn) return self
[ "def add_handler(self, predicate, handler):\n pass", "def set_maskable_callback(self, key_name, callback, silent=False):\n self.check_special_callback(key_name)\n if not silent:\n self.sanity_check_cb(key_name, callback)\n self.maskable_keymap[key_name] = callback", "def a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Associate the same handler for a group of keys. See SetHandler for more details.
def SetHandlerForKeys(self, keys, callback_fn, filter_fn=None): for k in keys: self.SetHandler(k, callback_fn, filter_fn=filter_fn) return self
[ "def addHandler(self, handler):\n # key_bind = False\n if hasattr(handler, 'process_key'):\n handler_key = handler.process_key\n for key in list(set(self.process_key) & set(handler_key)):\n exist_handler = self.key_handlers.get(key, list())\n self.ke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a data payload to Arturia device.
def send_to_device(data): debug.log('CMD', 'Sending payload: ' + str(data)) # Reference regarding SysEx code : # https://forum.arturia.com/index.php?topic=90496.0 device.midiOutSysex(bytes([0xF0, 0x00, 0x20, 0x6B, 0x7F, 0x42]) + data + bytes([0xF7]))
[ "def _send_data(self, data):\n command_data = CommandDataMessage(command_type=self.command_type, command_data=data)\n self.networking.send_message(command_data)", "def send_data(self, agent_name, data):\r\n\t\tmessage = [agent_name, data]\r\n\t\ttry:\r\n\t\t\tmsg = json.dumps(message)\r\n\t\texcept ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot a grouped bar chart barGroups list of groups, where each group is a list of bar heights barNames list containing the name of each bar within any group groupNames list containing the name of each group colors list containing the color for each bar within a group ylabel label for the yaxis title title
def plot_bars(barGroups, barNames, groupNames, colors, xlabel="", ylabel="", title="", width=0.8): fig, ax = plt.subplots() offset = lambda items, off: [x + off for x in items] maxlen = max(len(group) for group in barGroups) xvals = range(len(barGroups)) for i, bars in enumerate(zip(*barGroups)): ...
[ "def multi_bar(xlabels, data, yerr=None,\n group_labels=None, group_colors=None, axs=None,\n x_start=0,\n padding=0.15):\n\n Ngroups = len(data)\n assert Ngroups > 0\n assert 0 <= padding <= 1.0\n Nx = len(data[0])\n\n if yerr is None:\n yerr = [[0] * Nx]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns data structure for verite timeline JSON date entry, skips checking/including start data if ``ignore_date`` is enabled
def data(ignore_date=False):
[ "def make_timeline_data(self,user):\n annos = json.loads(self.user_annos.get(user))\n dates = [a['updated'] for a in annos]\n dates = [parser.parse(date) for date in dates]\n dates.sort()\n dates = dates\n \n first = dates[0]\n last = dates[-1]\n \n def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch new parameter set from the service and updates the step counter in this object with the new value. Throws a ValueError if the calibration ended already.
def requestNewParameters(self): res = self.getNewParameters(self.calibrationID, self.currentStep) if res['OK']: returnValue = res['Value'] # FIXME calibrationRun state will be updated number of worker times while only one time is enough if returnValue is not None: self.currentPhase = r...
[ "def parameters_updated(self):\n self.calculate_variables()\n termination = self.detect_termination()\n if termination is None:\n self.request_estimation()\n self.monitor_progress()\n else:\n self.callback.plp_terminated(termination)", "def update(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get new photon likelihood file.
def requestNewPhotonLikelihood(self): res = self.getNewPhotonLikelihood(self.calibrationID) if res['OK']: return res['Value'] else: return None
[ "def _get_ann_file(self):\n prefix = 'posetrack_instance' \\\n if 'test' not in self.image_set else 'image_info'\n return os.path.join(self.root, 'posetrack_data', 'annotations',\n prefix + '_' + self.image_set + '_0003420000.json')", "def file_log_prob(file: Pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get lisp state from VPP node.
def vpp_show_lisp_state(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_status.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def get_state(self):\n return self._skuld.cmd(SkuldCmd(name='get_state',\n args=None, block=True))", "def get_ovp_state(self):\r\n ovp_state = str(self.inst.query(\"VOLT:PROT:STAT?\"))\r\n return(ovp_state)", "def get_state(self, node_id):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get lisp eid table from VPP node.
def vpp_show_lisp_eid_table(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_eid_table.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def vpp_set_lisp_eid_table(node, eid_table):\n\n if node['type'] != NodeType.DUT:\n raise ValueError('Node is not DUT')\n\n lisp_locator_set = LispLocatorSet()\n lisp_eid = LispLocalEid()\n for eid in eid_table:\n vni = eid.get('vni')\n eid_address = eid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get lisp map resolver from VPP node.
def vpp_show_lisp_map_resolver(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_map_resolver.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def vpp_set_lisp_map_resolver(node, map_resolver):\n\n lisp_map_res = LispMapResolver()\n for map_ip in map_resolver:\n lisp_map_res.vpp_add_map_resolver(node, map_ip.get('map resolver'))", "def vpp_show_lisp_map_register(node):\n\n vat = VatExecutor()\n vat.execute_script_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LISP Map Register from VPP node.
def vpp_show_lisp_map_register(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_map_register.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def vpp_show_lisp_map_resolver(node):\n\n vat = VatExecutor()\n vat.execute_script_json_out('lisp/show_lisp_map_resolver.vat', node)\n return JsonParser().parse_data(vat.get_script_stdout())", "def getRegister(self, addrspc: ghidra.program.model.address.AddressSpace, offset: long, size: int)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LISP Map Request mode from VPP node.
def vpp_show_lisp_map_request_mode(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_map_request_mode.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def _get_mode(self, interface):\n url = self._construct_url(interface, suffix='mode')\n response = self._make_request('GET', url)\n root = etree.fromstring(response.text)\n mode = root.find(self._construct_tag('vlan-mode')).text\n return mode", "def get_vm_mode(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LISP Map Server from VPP node.
def vpp_show_lisp_map_server(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_map_server.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def vpp_show_lisp_map_resolver(node):\n\n vat = VatExecutor()\n vat.execute_script_json_out('lisp/show_lisp_map_resolver.vat', node)\n return JsonParser().parse_data(vat.get_script_stdout())", "def get_lbvserver(self):\n return self.options['lbvserver']", "def _get_lsp_tunnel_id(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LISP PETR configuration from VPP node.
def vpp_show_lisp_petr_config(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_petr_config.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def vpp_show_lisp_rloc_config(node):\n\n vat = VatExecutor()\n vat.execute_script_json_out('lisp/show_lisp_rloc_config.vat', node)\n return JsonParser().parse_data(vat.get_script_stdout())", "def plone_config():\n chef_api = autoconfigure()\n if '127.0.0.1:2222' in api.env.hosts:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LISP RLOC configuration from VPP node.
def vpp_show_lisp_rloc_config(node): vat = VatExecutor() vat.execute_script_json_out('lisp/show_lisp_rloc_config.vat', node) return JsonParser().parse_data(vat.get_script_stdout())
[ "def vpp_show_lisp_petr_config(node):\n\n vat = VatExecutor()\n vat.execute_script_json_out('lisp/show_lisp_petr_config.vat', node)\n return JsonParser().parse_data(vat.get_script_stdout())", "def get_new_config():\n\n return db.get_db().getRoot().getS(ns.newL2tpDeviceConfig, rdf.Type(ns.L...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fail if the lisp values are not equal.
def lisp_should_be_equal(lisp_val1, lisp_val2): len1 = len(lisp_val1) len2 = len(lisp_val2) if len1 != len2: raise RuntimeError('Values are not same. ' 'Value 1 {} \n' 'Value 2 {}.'.format(lisp_val1, ...
[ "def test_eq_not_identical(self):\n loc1 = SimpleLocation(22, 42, 1)\n loc2 = SimpleLocation(23, 42, 1)\n self.assertNotEqual(loc1, loc2)\n\n loc1 = SimpleLocation(23, 42, 1)\n loc2 = SimpleLocation(23, 43, 1)\n self.assertNotEqual(loc1, loc2)\n\n loc1 = SimpleLocati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a list of lisp locator_set we want set to VPP and then check if it is set correctly. Some locator_sets are duplicated.
def generate_duplicate_lisp_locator_set_data(node, locator_set_number): topo = Topology() locator_set_list = [] locator_set_list_vat = [] i = 0 for num in range(0, int(locator_set_number)): locator_list = [] for interface in node['interfaces'].values(): ...
[ "def vpp_set_lisp_locator_set(node, locator_set_list):\n\n if node['type'] != NodeType.DUT:\n raise ValueError('Node is not DUT')\n\n lisp_locator = LispLocator()\n lisp_locator_set = LispLocatorSet()\n for locator_set in locator_set_list:\n locator_set_name = locat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get metadata of a paper by it doi. Query all the APIs such as crossref, scopes, etc. If not found, return None.
def get_api_metadata_by_doi(doi): result = None docs = [] funcs = { 'crossref': get_api_crossref_metadata_by_doi, 'scopus': get_api_scopus_metadata_by_doi, } for k, f in funcs.items(): r = f(doi) if r: docs.append(r) if len(docs) > 0: result =...
[ "def get_metadata_by_doi(mongo_db, doi):\n\n result = None\n\n result = get_db_metadata_by_doi(mongo_db, doi)\n\n if result is None:\n result = get_api_metadata_by_doi(doi)\n\n return result", "def get_db_metadata_by_doi(mongo_db, doi):\n result = None\n\n docs = []\n funcs = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get metadata of a paper by it doi. Query existing metadata in COVID database. If not found, return None.
def get_db_metadata_by_doi(mongo_db, doi): result = None docs = [] funcs = { 'crossref': get_db_crossref_metadata_by_doi, 'scopus': get_db_scopus_metadata_by_doi, } for k, f in funcs.items(): r = f(mongo_db, doi) if r: docs.append(r) if len(docs) > 0:...
[ "def get_metadata_by_doi(mongo_db, doi):\n\n result = None\n\n result = get_db_metadata_by_doi(mongo_db, doi)\n\n if result is None:\n result = get_api_metadata_by_doi(doi)\n\n return result", "def get_api_metadata_by_doi(doi):\n result = None\n\n docs = []\n funcs = {\n 'crossr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get metadata of a paper by it doi. First query existing metadata in COVID database. If not found, query API directly. If still not found, return None.
def get_metadata_by_doi(mongo_db, doi): result = None result = get_db_metadata_by_doi(mongo_db, doi) if result is None: result = get_api_metadata_by_doi(doi) return result
[ "def get_api_metadata_by_doi(doi):\n result = None\n\n docs = []\n funcs = {\n 'crossref': get_api_crossref_metadata_by_doi,\n 'scopus': get_api_scopus_metadata_by_doi,\n }\n for k, f in funcs.items():\n r = f(doi)\n if r:\n docs.append(r)\n if len(docs) > 0:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an attribute name and a projector, return a producer which plucks the attribute off the instance, figures out whether it represents a single object or an iterable/queryset of objects, and applies the given projector to the related object or objects.
def relationship(name, related_projector): def producer(instance): try: related = none_safe_attrgetter(name)(instance) except ObjectDoesNotExist: return None return map_or_apply(related, related_projector) return producer
[ "def __call__(self, o=None, n=None, v=None, create_attributetype=True, \n create_attribute=True, klass=False, description=None, \n as_attribute=False, as_dict=True):\n ############################################\n # Permutation of o types\n # \n # no obje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an attribute name (which should be a relationship field), return a producer which returns a list of the PK of each item in the relationship (or just a single PK if this is a toone field, but this is an inefficient way of doing it).
def pk_list(name): return relationship(name, attrgetter("pk"))
[ "def uuids_as_list(attrname):\n return (lambda self, value: [operator.attrgetter('id')(obj)\n for obj in operator.attrgetter(\n attrname)(self)])", "def getPrimaryKeys(self):\n return orm.object_mapper(self).primary_key_from_instance(self)", "def getIdList(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I read the given file into a Pandas Dataframe. The Dataframe is then massaged to add three new columns reportTimestamp, dateId, confirmedCases/deaths to make the data concatenable and conducive to Elasticsearch
def create_df(file, df_type): try: date_id = file.split("/")[-1].split(".")[0] report_timestamp = datetime.strptime(date_id, "%m-%d-%y").strftime("%Y-%m-%dT%H:%M:%S") df = pd.read_csv(file) columns = df.columns.tolist() df["reportTimestamp"] = df.apply(lambda row: report_ti...
[ "def Get_Panda_Dataframe_From_File(filename,headers,get_hashtags = True,offset_time = True):\n raw_tweets = Get_Only_Headers_From_File(filename,headers,get_hashtags)\n if offset_time:\n f = open(filename,\"r\")\n tweet = json.loads(f.readline())\n time_offset = tweet[\"user\"][\"utc_offse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I merge the given dataframe (confirmed_cases_df/covid_deaths_df) with the population dataframe on the County Name column
def merge_df(covid_df, population_df): try: logger.info("Covid DF Shape - {}".format(covid_df.shape)) logger.info("Population DF Shape - {}".format(population_df.shape)) merged_df = pd.merge(covid_df, population_df[["County Name", "population"]], on="County Name") logger.info("Merg...
[ "def merge(self, country_list):\n countries = self.select(country_list)\n data = list()\n for k in countries.keys():\n data.append(countries.get(k).df[k])\n return CountryData(pd.concat(data, axis=1))", "def merge_by_year(year):\n \n #Load the data sets.\n countrie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I read confirmed_cases and covid_deaths data from the given locations and concatenate the data into their respective Pandas Dataframes. The Dataframes are then merged with a Population Dataframe to add population information. The two concatenated Dataframes are then sent to Elasticsearch using the Bulk API.
def main(): try: # Switch the wokring directory to Capstone cwd = os.getcwd() # Assign directory paths confirmed_cases_dir = "{}/covid_county_data/confirmed_cases/*".format(cwd) covid_deaths_dir = "{}/covid_county_data/covid_deaths/*".format(cwd) # Get all data file...
[ "def load_location_data_and_clean(states = True, modernized=True, save=False): \n if states:\n df = pd.read_csv('../../data/original_data/state_data.csv')\n save_local = '../../data/state_data_cleaned_final.csv'\n else: \n if modernized:\n df = pd.read_csv('../../data/origin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It cleans lines out and appending cleaned lines to out_collector. Lines that cannot be cleaned are appended to err_collector. Lines earlier than begin and later than end are ignored.
def clean(lines, out_collector, err_collector, begin=None, end=None): def open_full_path(cleaned_call): return cleaned_call.args[0] def error(tokens, error_msg): return " ".join(tokens) + " error: " + error_msg def between(stamp, begin, end): ge_begin = not (begin and (stamp < beg...
[ "def cleanSyntaxErrors(self):\n \n self.markerDeleteAll()\n self.clearAnnotations()\n last_line = self.lines()\n last_offset = self.lineLength(last_line)\n self.clearIndicatorRange(0, 0, last_line, last_offset,\n self._syntax_error_indicator)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fullpath is not mandatory at syscall level. we can create fullpaths using pwd when basepath points to basenames
def full_path(pwdir, basepath): if not basepath.startswith('/'): return pwdir + basepath return basepath
[ "def makefullpath(path):\n try:\n os.makedirs(os.path.split(path)[0])\n except:\n pass", "def _change_base_directory(self,fname,basename):\n\n # Compensate the possible problem with incompatible HOME paths\n bases = self.gethomepaths()\n for base in bases:\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when 65534 1856 1867 (gmetad) sys_fstat64 1319227151912074154 5 0 returns 65534 1856 1867 (gmetad) fstat 1319227151912074154 5 0 or 65534 1856 1867 (gmetad) fstat 1319227151912074154 fullpath 5 0 if fullpath is available. Note that we keep fd anyway
def clean_fstat(tokens, fullpath): if fullpath: args = [fullpath, tokens[-2]] else: args = [tokens[-2]] return CleanCall(tokens[0], tokens[1], tokens[2], tokens[3], "fstat", tokens[5], args, tokens[-1])
[ "def fgetattr(self, path, fh):\n q.logger.log(\"fgetattr: %s (fh %s)\" % (path, fh))\n return fh.stat", "def mode(path):\n return stat(path).st_mode", "def _get_stat(cls, path):\n return os.stat(path)", "def _mock_basic_fs_calls(self):\n def _noop_handler(*_args, **_kwargs):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when 0 9352 9352 (trivialrewrite) sys_llseek 131920380172365631 7 4294967295 4294967290 SEEK_CUR 708 then 0 9352 9352 (trivialrewrite) llseek 131920380172365631 7 4294967295 4294967290 SEEK_CUR 708 when 0 23506 23506 (localedef) sys_llseek 131922916938952032 3 0 0 SEEK_END 1279166 then 0 23518 23518 (localedef) llseek ...
def clean_sys_llseek(tokens, fullpath): #sys_llseek has both low and high offset (I'll check if in our traces they are always the same value #FIXME: we need to choose between low and high offsets args = [] args.append(fullpath) args.extend(tokens[-5:-1]) return CleanCall(tokens[0], tokens[1], toke...
[ "def test_files_seek(self):\n with self.fs.openbin('top.txt') as f:\n if f.seekable():\n self.assertEqual(f.seek(0), 0)\n self.assertEqual(f.tell(), 0)\n self.assertEqual(f.seek(2), 2)\n self.assertEqual(f.tell(), 2)\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when 0 940 940 (tar) sys_open 1319227153693893147 /local/ourgrid/vserver_images/worker.lsd.ufcg.edu.br_2/ usr/lib/python2.5/encodings/euc_jp.pyc 32961 384 5 returns 0 940 940 (tar) open 1319227153693893147 /local/ourgrid/vserver_images/worker.lsd.ufcg.edu.br_2/usr/lib/python2.5/encodings/euc_jp.pyc 32961 384 5
def clean_open(tokens): #interesting line -> 0 940 940 (tar) sys_open 1319227153693893-147 /local/ourgrid/vserver_images/worker.lsd.ufcg.edu.br_2/ usr/lib/python2.5/encodings/euc_jp.pyc 32961 384 5 #is it possible to get empty chars in basepath, to we re-join themFIXME basepath can be made of empty space, so to...
[ "def unzipTIFgap(inTar, sensorType, extractPath):\n tar = tarfile.open(inTar)\n checkList = tar.getnames()\n for band in sensorType:\n for tarFileName in checkList:\n if band in tarFileName:\n break\n else:\n # the print statement needs to be replaced with...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set_ones creates row vectors of the form v=[0,...,0,1,..........,1,0,...,0] ones_start ones_stop If ones_start is larger than or equal to width, return vector of zeros. >>> set_ones(6, 7, 10) array([0., 0., 0., 0., 0., 0.]) >>> set_ones(6, 1, 3) array([0., 1., 1., 0., 0., 0.])
def set_ones(width, ones_start=0, ones_stop=0): v = np.zeros(width) if ones_start < width: v[ones_start:ones_stop] = 1 return v
[ "def make_mask(self, num_ones):\n res = 0\n for i in range(num_ones):\n res |= (1 << i)\n return res", "def ones(shape, dtype=None, order=None):\n a = empty(shape, dtype, order)\n a.fill(1)\n return a", "def test_timeseries_set_ones(self):\n ts = self.ts.clone()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
establish trendline for Dict Type is either "sup" or "res"
def trend(Dict, Type, thres): count = 0 countF=0 fLine={}#store flat trendlines Line={}#store other trendlines for x, y in Dict.items(): print("***************************************************") print("first base value is ",...
[ "def trendline(res, stab):\n\n if res.size != stab.size:\n print 'Failed in trendline.'\n sys.exit()\n\n delta = res.size*np.sum(res*res) - np.sum(res)*np.sum(res)\n intercept = (np.sum(res*res)*np.sum(stab) - np.sum(res)*np.sum(res*stab)) / delta\n slope = (res.size*np.sum(res*stab) - np....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable ARP and ICMP protocol
def load_arp_icmp(self): match = ofparser.OFPMatch(eth_type = 0x0806) actions = [ofparser.OFPActionOutput(ofp.OFPP_FLOOD)] self.add_flow(datapath = self.datapath, table_id = 0, priority = 100, match = match, actions = actions) ...
[ "def set_proxy_arp(ifname, value):\n\n with open(\"/proc/sys/net/ipv4/conf/%s/proxy_arp\" % ifname, \"w\") as f:\n f.write(\"1\\n\" if value else \"0\\n\")\n logging.debug(\"Proxy ARP for %s interface has been %s.\", ifname,\n \"enabled\" if value else \"disabled\")", "def test_arp_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse tree inorder iterative. Inorder Traversierung des Baumes mittels Iteration und eines Stacks.
def inorderIterative(self): stack = [] # Wir benutzen den Python eigenen Stack: eine Liste. n = self._head._right while (n is not self._sentinal): stack.append(n) n = n._left while stack: n = stack.pop() self.printnode(n) n ...
[ "def traverse_depthwise(self, flag=None):\n queue = deque([self]) \n while len(queue) != 0:\n node = queue.popleft()\n if node.has_children():\n for child in node.get_children():\n if child is not None:\n queue.append(child...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse tree postorder iterative. Postorder Traversierung des Baumes mittels Iteration und eines Stacks.
def postorderIterative(self): stack = [] # Wir benutzen den Python eigenen Stack: eine Liste. n = self._head._right done = False while not done: while (n is not self._sentinal): if n._right is not self._sentinal: stack.append(n._right)...
[ "def postorder(tree):\n # check the base case\n if tree != None:\n # recursively traverse left child\n postorder(tree.get_left_child())\n # recursively traverse right child\n postorder(tree.get_right_child())\n # print root node\n print(tree.get_root_node())", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse tree levelorder iterative. Inorder Traversierung des Baumes mittels Iteration und eines Stacks.
def levelorderIterative(self): from collections import deque queue = deque([]) # Wir benutzen die Python eigene Queue, eine deque. queue.append(self._head._right) while queue: n = queue.popleft() self.printnode(n) if n._left is not self._sentinal: ...
[ "def traverse_depthwise(self, flag=None):\n queue = deque([self]) \n while len(queue) != 0:\n node = queue.popleft()\n if node.has_children():\n for child in node.get_children():\n if child is not None:\n queue.append(child...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the User key and cert if they exist otherwise throws an exception
def getKeyCert(): # First presendence to HOST Certificate, RARE if os.environ.has_key('X509_HOST_CERT'): cert = os.environ['X509_HOST_CERT'] key = os.environ['X509_HOST_KEY'] # Second preference to User Proxy, very common elif os.environ.has_key('X509_USER_PROXY'): cert = os.environ['X509_USER_P...
[ "def get_valid_certs() -> tuple:\n if 'AlienSessionInfo' in globals() and AlienSessionInfo['verified_cert']: return AlienSessionInfo['user_cert'], AlienSessionInfo['user_key']\n\n FOUND = path_readable(USERCERT_NAME) and path_readable(USERKEY_NAME)\n if not FOUND:\n msg = f'User certificate files NO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a line and the document it is in, get the data at that line that corresponds to this schema column.
def fetch_data(self, document, line): return [col.fetch_data(document, line) for col in self.sources]
[ "def dataline(self, line):\n return super(scandata, self).data[:, line - 1]", "def get_data(self, column, row):\n return self.data[column][row]", "def find(self, line):\r\n for anEntry in self.db.get_ncf_entries():\r\n if anEntry.isMatch(line):\r\n return anEntry\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }