query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Destroy the block at the given coordinates. This may or may not set the block to be full of air; it uses the block's preferred replacement. For example, ice generally turns to water when destroyed. This is safe as a noop; for example, destroying a block of air with no metadata is not going to cause state changes.
def destroy(self, coords): block = blocks[self.get_block(coords)] self.set_block(coords, block.replace) self.set_metadata(coords, 0)
[ "def delete_block_surf(self, coords, loc):\n self.d.delete_block_surf(coords, loc)", "def remove_block(self, coords):\n self.area.remove_block(coords)\n self.hide_block(coords)\n neighbors = self.area.get_neighbors(coords)\n for element in neighbors['hide']:\n self.hi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the height of an xzcolumn of blocks.
def height_at(self, x, z): return self.heightmap[x * 16 + z]
[ "def find_height(self, x, z):\n x_index = bisect_left(self.x_terrain, x)\n z_index = bisect_left(self.z_terrain, z)\n if x_index < len(self.x_terrain)-2:\n x_finded = self.x_terrain[x_index+1]\n else :\n x_finded = self.x_terrain[-1]\n if z_index < len(self.z...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a search and replace on all blocks in this chunk. Named after the ubiquitous Unix tool. Does a semantic s/search/replace/g on this chunk's blocks.
def sed(self, search, replace): for section in self.sections: for i, block in enumerate(section.blocks): if block == search: section.blocks[i] = replace self.all_damaged = True self.dirty = True
[ "def replace_all(file, search, replace):\n for line in fileinput.input(file, inplace=True):\n if search in line:\n line = line.replace(search, replace)\n sys.stdout.write(line)", "def main():\n\n description = '''Replace a block of lines with another block.\n\n Bo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests the init method of MicrophoneToText
def test_init(self): mic = mi.MicrophoneToText() self.assertTrue(mic.switch) self.assertIsNotNone(mic.resultkeywords) self.assertIsNotNone(mic.result) self.assertIsNotNone(mic.keywordsshort) # tests also chunk and maxbuffer self.assertIsNotNone(mic.q) sel...
[ "def __init__(self):\n\n self.speech_to_text = Auth.authenticate_s2t(self)", "def initAudio(self):\n\t\t# Initialize pitch detection\n\t\tself.listener = PitchDetect(channels=1)\n\t\tself.listener.listen()\n\t\tself.recording = False\n\t\tself.paused = False", "def test_init_unit(self):\n reading ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests the switchoff method of MicrophoneToText
def test_switchoff(self): mic = mi.MicrophoneToText() mic.switchoff() with self.assertRaises(OSError): mic.stream.is_active() self.assertFalse(mic.switch) self.assertFalse(mic.audio_source.is_recording) self.assertTrue(mic.result.closed)
[ "def off():\r\n utils.print_for_unimplemented_functions(off.__name__)\r\n telemetry_py.send_telemetry(TelemetryEvent.MICROBIT_API_RADIO)", "def switch_off(self, device):\n pass", "def _turn_off(self):\n self._turn_display('OFF')", "def turn_off(self):\n print(\"Turning off source me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests the analyze_text method of MicrophoneToText
def test_analyze_text(self): mic = mi.MicrophoneToText() with open('../examples/result.txt', 'w', encoding='utf-8') as f: f.write('x transcript": straße lautet aarbergerstraße }x\n') f.write('x transcript": ort lautet testort }x\n') f.write('x transcript": einkommen...
[ "def test_convert_audio_to_text(self):\n\n text = self.converter.convert_audio_to_text(START, END, [WORD], lambda: False)\n text = text.strip()\n self.assertEqual(text, WORD)", "def speech_recognizer_function(self, text_widget):\r\n label_listening = Label(self.root, text=\"listening t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests the find_correct_keyword method from MicrophoneToText
def test_get_correct_keyword(self): mic = mi.MicrophoneToText() mic.keywordsshort = {'street': ['straße lautet aarberger straße '], 'location': ['ort lautet berlin'], 'income': ['einkommen lautet vierzigtausend'] , 'capital': ['eigenkapital lautet hundertfünfundzwanzigtause...
[ "def test_findcorrectkeyword(self):\n mic = mi.MicrophoneToText()\n\n mic.keywordsshort[\"street\"] = [\"adresse lautet amselweg\", 'useless']\n mic.keywordsshort['location'] = [\"der ort lautet berlin\", 'useless']\n mic.keywordsshort['capital'] = [\"der Kaufpreis lautet vierhunderttaus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests the find_word method from MicrophoneToText
def test_find_word(self): mic = mi.MicrophoneToText() teststring = 'x transcript": ort lautet testort }x' word = mic.find_word(teststring) self.assertEqual(word, ' ort lautet testort ')
[ "def test_find_word(self):\n self.assertEqual(find_word('GREEN'), [(1, 1), (1, 1), (0, 9)])\n self.assertEqual(find_word('ABSENT'), [])\n self.assertEqual(find_word('PW'), [(1, 7), (3, 7), (0, 8)])", "def test_find_word2(self):\n self.assertEqual(find_word2('GREEN'), [(1, 1), (1, 1), (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests the MyRecognizeCallback class check if there appears following console output Connection closed Connection was successful
def test_recognize(self): rec = mi.MyRecognizeCallback() rec.on_close() rec.on_connected() rec.on_data('"final": true truetestd') rec.on_error("testerror") rec.on_hypothesis("testh") rec.on_inactivity_timeout("testerrorinac") rec.on_listening() re...
[ "def verify_capture(self):\n reply = self.socket.recv(3)\n if reply[0] == codes['timeout']:\n print(\"Ocurrió un timeout en la conexión\")\n self.close_connection()\n if reply[0] == codes['attemps']:\n print(\"No lo capturaste. Te quedan \" +\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests another time the find_correct_keyword method
def test_findcorrectkeyword(self): mic = mi.MicrophoneToText() mic.keywordsshort["street"] = ["adresse lautet amselweg", 'useless'] mic.keywordsshort['location'] = ["der ort lautet berlin", 'useless'] mic.keywordsshort['capital'] = ["der Kaufpreis lautet vierhunderttausend", 'useless'] ...
[ "def test_get_correct_keyword(self):\n mic = mi.MicrophoneToText()\n\n mic.keywordsshort = {'street': ['straße lautet aarberger straße '], 'location': ['ort lautet berlin'], 'income': ['einkommen lautet vierzigtausend']\n , 'capital': ['eigenkapital lautet hundertfünfundzwa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Can create a service with a blank name.
def test_create_service_with_empty_name(self): response = self.tenant_client.create_service( type_=self.type, description=self.description) service = response.entity self.addCleanup(self.tenant_client.delete_service, response.entity.id_) self.assertEqual(response....
[ "def create_service(self, service_name, *args, **kwargs):\n\n creator = self._service_creators.get(service_name, None)\n\n if creator is None:\n return None\n\n return creator(*args, **kwargs)", "def test_creation_when_missing_service_name(self):\n self.data = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Can create two different services with the same name, type and description.
def test_create_service_with_duplicate_data(self): first_response = self.tenant_client.create_service( name=self.name, type_=self.type, description=self.description) first_service = first_response.entity self.assertEqual(first_response.status_code, 200) ...
[ "def test_ipam_services_create(self):\n pass", "def test_create_services_with_tag(self):\n tag1 = sample_tag(user=self.user, name='Electrical')\n tag2 = sample_tag(user=self.user, name='Distribution')\n\n payload = {\n 'title' : 'Fitting Job',\n 'tags' : [tag1.id,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
self.buffer를 비우고, self.buffer에 저장되어 있던 정보를 반환합니다. self.buffer에는 이전 keyboard_buffer.regurgitate_string() 호출 이후로 입력받은 문자열 정보가 저장됩니다.
def regurgitate_string(self) -> str: result = self.buffer self.buffer = '' return result
[ "def string_buffer(self):\n return self._buffer", "def buffer_before_token(self):\n r = \"\".join(i for i in map(lambda x: x.decode(\"utf-8\"), self.buffer))\n self.buffer = []\n return r", "def _show_key_processor_key_buffer(self, new_screen: Screen) -> None:\n app = get_app(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
self.backspaces를 0으로 설정하고, self.backspaces에 저장되어 있던 정수를 반환합니다. self.backspaces는 이전 keyboard_buffer.regurgitate_backspace() 호출 이후로 감지한 백스페이스 입력의 횟수가 저장됩니다.
def regurgitate_backspace(self) -> int: result = self.backspaces self.backspaces = 0 return result
[ "def test_backspace(self):\n self.widget.keystrokeReceived('X', None)\n self.painted = False\n self.widget.keystrokeReceived(ServerProtocol.BACKSPACE, None)\n self.assertEqual(self.widget.cursor, 0)\n self.assertEqual(self.widget.buffer, '')\n self.failUnless(self.painted)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise all the values that is going to be used in the program Create files by the given url and download the given url Then call pywget_inside_crawler() function
def initialise(url, depth): dir_string = url[url.find('/')+2 : url.rfind('/')+1] # the directory name that is going to be created format of .../.../.../ dir_string_list = dir_string.split('/') root_dir_name = dir_string_list[0] # the root direc...
[ "def download(self):\n filtered = self.__fetch_url()\n if filtered:\n print('> Found following urls in page:')\n for i, url in enumerate(filtered): print('{} - {}'.format(i, url))\n else:\n print('> No URLs found in page')\n if(input(\"> Exit? [y/n]\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crawl the given url find all and tags Get the information inside the tags and apply pywget_recursive() function on each of them
def pywget_inside_crawler(url, depth, start_dir, start_file, root_dir_name): depth -= 1 content = '' try: request = urllib.request.urlopen(url) content = request.read().decode("utf-8") except: pass # all the information that's inside <a href> and <img src> tags match = ...
[ "def _scrape_url(self, url):\n \n try:\n req = urllib2.Request(url)\n res = urllib2.urlopen(req)\n except urllib2.HTTPError as err:\n # For now silently catch HTTP errors such as 404s\n return\n \n html = res.read()\n \n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively create directories and download files by the given url
def pywget_recursive(url, depth, start_dir, start_file, root_dir_name): dir_string = url[url.find('/')+2 : url.rfind('/')+1] # the directory name that is going to be created dir_string_list = dir_string.split('/') dir_string_list[0] = root_dir_name dir_string = '/'.join(dir_string_...
[ "def initialise(url, depth):\n dir_string = url[url.find('/')+2 : url.rfind('/')+1] # the directory name that is going to be created format of .../.../.../\n dir_string_list = dir_string.split('/')\n root_dir_name = dir_string_list[0] # the ro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add information inside and to the given list If it is an absolute link, check if it's under the same domain, if so add it to the list otherwise ignore If it is a relative link, add prefix in the front and add it to the list
def add_item_to_list(given_list, prefix): new_list = [] if given_list: for item in given_list: item.lstrip() if item.startswith("http://") or item.startswith("https://") or item.startswith("//"): if item.startswith(prefix): new_list.append(item...
[ "def mk_link_list(self, BS_object, base_url):\n link_list = []\n body = BS_object.find('body')\n for element in body.find_all('a'):\n # for link in BS_object.find_all('a'): # TEST if there are any links in html head\n \n raw_link = element.get('href')\n print...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the setting of the target temperature with range.
async def test_set_target_temp_range(opp): state = opp.states.get(ENTITY_ECOBEE) assert state.attributes.get(ATTR_TEMPERATURE) is None assert 21.0 == state.attributes.get(ATTR_TARGET_TEMP_LOW) assert 24.0 == state.attributes.get(ATTR_TARGET_TEMP_HIGH) await common.async_set_temperature( opp...
[ "def test_temperature_range(self):\n min = -20\n max = 40\n while not self.world.step():\n self.assertTrue(min <= self.world.weather['sun'] <= max,\n \"temperature is out of range\")", "def test_temperatures_value(self):\n self.assertEqual(self.Tmi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test setting the target temperature range without attribute.
async def test_set_target_temp_range_bad_attr(opp): state = opp.states.get(ENTITY_ECOBEE) assert state.attributes.get(ATTR_TEMPERATURE) is None assert 21.0 == state.attributes.get(ATTR_TARGET_TEMP_LOW) assert 24.0 == state.attributes.get(ATTR_TARGET_TEMP_HIGH) with pytest.raises(vol.Invalid): ...
[ "def test_temperature_range(self):\n min = -20\n max = 40\n while not self.world.step():\n self.assertTrue(min <= self.world.weather['sun'] <= max,\n \"temperature is out of range\")", "async def test_set_target_temp_range(opp):\n state = opp.states.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test setting the target humidity without required attribute.
async def test_set_target_humidity_bad_attr(opp): state = opp.states.get(ENTITY_CLIMATE) assert 67 == state.attributes.get(ATTR_HUMIDITY) with pytest.raises(vol.Invalid): await common.async_set_humidity(opp, None, ENTITY_CLIMATE) await opp.async_block_till_done() state = opp.states.get(ENT...
[ "async def test_set_target_humidity(opp):\n state = opp.states.get(ENTITY_CLIMATE)\n assert 67 == state.attributes.get(ATTR_HUMIDITY)\n\n await common.async_set_humidity(opp, 64, ENTITY_CLIMATE)\n await opp.async_block_till_done()\n\n state = opp.states.get(ENTITY_CLIMATE)\n assert 64.0 == state.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the setting of the target humidity.
async def test_set_target_humidity(opp): state = opp.states.get(ENTITY_CLIMATE) assert 67 == state.attributes.get(ATTR_HUMIDITY) await common.async_set_humidity(opp, 64, ENTITY_CLIMATE) await opp.async_block_till_done() state = opp.states.get(ENTITY_CLIMATE) assert 64.0 == state.attributes.get...
[ "def test_humidity_settings(self):\n self.assertEqual(DPTHumidity().value_min, 0)\n self.assertEqual(DPTHumidity().value_max, 670760)\n self.assertEqual(DPTHumidity().unit, \"%\")\n self.assertEqual(DPTHumidity().resolution, 1)", "async def test_report_humidifier_humidity_state(hass: H...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test setting hvac mode without required attribute. Also check the state.
async def test_set_hvac_bad_attr_and_state(opp): state = opp.states.get(ENTITY_CLIMATE) assert state.attributes.get(ATTR_HVAC_ACTION) == CURRENT_HVAC_COOL assert state.state == HVAC_MODE_COOL with pytest.raises(vol.Invalid): await common.async_set_hvac_mode(opp, None, ENTITY_CLIMATE) await ...
[ "def test_hvac_settings_mode() -> None:\n response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(\n f\"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/hvac-settings.json\",\n schemas.KamereonVehicleDataResponseSchema,\n )\n response.raise_for_error_code()\n\n vehi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test setting the hold mode eco.
async def test_set_hold_mode_eco(opp): await common.async_set_preset_mode(opp, PRESET_ECO, ENTITY_ECOBEE) await opp.async_block_till_done() state = opp.states.get(ENTITY_ECOBEE) assert state.attributes.get(ATTR_PRESET_MODE) == PRESET_ECO
[ "async def test_set_away_mode_on(opp):\n await common.async_set_away_mode(opp, True, ENTITY_WATER_HEATER)\n state = opp.states.get(ENTITY_WATER_HEATER)\n assert state.attributes.get(\"away_mode\") == \"on\"", "def set_hold_mode(self, hold):\n self._hold = hold\n self.schedule_update_ha_stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test setting the auxiliary heater without required attribute.
async def test_set_aux_heat_bad_attr(opp): state = opp.states.get(ENTITY_CLIMATE) assert state.attributes.get(ATTR_AUX_HEAT) == STATE_OFF with pytest.raises(vol.Invalid): await common.async_set_aux_heat(opp, None, ENTITY_CLIMATE) await opp.async_block_till_done() assert state.attributes.ge...
[ "def test_initNoisy(self):\n self.assertTrue(self.noisyAttemptMgr.noisy)", "def test_hasequipment_value(inverter: SingleInverter) -> None:\n assert isinstance(inverter.data['powerflow']['hasEquipment'], bool)\n #print(f\"Hasequipment: {gw.data['powerflow']['hasEquipment']}\")", "def test_trainable_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test setting the auxiliary heater off/false.
async def test_set_aux_heat_off(opp): await common.async_set_aux_heat(opp, False, ENTITY_CLIMATE) await opp.async_block_till_done() state = opp.states.get(ENTITY_CLIMATE) assert state.attributes.get(ATTR_AUX_HEAT) == STATE_OFF
[ "def set_heater_off(self):\n pin = self.config.get('relay_board_pin')\n status = self.heater_status\n\n if status == True:\n GPIO.output(pin, False)\n #now = datetime.now()\n #current_time = now.strftime(\"%d/%m/%Y-%H:%M:%S\")\n print(\"Turn off heate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert that this platform has a certain feature or raise an exception otherwise.
def assert_has_feature(self, feature_name): if not self.features.get("has_{}".format(feature_name), False): self.raise_config_error("Platform {} does not support to configure {feature_name}. " "Please make sure the platform " "y...
[ "def check_feature(self, feature: SwitchFeature) -> None:\n if not self.has_feature(feature):\n raise RuntimeError(\"{} does not support {}\".format(self.name(), feature.value))\n pass", "def validate_environment():\n if not accessibility_enabled():\n raise Exception, (\"Accessi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return config spec for this platform.
def get_config_spec(cls): return False
[ "def get_device_spec():\n dev_info = get_device_info()\n if dev_info is not None:\n return device_spec.DeviceSpec(\n dev_info['device_type'],\n dev_info['device_index'],\n )\n else:\n cfg = config.config()\n return device_spec.DeviceSpec(\n cfg.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a firmware update.
def update_firmware(self) -> str:
[ "def update_firmware(self):\n self.execute_command(CMD_UPDATE_FIRMWARE)", "def performFirmwareUpdate(self, deviceIndex) -> None:\r\n fn = self.function_table.performFirmwareUpdate\r\n error = fn(deviceIndex)\r\n openvr.error_code.FirmwareError.check_error_value(error)", "async def up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subclass this method in a platform module to configure the DMD. This method should return a reference to the DMD's platform interface method will will receive the frame data.
def configure_dmd(self) -> "DmdPlatformInterface": raise NotImplementedError
[ "def configure_dmd(self):\n raise NotImplementedError", "def __init__(self, *args, **kwargs):\n super(DataMoverTestBase, self).__init__(*args, **kwargs)\n self.dm_cmd = None\n self.processes = None\n self.pool = []\n self.containers = []\n self.uuids = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a reference to the hardware sound interface.
def configure_hardware_sound_system(self) -> "HardwareSoundPlatformInterface": raise NotImplementedError
[ "def get_mixer_dev(self):\n\t\treturn call_sdk_function('PrlVmDevSound_GetMixerDev', self.handle)", "def getSound(self):\n return self._sound", "def get_output_dev(self):\n\t\treturn call_sdk_function('PrlVmDevSound_GetOutputDev', self.handle)", "def getSound(self):\r\n return self._shipsound", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return addition config section for segment displays.
def get_segment_display_config_section(cls) -> Optional[str]: return None
[ "def config_section(self):\n\n def c(s):\n \"\"\"return a commented, wrapped block.\"\"\"\n s = '\\n\\n'.join(wrap_paragraphs(s, 78))\n\n return '# ' + s.replace('\\n', '\\n# ')\n\n # section header\n breaker = '#' + '-' * 78\n klass = self.__class__.__na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate segment display config for platform.
def validate_segment_display_section(self, segment_display, config) -> dict: if self.get_segment_display_config_section(): spec = self.get_segment_display_config_section() # pylint: disable-msg=assignment-from-none config = segment_display.machine.config_validator.validate_config(spec,...
[ "def check_display_option(display):\n display_options = get_display_options(verbose=False)\n if display not in display_options:\n err_str = \"The display value (%s) does not correspond to a possible \\\n display value in ENA\" % (display)\n raise ValueError(err_str)", "async def configu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subclass this method in a platform module to configure a segment display. This method should return a reference to the segment display platform interface method will will receive the text to show.
async def configure_segment_display(self, number: str, display_size: int, platform_settings) -> "SegmentDisplayPlatformInterface": raise NotImplementedError
[ "def configure_segment_display(self, number: str, platform_settings) -> LightSegmentDisplay:\n settings = self.machine.config_validator.validate_config(\"light_segment_displays\", platform_settings)\n return LightSegmentDisplay(number, lights=settings['lights'], segment_type=settings['type'])", "asy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register display for flash task.
def _handle_software_flash(self, display): self._displays.add(display)
[ "def start_flash(display):\n ck_display[str(display)].configure(relief=tkinter.RAISED, bd=0, highlightbackground='blue', highlightthickness=8)", "def add_display(self, display):\n self.logger.debug(\"running\")\n self.__list_of_displays.append(display)\n self.__refresh()\n self.logg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise I2C platform and set feature.
def __init__(self, machine): super().__init__(machine) self.features['has_i2c'] = True
[ "def __init__(self, machine):\n super().__init__(machine)\n\n # Set default platform features. Each platform interface can change\n # these to notify the framework of the specific features it supports.\n self.features['has_drivers'] = True\n self.features['max_pulse'] = 255", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure a servo device in platform.
async def configure_servo(self, number: str) -> "ServoPlatformInterface": raise NotImplementedError
[ "def configure_servo(self, board):\n self.servo = board.get_pin(f\"d:{self.pin}:p\")\n board.servo_config(\n pin = self.pin,\n min_pulse = 544,\n max_pulse = 2400,\n angle = 93\n )", "def configure_servo(self, config):\n raise NotIm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return config section for additional stepper config items.
def get_stepper_config_section(cls) -> Optional[str]: return None
[ "def get_step_conf(self):\n return self.step_conf", "def config_section(self):\n\n def c(s):\n \"\"\"return a commented, wrapped block.\"\"\"\n s = '\\n\\n'.join(wrap_paragraphs(s, 78))\n\n return '# ' + s.replace('\\n', '\\n# ')\n\n # section header\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate a stepper config for platform.
def validate_stepper_section(self, stepper: "Stepper", config: dict) -> dict: if self.get_stepper_config_section(): spec = self.get_stepper_config_section() # pylint: disable-msg=assignment-from-none config = stepper.machine.config_validator.validate_config(spec, config, stepper.name)...
[ "def _validate_config(self):\n pass", "def validate_config(self):\n pass", "def _validate_config(self):\n raise NotImplementedError", "def _validate_machine_configuration(self):\n # Check weights dir\n self.m['weights_dir'] = Path(self.m['weights_dir'])\n if not self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure a smart stepper (axis) device in platform.
async def configure_stepper(self, number: str, config: dict) -> "StepperPlatformInterface": raise NotImplementedError
[ "def configure_stepper(self):\n self.logger.info('configurating stepper')\n if 'Z' in self.current_axis:\n self.anc350_instrument.configure_stepper('ZPiezoStepper', self.settings['amplitudeZ'] * ur('V'), self.settings['frequencyZ'] * ur('Hz'))\n else:\n self.anc350_instrum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse light number to a list of channels.
def parse_light_number_to_channels(self, number: str, subtype: str): raise NotImplementedError
[ "def parse_light_number_to_channels(self, number: str, subtype: str):\n if subtype == \"simple\":\n # simple LEDs use the format <board_address_id> - <led> (simple LEDs only have 1 channel)\n board_address_id, index = number.split('-')\n return [\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subclass this method in a platform module to configure a light. This method should return a reference to the light object which will be called to access the hardware.
def configure_light(self, number: str, subtype: str, config: LightConfig, platform_settings: dict) -> "LightPlatformInterface": raise NotImplementedError
[ "def configure_light(self, number: str, subtype: str, config, platform_settings: dict) -> VisualPinballEngineLight:\n if not subtype:\n subtype = \"light\"\n number = \"{}-{}\".format(subtype, number)\n light = VisualPinballEngineLight(number, self, config)\n self._configured_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subclass this method in a platform module to configure a switch. This method should return a reference to the switch's platform interface object which will be called to access the hardware.
def configure_switch(self, number: str, config: SwitchConfig, platform_config: dict) -> "SwitchPlatformInterface": raise NotImplementedError
[ "def configure_switch(self, config):\n raise NotImplementedError", "def port_maker(self, platform):\n raise NotImplementedError()", "def _get_get_interface_switchport(self):\n return self.__get_interface_switchport", "def configure_hardware_sound_system(self) -> \"HardwareSoundPlatformInterfa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return config section for additional switch config items.
def get_switch_config_section(cls) -> Optional[str]: return None
[ "def get_switch_config_section(cls):\n return None", "def section_config(feature, device_cfg, network_os):\n section_starts_with = feature.get(\"section\")\n if not section_starts_with:\n return device_cfg\n\n match = False\n section_config_list = []\n os_parser = parser_map[network_o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate a switch config for platform.
def validate_switch_section(self, switch: "Switch", config: dict) -> dict: if self.get_switch_config_section(): spec = self.get_switch_config_section() # pylint: disable-msg=assignment-from-none config = switch.machine.config_validator.validate_config(spec, config, switch.name) ...
[ "def validate_switch_section(self, switch: Switch, config: dict) -> dict:\n base_spec = [\"device\"]\n if self.__class__.get_switch_config_section():\n base_spec.append(self.__class__.get_switch_config_section())\n switch.machine.config_validator.validate_config(\n \"switc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all hardware switch states. Subclass this method in a platform module to return the hardware states of all the switches on that platform. of a switch. This method should return a dict with the switch numbers as keys and the hardware state of the switches as values. (0 = inactive, 1 = active) This method should not ...
async def get_hw_switch_states(self) -> Dict[str, bool]: raise NotImplementedError
[ "def _get_switch_map(self):\n switch_map = {}\n switch_map_obj = {}\n if not self.switch_states:\n return {}\n change_count = 0\n last_change = '#n/a' # Clevery chosen to be sorted less than timestamp.\n with self.lock:\n for switch, switch_state in s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subclass this method in a platform module to configure a driver. This method should return a reference to the driver's platform interface object which will be called to access the hardware.
def configure_driver(self, config: DriverConfig, number: str, platform_settings: dict) -> "DriverPlatformInterface": raise NotImplementedError
[ "def configure_hardware_sound_system(self) -> \"HardwareSoundPlatformInterface\":\n raise NotImplementedError", "def _configure(self, driver_config):\n\n #\n # NOTE the \"pnode\" parameter may be not very \"standard\" but it is the\n # current convenient mechanism that captures the ove...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subclass this method in a platform module to clear a hardware switch rule for this switch. Clearing a hardware rule means actions on this switch will no longer affect coils. Another way to think of this is that it 'disables' a hardware rule. This is what you'd use to disable flippers and autofire_coils during tilt, gam...
def clear_hw_rule(self, switch: SwitchSettings, coil: DriverSettings): raise NotImplementedError
[ "def clear_hw_rule(self, switch, coil):\n raise NotImplementedError", "def clear_hw_rule(self, switch: SwitchSettings, coil: DriverSettings):\n self.debug_log(\"Clearing Hardware Rule for coil: %s, switch: %s\",\n coil.hw_driver.number, switch.hw_switch.number)\n driver ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return addition config section for coils.
def get_coil_config_section(cls) -> Optional[str]: return None
[ "def get_coil_config_section(cls):\n return \"pkone_coils\"", "def get_coil_config_section(cls):\n return None", "def config_section(self):\n\n def c(s):\n \"\"\"return a commented, wrapped block.\"\"\"\n s = '\\n\\n'.join(wrap_paragraphs(s, 78))\n\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate coil config for platform.
def validate_coil_section(self, driver, config) -> dict: if self.get_coil_config_section(): spec = self.get_coil_config_section() # pylint: disable-msg=assignment-from-none config = driver.machine.config_validator.validate_config(spec, config, driver.name) elif config: ...
[ "def validate_coil_section(self, driver, config):\n base_spec = [\"device\"]\n if self.__class__.get_coil_config_section():\n base_spec.append(self.__class__.get_coil_config_section())\n driver.machine.config_validator.validate_config(\n \"coils\", config, driver.name,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set pulse on hit rule on driver. Pulses a driver when a switch is hit. When the switch is released the pulse continues. Typically used for autofire coils such as pop bumpers.
def set_pulse_on_hit_rule(self, enable_switch: SwitchSettings, coil: DriverSettings): raise NotImplementedError
[ "def set_pulse_on_hit_rule(self, enable_switch, coil):\n raise NotImplementedError", "def set_pulse_on_hit_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):\n self._check_coil_switch_combination(coil, enable_switch)\n driver = coil.hw_driver\n driver.set_hardware_rule(1,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set pulse on hit and release rule to driver. Pulses a driver when a switch is hit. When the switch is released the pulse is canceled. Typically used on the main coil for dual coil flippers without eos switch.
def set_pulse_on_hit_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings): raise NotImplementedError
[ "def set_pulse_on_hit_and_release_rule(self, enable_switch, coil):\n raise NotImplementedError", "def set_pulse_on_hit_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):\n self._check_coil_switch_combination(coil, enable_switch)\n driver = coil.hw_driver\n dri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set pulse on hit and enable and release rule on driver. Pulses a driver when a switch is hit. Then enables the driver (may be with pwm). When the switch is released the pulse is canceled and the driver gets disabled. Typically used for single coil flippers.
def set_pulse_on_hit_and_enable_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings): raise NotImplementedError
[ "def set_pulse_on_hit_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):\n raise NotImplementedError", "def set_pulse_on_hit_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):\n self._check_coil_switch_combination(coil, enable_switch)\n driv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set pulse on hit and enable and release and disable rule on driver. Pulses a driver when a switch is hit. When the switch is released the pulse is canceled and the driver gets disabled. When the eos_switch is hit the pulse is canceled and the driver becomes disabled. Typically used on the main coil for dualwound coil f...
def set_pulse_on_hit_and_release_and_disable_rule(self, enable_switch: SwitchSettings, eos_switch: SwitchSettings, coil: DriverSettings, repulse_settings: Optional[RepulseSettings]): raise NotImplementedE...
[ "def set_pulse_on_hit_and_release_and_disable_rule(self, enable_switch: SwitchSettings, eos_switch: SwitchSettings,\n coil: DriverSettings,\n repulse_settings: Optional[RepulseSettings]):\n del repulse_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set pulse on hit and enable and release and disable rule on driver. Pulses a driver when a switch is hit. Then enables the driver (may be with pwm). When the switch is released the pulse is canceled and the driver becomes disabled. When the eos_switch is hit the pulse is canceled and the driver becomes enabled (likely ...
def set_pulse_on_hit_and_enable_and_release_and_disable_rule(self, enable_switch: SwitchSettings, eos_switch: SwitchSettings, coil: DriverSettings, repulse_settings: Optional[RepulseSettings...
[ "def set_pulse_on_hit_and_release_and_disable_rule(self, enable_switch: SwitchSettings,\n eos_switch: SwitchSettings, coil: DriverSettings,\n repulse_settings: Optional[RepulseSettings]):\n raise NotImpl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a callback for when the given future has been resolved.
def on_future(self, _future, _callback, *_args, **_kwargs): callback = functools.partial(self._do_on_future, _callback, _args, _kwargs) # Create timeout handler and regular handler. self._future_timeouts[_future] = self.schedule_in(self.future_timeout, callback) future.add_done_callback...
[ "def add_done_callback(self, callback):\n self._loop.call_soon_threadsafe(self.future.add_done_callback, callback)", "def add_done_callback(self, fn):\n if self._result_set:\n _helpers.safe_invoke_callback(fn, self)\n return\n\n self._done_callbacks.append(fn)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule a callback to be ran as soon as possible in this loop. Will return an opaque handle that can be passed to `unschedule` to unschedule the function.
def schedule(self, _callback, *_args, **_kwargs): @coroutine @functools.wraps(_callback) def inner(): _callback(*_args, **_kwargs) return self.schedule_async(inner())
[ "def schedule_callback(self, deferred, func, *args, **kwargs):\n self.increment_pc()\n saved_pc = self.program_counter[:]\n\n @wrapper(func)\n def callback_wrapper(*args, **kwargs):\n \"\"\"Wrapper for a callback which ensures a correct PC.\"\"\"\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule a callback to be ran as soon as possible after `when` seconds have passed. Will return an opaque handle that can be passed to `unschedule` to unschedule the function.
def schedule_in(self, _when, _callback, *_args, **_kwargs): if isinstance(_when, datetime.timedelta): _when = _when.total_seconds() @coroutine @functools.wraps(_callback) def inner(): yield from asyncio.sleep(_when) _callback(*_args, **_kwargs) ...
[ "def schedule_async_in(self, _when, _callback):\n if isinstance(_when, datetime.timedelta):\n _when = _when.total_seconds()\n\n @coroutine\n @functools.wraps(_callback)\n def inner():\n yield from asyncio.sleep(_when)\n yield from _callback\n\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule a coroutine to be ran as soon as possible after `when` seconds have passed. Will return an opaque handle that can be passed to `unschedule` to unschedule the function.
def schedule_async_in(self, _when, _callback): if isinstance(_when, datetime.timedelta): _when = _when.total_seconds() @coroutine @functools.wraps(_callback) def inner(): yield from asyncio.sleep(_when) yield from _callback return self.schedu...
[ "def schedule_in(self, _when, _callback, *_args, **_kwargs):\n if isinstance(_when, datetime.timedelta):\n _when = _when.total_seconds()\n\n @coroutine\n @functools.wraps(_callback)\n def inner():\n yield from asyncio.sleep(_when)\n _callback(*_args, **_k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule a callback to be ran every `interval` seconds. Will return an opaque handle that can be passed to unschedule() to unschedule the interval function. A function will also stop being scheduled if it returns False or raises an Exception.
def schedule_periodically(self, _interval, _callback, *_args, **_kwargs): if isinstance(_interval, datetime.timedelta): _interval = _interval.total_seconds() @coroutine @functools.wraps(_callback) def inner(): while True: yield from asyncio.sleep(...
[ "def schedule_interval(self, callback, interval, *args, **kwargs):\n if self.is_running:\n pyglet.clock.schedule_interval(callback, interval, *args, **kwargs)\n self.scheduled_interval_calls.append(\n (callback, interval, args, kwargs)\n )", "def on_interval(interval...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whether or not the given handle is still scheduled.
def is_scheduled(self, handle): return not handle.cancelled()
[ "def is_locked(self):\r\n if not self.is_active():\r\n return True\r\n #last = self.last_queued()\r\n if not self.locked_until or self.locked_until < datetime.datetime.now():\r\n return False\r\n return True", "def was_not_handled(self):\n\n return task_sch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run until future is resolved.
def run_until(self, future): @coroutine def inner(): yield from future self._unschedule_all() self.loop.run_until_complete(asyncio.ensure_future(inner()))
[ "async def wait_until_done(self) -> None:\n ...", "def run_until_complete(self, future, **kw):\n\n def stop(f):\n self.stop()\n\n future = tasks.ensure_future(future, loop=self)\n future.add_done_callback(stop)\n try:\n self.run_forever(**kw)\n final...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take a nuke node, such as a read node or a Cryptomatte gizmo, and Reformat metadata into a dictionary, and collect channel information.
def __init__(self, node_in): self.cryptomattes = {} self.nuke_node = node_in self.selection = None if not node_in: return exr_metadata_dict = node_in.metadata() or {} prefix = "exr/cryptomatte/" default_selection = None for key, value in exr...
[ "def __init__(self, node_in, reload_metadata=False):\n self.cryptomattes = {}\n self.nuke_node = node_in\n self.selection = None\n self.filename = None\n\n if not self.nuke_node:\n return\n\n exr_metadata_dict = {}\n if not reload_metadata:\n ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that the selection is valid.
def is_valid(self): if self.selection is None: return False if self.selection not in self.cryptomattes: return False if "channels" not in self.cryptomattes[self.selection]: return False if len(self.cryptomattes[self.selection]["channels"]) < 2: ...
[ "def _can_select(self):\n return self.multiple_selection or len(self.regions) < 1", "def validateSelection(self, exportItems):\n\n invalidItems = []\n # Look for selected items which arent of the correct type\n for item in exportItems:\n if not item.sequence() and not item.trackItem():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets the selection (eg. cryptoObject) based on the name. Returns true if successful.
def set_selection(self, selection): for num in self.cryptomattes: if self.cryptomattes[num]["name"] == selection: self.selection = num return True self.selection = None return False
[ "def set_selection(self, selection):\n selection = _legal_nuke_layer_name(selection)\n for num in self.cryptomattes:\n if self.cryptomattes[num][\"name\"] == selection:\n self.selection = num\n return True\n self.selection = None\n return False", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the names of the cryptomattes contained the file, which are the possible selections or cryptomatte channels.
def get_cryptomatte_names(self): return [self.cryptomattes[x]["name"] for x in self.cryptomattes]
[ "def _identify_channels(self, name):\n\n channel_list = []\n if self.nuke_node.Class() in [\"Cryptomatte\", \"Encryptomatte\"]:\n # nuke_node is a keyer gizmo or encryptomatte gizmo\n channel_list = self.nuke_node.node('Input1').channels()\n else:\n # nuke_node ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
from a name like "cryptoObject", gets sorted channels, such as cryptoObject, cryptoObject00, cryptoObject01
def _identify_channels(self, name): channel_list = [] if self.nuke_node.Class() == "Cryptomatte": # nuke_node is a keyer gizmo channel_list = self.nuke_node.node('Input1').channels() else: # nuke_node might a read node channel_list = self.nuke_nod...
[ "def ordered_channel_names(self):\n channel_list = []\n for k in self.__dict__.keys():\n if k.startswith('channel_'):\n channel_list.append(\n [int(k.split('channel_')[1]), self.__dict__[k]]\n )\n channel_list.sort()\n if le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads json manifest and unpacks hex strings into floats, and converts it to two dictionaries, which map IDs to names and vice versa. Also caches the last manifest in a global variable so that a session of selecting things does not constantly require reloading the manifest (' ~0.13 seconds for a 32,000 name manifest.')
def parse_manifest(self): import json import struct num = self.selection try: manifest = json.loads(self.cryptomattes[num].get("manifest", "{}")) except: manifest = {} from_names = {} from_ids = {} unpacker = struct.Struct('=f') ...
[ "def parse_manifest(self):\n import json\n import struct\n import os\n\n num = self.selection\n manifest = {}\n\n manif_file = self.cryptomattes[num].get(\"manif_file\", \"\")\n if manif_file:\n manif_file = self.resolve_manifest_paths(self.filename, manif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing function to check for implementation errors and hash collisions. Checks all names and values in the manifest in the manifest by rehashing them, to ensure that the entire process is sound. Also finds collisions. Returns a tuple of errors and collisions.
def test_manifest(self): self.parse_manifest() ids = {} errors = [] collisions = [] manifest = self.cryptomattes[self.selection]["names_to_IDs"] for name, idvalue in manifest.iteritems(): if mm3hash_float(name) != idvalue: errors.append("compu...
[ "def test_manifest(self, quiet=False):\n self.parse_manifest()\n\n ids = {}\n errors = []\n collisions = []\n manifest = self.cryptomattes[self.selection][\"names_to_IDs\"]\n for name, idvalue in manifest.items():\n if mm3hash_float(name) != idvalue:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a connection to another endpoint and return a ConnectionId for it. You can send messages on this ConnectionId immediately.
def connect(self, endpoint: Endpoint) -> ConnectionId: if not self.started: raise Exception(f"Bus {self.busIdentity} is not active") endpoint = Endpoint(endpoint) with self._lock: connId = self._newConnectionId() self._connIdToOutgoingEndpoint[connId] = endp...
[ "def create(self, connectionParams) :\n conn = RemoteConnection(connectionParams)\n\n # Generate a unique id by which to refer to this connection in the future\n id = str(uuid.uuid1())\n\n self.remoteConnections[id] = conn\n return id", "def _connection_maker(\n self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule a callback to fire on the message read thread. Use 'delay' or 'atTimestamp' to decide when the callback runs, or use neither to mean 'immediately'. You can't use both.
def scheduleCallback(self, callback, *, atTimestamp=None, delay=None): if callback is None: self._logger.warning("Cannot scheduleCallback(None); discarding.") # This would cause the event loop thread to terminate return if atTimestamp is not None and delay is not Non...
[ "def _call_later(self, delay, callback):\n self.io_loop.call_later(delay, callback)", "def schedule(self, delay, cb):\n return scheduler.add(delay, callback=cb)", "def poll(self):\n msgs = self._read()\n\n if msgs and self.callback:\n for msg in msgs:\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule an event to get sent to the onEvent callback on the input loop
def _scheduleEvent(self, event): self._eventsToFireQueue.put(event) assert os.write(self._eventToFireWakePipe[1], b" ") == 1
[ "def event_queue_proc(self,event):\r\n event()", "def activate(t):\n if t.input != timer:\n loop.add_reader(t.input, (lambda: handler(t.input)))", "def schedule_next_event(self):\n if self.events:\n self.event = self.events.pop()\n self.timeout_counter = self.event....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Our select loop indicated 'socketWithData' has data pending.
def _handleReadReadySocket(self, socketWithData): if socketWithData is self._acceptSocket: try: newSocket, newSocketSource = socketWithData.accept() except OSError as exc: # e.g., OSError: [Errno 24] Too many open files self._logger.info(f...
[ "def await_data(self):\n self.data.append(self.socket.recv(1))", "def _read_data(self):\n while True:\n try:\n data = yield from asyncio.wait_for(self._socket.recv(), 1)\n except asyncio.TimeoutError:\n continue\n except asyncio.Cancelle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Socket 'writeable' can accept more bytes.
def _handleWriteReadySocket(self, writeable): if writeable not in self._socketToBytesNeedingWrite: return try: bytesWritten = writeable.send(self._socketToBytesNeedingWrite[writeable]) except ssl.SSLWantReadError: bytesWritten = -1 except ssl.SSLWan...
[ "def writeSomeData(self, data):\n try:\n # Limit length of buffer to try to send, because some OSes are too\n # stupid to do so themselves (ahem windows)\n return self.socket.send(buffer(data, 0, self.SEND_LIMIT))\n except socket.error, se:\n if se.args[0] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate over the items in the wishlist and get the products from the database.
def __iter__(self): product_ids = self.wishlist.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.wishlist[str(product.id)]['product'] = product for item in self.wishlist.values(): yield item
[ "def __iter__(self):\n products_ids = self.wishlist.keys()\n # get the products objects and add them to the wishlist\n products = Product.objects.filter(id__in=products_ids)\n\n wishlist_session = self.wishlist.copy()\n wishlist = {}\n for product in products:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add or remove a product to the wishlist or update its quantity.
def add_remove(self, product): product_id = str(product.id) if product_id not in self.wishlist: self.wishlist[product_id] = {'price': str(product.price_in_dollars)} else: del self.wishlist[product_id] self.save()
[ "def add(self, product):\n product_id = str(product.id)\n self.wishlist[product_id] = {'price': str(product.price)}\n self.save()", "def add_to_wishlist(request, product_id):\n product = get_object_or_404(Product, pk=product_id)\n wishlist = get_object_or_404(Wishlist, user=request.user...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Permute elements of a tensor along a dimension `dim`. If permutation is None do nothing.
def apply_permutation(tensor: Tensor, dim: int, permutation: Optional[Tensor]): if permutation is None: return tensor return tensor.index_select(dim, permutation)
[ "def _permute_tensor(input, permutation):\n # Cache the original dimensions\n dimensions = input.size()\n\n # Apply the permutation to the flattened tensor\n output_flat = torch.index_select(input.view(-1), 0, permutation)\n\n # Restore original dimensions\n output = output_flat.view(dimensions)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through all the layers and through all directions within each layer. Arguments should be listlike of length ``num_layers num_directions`` where each element corresponds to (layer, direction) pair. The corresponding elements of each of these lists will be iterated over.
def iterate_layers(self, *args): for layer in range(self.num_layers): yield layer, ( ( direction, tuple(arg[self.num_directions * layer + direction] for arg in args), ) for direction in range(self.num_directions)...
[ "def __iter__(self) -> Iterable[\"AbstractLane\"]:\n for origin in self.graph:\n for destination in self.graph[origin]:\n for index, lane in self.graph[origin][destination].items():\n yield lane", "def layers(self):\r\n\r\n\t\tif self.numlayerdims == 0:\r\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scale Flickr url_s image to fit Folium popup. Popup shape is hardcoded as `self.popup_width` in both length and height. Function rescales so that the long axis exactly fits within this box.
def scale_image_to_frame(self, width, height): aspect = width / height # Image is landscape. if aspect >= 1: scale = self.popup_width / width return (self.popup_width, int(scale * height)) # Otherwise image is portrait. scale = self.popup_width / height ...
[ "def scaleFitWindow(self):\n e = 2.0 # So that no scrollbars are generated.\n w1 = self.width() * 0.65 - e\n h1 = self.height() * 0.65 - e\n a1 = w1 / h1\n # Calculate a new scale value based on the pixmap's aspect ratio.\n w2 = self.canvas.image.width() - 0.0\n h2 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the lowest four bits of all the 16 bits tiff file in a folder to zero.
def tiff_low_four_bits_set_zero(path_tiff_source, path_tiff_out): dir = glob.glob(path_tiff_source + '\\' + '*.tiff') for source_file in dir: tif = TIFF.open(source_file, mode='r') img = tif.read_image() img = img - img % 16 #lowest four bits set zero img_name = os.path.basenam...
[ "def reset(self):\n self.all_files_idx = np.arange(self._div*self._nb_dir)\n\n if self.shuffle>1:\n np.random.shuffle(self.all_files_idx)\n\n self.idx_folder = self.all_files_idx//self._div\n self.idx_file = self.all_files_idx % self._div\n self.current_folder = self.id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function splits one 16bits tiff file to two different 8bits tiff files. The strategy of split is setting the lowest 8 bits of the source 16 bits file as the pixel value of one split file and the same as the highest 8 bits.
def tiff_split(path_tiff_source, path_tiff_out): path_out_low = path_tiff_out + '\\' + 'low8bits' path_out_hig = path_tiff_out + '\\' + 'high8bits' path_out_list=[path_out_hig,path_out_low] makdir(path_out_low) makdir(path_out_hig) for file in glob.glob(path_tiff_source + '\\' + '*.tiff'): ...
[ "def binary4_split(self):\n self.black = cv2.inRange(self.image, 0, 40)\n self.darkgrey = cv2.inRange(self.image, 41, 131)\n self.lightgrey = cv2.inRange(self.image, 132, 220)\n self.white = cv2.inRange(self.image, 221, 255)", "def splitImgs(self, tile_size, n_tiles):\n\n if n_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
unblock the given ip
def unblock_ip_view(request, ip): if request.method == 'POST': unblock_ip(ip) return HttpResponseRedirect(reverse("defender_blocks_view"))
[ "def unblock_ip(ip, logger, dashboard_log, firewall_ip_and_port):\n try:\n request = requests.delete(f\"http://{firewall_ip_and_port}/firewall/{ip}\")\n if not request.ok:\n logger.error(f\"Unblocking IP {ip} was unsuccessful. Code {request.status_code}\")\n dashboard_log.appe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
unblock he given username
def unblock_username_view(request, user_id): if request.method == 'POST': username = User.objects.get(id=user_id).username unblock_username(username) log_user_unlock.send(sender=unblock_username_view, request=request, username=username) return HttpResponse(json.dumps({"status": "unlo...
[ "async def unblockcmd(self, message):\n user = await utils.get_target(message)\n if not user:\n await utils.answer(message, self.strings[\"who_to_unblock\"])\n return\n await message.client(functions.contacts.UnblockRequest(user))\n await utils.answer(message, self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns adapter implementing the ICAVLService interface using CAVL_SERVICE setting
def get_cavl_service() -> ICAVLService: try: return import_string(settings.CAVL_SERVICE)() except ImportError as e: msg = "Could not import '%s' for API setting 'CAVL_SERVICE'. %s: %s." % ( settings.CAVL_SERVICE, e.__class__.__name__, e, ) rais...
[ "def get_ksa_adapter(service_type, ksa_auth=None, ksa_session=None,\n min_version=None, max_version=None):\n confgrp = _get_conf_group(service_type)\n\n ksa_auth, ksa_session = _get_auth_and_session(\n confgrp, ksa_auth, ksa_session)\n\n return ks_loading.load_adapter_from_conf_op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns adapter implementing INotification interface using NOTIFIER setting
def get_notifications() -> INotifications: notifiers = {"django": DjangoNotifier, "govuk-notify": GovUKNotifyEmail} notifier = getattr(settings, "NOTIFIER", "django") notifier_class = notifiers[notifier] return notifier_class()
[ "def notifier(self, name):\n\n # Look up the notifier\n notifier = self.notifiers.get(name, self.notifiers.get(None))\n\n # Return the driver\n return notifier.driver", "def notifier(self):\n\n return self.config.notifier(self._notifier)", "def get_notifiers():\n return {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
saveAsim(samplePt, obj_animatLabModel, fldrSimFiles, ix, indexLen, verbose=3) samplePt Dict of simulation parameters to update with key as [element name].[element property] obj_animatLabModel AnimatLabModel object to update fldrSimFiles Folder path where simulation files are saved ix Incremented file index to avoid ove...
def saveAsim(samplePt, obj_animatLabModel, fldrSimFiles, ix, indexLen=3, verbose=3): #cols = ['ERROR'] cols = [] basename = os.path.split(obj_animatLabModel.asimFile)[-1].split('.')[0] saveFile = {} # Generate new .asim file name filename = basename + '-' + str(ix+1).zfill(indexLen) + '.a...
[ "def _save_mayavi_figure(self, fig, filename, azimuth=153, elevation=62,\n distance=400, focalpoint=[25., 63., 60.], aa=16,\n size=(1024, 1024)):\n scene = fig.scene\n\n scene.anti_aliasing_frames = aa\n\n mlab.view(azimuth=azimuth, elevatio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
__init__(projName, obj_aproj=None, obj_simRunner=None, obj_simSet=None) Initiate ProjectManager object projName Unique name for ProjectManager object obj_aproj AnimatLabModel object obj_simrunner SimRunner object
def __init__(self, projName, obj_aproj=None, obj_simRunner=None): self.projName = projName self.activityLog = {} self.errorLog = {} if (type(obj_aproj) == AnimatLabModel) or (obj_aproj is None): self.aproj = obj_aproj else: raise TypeErro...
[ "def __init__(self, ctx, provider=None):\n super(A2MLProject, self).__init__(ctx, 'project')\n self.runner = self.build_runner(ctx, provider)", "def __init__(self, task_queue, results_queue, individuals):\n Process.__init__(self)\n \n self.proc_name = self.name\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set_aproj(obj_aproj) Sets the AnimatLabModel object for the ProjectManager obj_aproj AnimatLabModel object for basis of simulations
def set_aproj(self, obj_aproj): if type(obj_aproj) == AnimatLabModel: self.aproj = obj_aproj else: raise TypeError("obj_aproj must be an AnimatLabModel object!")
[ "def __init__(self, projName, obj_aproj=None, obj_simRunner=None):\n \n self.projName = projName\n self.activityLog = {}\n self.errorLog = {}\n \n if (type(obj_aproj) == AnimatLabModel) or (obj_aproj is None):\n self.aproj = obj_aproj\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set_simRunner(obj_simRunner) Sets the simRunner object for the ProjectManager obj_simRunner SimulationRunner object for organizing simulations
def set_simRunner(self, obj_simRunner): if type(obj_simRunner) == AnimatLabSimulationRunner: self.simRunner = obj_simRunner else: raise TypeError("obj_simRunner must be an AnimatLabSimulationRunner object!")
[ "def setSimulation(self, simulation):\r\n raise NotImplementedError()", "def set_up_sim_tool(self, sim_tool: HammerSimTool,\n name: str, run_dir: str = \"\") -> bool:\n\n if self.tech is None:\n self.log.error(\"Must load technology before loading sim tool\")\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make_asims(obj_simSet) obj_simSet SimulationSet object used to generate parameter combinations DESCRIPTION Generates .asim files used as the basis for AnimatLab simulations based on the parameter dictionary formatted by obj_simSet.
def make_asims(self, obj_simSet): if type(obj_simSet) is not SimulationSet: raise TypeError("obj_simSet must be a SimulationSet object!") cols = ['FileName'] saveFiles = {} # Calculate size of text buffer for naming files countLength = len(...
[ "def createArmySims(self):\n # create army sims for player\n for systemID in self.game.myArmies.keys():\n self.createPlayerArmySim(systemID)\n \n # create army sims representing other empires\n for systemID in self.game.otherArmies.keys():\n self.createOtherA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run(cores=1) cores Number of cores to use to run simulations. None >> Run simulations in serial (longest time) + [] >> Use up to [] of cores 1 >> Use ALL CPU cores DESCRIPTION ProjectManager.run() is a simple interface function that runs AnimatLab simulations. The cores argument is passed to the simulationRunner class,...
def run(self, cores=-1): self.simRunner.do_simulation(cores=cores) return True
[ "def run_simulation(num_robots, speed, capacity, width, height, dirt_amount, min_coverage, num_trials,\n robot_type):\n raise NotImplementedError", "def run_sim(params):\n sim = Simulation(params)\n return sim.run()", "def set_cores(self, cores):\n self.cores = cores\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
m is a the message encoded as a polynomial
def encrypt(self,m): if m._N <= self._P.get_N(): r = self._P.gen_rPoly() e = (r.scale(self._P.get_p())*self._h+m) % self._P.get_q() return e # Polynomial representing the encryption message else: raise Exception("m is too large, must be equal or under si...
[ "def CharacteristicPolynomial(mol, mat=...): # -> ndarray:\n ...", "def fpoly(x, m):\n if isinstance(x, np.ndarray):\n n = x.size\n else:\n n = 1\n if m < 1:\n raise ValueError('Order of polynomial must be at least 1.')\n try:\n dt = x.dtype\n except AttributeError:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps a list of strings to their shortest unique suffixes Maps all original strings to the smallest number of chunks, as specified by delim, that are not a suffix of any other original string. If the original string was a suffix of another string, map it to its unaltered self.
def _get_shortest_unique_suffix_dict( input_str_list: List[str], delim: str = "." ) -> Dict[str, str]: # all input strings must be unique assert len(input_str_list) == len(set(input_str_list)) if delim == "": raise ValueError("delim must be a non-empty string.") suffix_dict = defaultdict(li...
[ "def ukkonen(self):\n\n\t\tfor i in range(len(self.original_string)):\n\t\t\t# Construct the implicit suffix tree for the prefix S[1..i]\n\t\t\tfor j in range(1, i+1): \n\t\t\t\t# These indices are bound to be wrong\n\t\t\t\t# This will need changed in order to actually get the linear running \n\t\t\t\t# time.\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract standard plots for singleobjective optimization. Extracts a list of plots from an Experiment and GenerationStrategy of general interest to an Ax user. Currently not supported are
def get_standard_plots( experiment: Experiment, generation_strategy: Optional[GenerationStrategy] ) -> List[go.Figure]: objective = not_none(experiment.optimization_config).objective if isinstance(objective, MultiObjective): logger.warning( "get_standard_plots does not currently support...
[ "def get_plots(self):\n plots = list()\n plots.append({\"name\": \"MODESTGA\", \"axes\": self.plot_parameter_evo()})\n return plots", "def make_plots(population, generation):\n base = \"post\"\n label = \"gen_\" + str(generation)\n\n objectives = len(archive[0][0].fitness)\n\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms an experiment to a DataFrame. Only supports Experiment and SimpleExperiment. Transforms an Experiment into a dataframe with rows keyed by trial_index and arm_name, metrics pivoted into one row.
def exp_to_df( exp: Experiment, metrics: Optional[List[Metric]] = None, run_metadata_fields: Optional[List[str]] = None, trial_properties_fields: Optional[List[str]] = None, **kwargs: Any, ) -> pd.DataFrame: def prep_return( df: pd.DataFrame, drop_col: str, sort_by: List[str] ) -> p...
[ "def exp_to_df(\n exp: Experiment,\n metrics: Optional[List[Metric]] = None,\n key_components: Optional[List[str]] = None,\n **kwargs: Any,\n) -> pd.DataFrame:\n key_components = key_components or [\"trial_index\", \"arm_name\"]\n\n # Accept Experiment and SimpleExperiment\n if isinstance(exp, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the optimal trial given an experiment, based on raw objective value. Returns a 1row dataframe. Should match the row of ``exp_to_df`` with the best raw objective value, given the same arguments.
def get_best_trial( exp: Experiment, additional_metrics: Optional[List[Metric]] = None, run_metadata_fields: Optional[List[str]] = None, **kwargs: Any, ) -> Optional[pd.DataFrame]: objective = not_none(exp.optimization_config).objective if isinstance(objective, MultiObjective): logger.wa...
[ "def evaluate_optimum(dataset: Dataset) -> pd.DataFrame:\n # Get the index of data point with highest observed objective\n optimum_idx = dataset.pretransform_df[dataset.pretransform_output_name].argmax()\n # Get the inputs of the data point with highest observed objective\n optimum_loc = dataset.pretran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the form on get, on submission, save the uploaded pdf to the "serial" directory, and return the form populated along with the generated thumbnails.
def generate_thumbnails(self): form = Form(PDFUploadSchema(), buttons=("submit",)) if "submit" in self.request.POST: log.info("submit: %s", self.request.POST) controls = self.request.POST.items() try: appstruct = form.validate(controls) ...
[ "def upload():\n\n form = ScanDocumentForm()\n\n if form.validate_on_submit():\n\n file = form.filePdf.data\n pdf = PdfFile(name=file.filename, num_page=form.num_page, pdf_owner=current_user.get_id())\n\n # set range\n if form.has_range:\n print(\"set range\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the output filenames and generate the top and mosaic thumbnails and write them to disk.
def write_thumbnails(self, appstruct): slugser = slugify(appstruct["serial"]) pdf_filename = "thumbnails/%s/uploaded.pdf" % slugser top_file = "thumbnails/%s/top.png" % slugser mos_file = "thumbnails/%s/mosaic.png" % slugser thumg = ThumbnailGenerator(pdf...
[ "def writeThumbnails():\n thumbs = getThumbnails()\n for i in thumbs:\n os.system(\n f\"eyeD3 --add-image 'thumbnails/{i}:FRONT_COVER' 'music/mp3/{removeExtension(i)}.mp3'\")", "def create_mosaic(self):\n\n mosaic = self.create_trimmed_mosaic_base()\n s_img_p = SourceImagePro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expect a binary blob of image data from wand and a filename. Write the binary blob to the file.
def save_blob(self, img_blob, filename): out_file = open(filename, "wb") out_file.write(img_blob) out_file.close()
[ "def _save_binary(file_name, data):\n with open(file_name, \"wb\") as f:\n cp.dump(data, f)", "def writebinary(filename, infile):\n filehandle = open(filename, 'wb')\n filehandle.write(infile)\n filehandle.close()", "def write_img_to_db():\n with lite.connect(\"test.db\") as con:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read from the file pointer, write intermediate file, and then copy to final destination.
def single_file_write(self, file_pointer, filename): temp_file = "resources/temp_file" file_pointer.seek(0) with open(temp_file, "wb") as output_file: shutil.copyfileobj(file_pointer, output_file) os.rename(temp_file, filename) log.info("Saved file: %s", filename)
[ "def tag_copy(in_fh, out_fh, size):\n contents = in_fh.read(size)\n out_fh.write(contents)", "def copyfileobj(self, fsrc, fdst, length=(16*1024)):\n fsrcRead = fsrc.read\n fdstWrite = fdst.write\n while True:\n buf = fsrcRead(length)\n if not buf:\n brea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }