body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def make_request(self, request, data, max_wait=600, step=5, wait=0):
'Sends a get, post or delete request every step seconds until the request was successful or wait exceeds max_wait.\n\n Args:\n request (str): Define which kind of request to execute.\n data (str): Submit information or... | 6,385,178,805,594,607,000 | Sends a get, post or delete request every step seconds until the request was successful or wait exceeds max_wait.
Args:
request (str): Define which kind of request to execute.
data (str): Submit information or sherpas job_id for a status request or job_id for deleting a trial.
max_wait (int, optional): Tim... | argo_scheduler.py | make_request | predictive-quality/ml-pipeline-blocks-hpo-sherpa | python | def make_request(self, request, data, max_wait=600, step=5, wait=0):
'Sends a get, post or delete request every step seconds until the request was successful or wait exceeds max_wait.\n\n Args:\n request (str): Define which kind of request to execute.\n data (str): Submit information or... |
def file_strategy(self, job_id, metrics):
'Delete all trial files which were generated through a hpo trial\n It deletes all files in the output_path related to the job_id\n\n Args:\n job_id (str): Sherpa Job_ID / Argo trial workflow name\n metrics (dict): metrics to compare\n... | -7,574,703,012,453,597,000 | Delete all trial files which were generated through a hpo trial
It deletes all files in the output_path related to the job_id
Args:
job_id (str): Sherpa Job_ID / Argo trial workflow name
metrics (dict): metrics to compare | argo_scheduler.py | file_strategy | predictive-quality/ml-pipeline-blocks-hpo-sherpa | python | def file_strategy(self, job_id, metrics):
'Delete all trial files which were generated through a hpo trial\n It deletes all files in the output_path related to the job_id\n\n Args:\n job_id (str): Sherpa Job_ID / Argo trial workflow name\n metrics (dict): metrics to compare\n... |
def submit_job(self, command, env={}, job_name=''):
"Submits a new hpo trial to argo in order to start a workflow template\n\n Args:\n command (list[str]): List that contains ['Argo WorkflowTemplate','Entrypoint of that Argo WorkflowTemplate]\n env (dict, optional): Dictionary that cont... | 1,542,736,167,545,708,800 | Submits a new hpo trial to argo in order to start a workflow template
Args:
command (list[str]): List that contains ['Argo WorkflowTemplate','Entrypoint of that Argo WorkflowTemplate]
env (dict, optional): Dictionary that contains env variables, mainly the sherpa_trial_id. Defaults to {}.
job_name (str, op... | argo_scheduler.py | submit_job | predictive-quality/ml-pipeline-blocks-hpo-sherpa | python | def submit_job(self, command, env={}, job_name=):
"Submits a new hpo trial to argo in order to start a workflow template\n\n Args:\n command (list[str]): List that contains ['Argo WorkflowTemplate','Entrypoint of that Argo WorkflowTemplate]\n env (dict, optional): Dictionary that contai... |
def get_status(self, job_id):
'Obtains the current status of the job.\n Sends objective values/metrics to the DB when a trial succeeded.\n Compares objective values and decides wether to delete or keep files. \n\n Args:\n job_id (str): Sherpa Job_ID / Name of the workflow tha... | 8,755,017,924,860,176,000 | Obtains the current status of the job.
Sends objective values/metrics to the DB when a trial succeeded.
Compares objective values and decides wether to delete or keep files.
Args:
job_id (str): Sherpa Job_ID / Name of the workflow that was started by Argo
Returns:
sherpa.schedulers._JobStatus: the jo... | argo_scheduler.py | get_status | predictive-quality/ml-pipeline-blocks-hpo-sherpa | python | def get_status(self, job_id):
'Obtains the current status of the job.\n Sends objective values/metrics to the DB when a trial succeeded.\n Compares objective values and decides wether to delete or keep files. \n\n Args:\n job_id (str): Sherpa Job_ID / Name of the workflow tha... |
def kill_job(self, job_id):
'Kill a job by deleting the argo workflow completly\n\n Args:\n job_id (str): Sherpa Job_ID / Name of the workflow that was started by Argo\n '
response_kill = self.make_request(request='DELETE', data=job_id)
if (response_kill.status_code == 200):
... | -2,386,664,912,636,583,000 | Kill a job by deleting the argo workflow completly
Args:
job_id (str): Sherpa Job_ID / Name of the workflow that was started by Argo | argo_scheduler.py | kill_job | predictive-quality/ml-pipeline-blocks-hpo-sherpa | python | def kill_job(self, job_id):
'Kill a job by deleting the argo workflow completly\n\n Args:\n job_id (str): Sherpa Job_ID / Name of the workflow that was started by Argo\n '
response_kill = self.make_request(request='DELETE', data=job_id)
if (response_kill.status_code == 200):
... |
def _module_available(module_path: str) -> bool:
"\n Check if a path is available in your environment\n\n >>> _module_available('os')\n True\n >>> _module_available('bla.bla')\n False\n "
try:
return (find_spec(module_path) is not None)
except AttributeError:
return False
... | 1,338,762,679,162,271,200 | Check if a path is available in your environment
>>> _module_available('os')
True
>>> _module_available('bla.bla')
False | pytorch_lightning/utilities/imports.py | _module_available | Queuecumber/pytorch-lightning | python | def _module_available(module_path: str) -> bool:
"\n Check if a path is available in your environment\n\n >>> _module_available('os')\n True\n >>> _module_available('bla.bla')\n False\n "
try:
return (find_spec(module_path) is not None)
except AttributeError:
return False
... |
def _compare_version(package: str, op, version) -> bool:
'\n Compare package version with some requirements\n\n >>> _compare_version("torch", operator.ge, "0.1")\n True\n '
try:
pkg = importlib.import_module(package)
except (ModuleNotFoundError, DistributionNotFound):
return Fals... | -222,479,884,128,013,500 | Compare package version with some requirements
>>> _compare_version("torch", operator.ge, "0.1")
True | pytorch_lightning/utilities/imports.py | _compare_version | Queuecumber/pytorch-lightning | python | def _compare_version(package: str, op, version) -> bool:
'\n Compare package version with some requirements\n\n >>> _compare_version("torch", operator.ge, "0.1")\n True\n '
try:
pkg = importlib.import_module(package)
except (ModuleNotFoundError, DistributionNotFound):
return Fals... |
def init():
'Return True if the plugin has loaded successfully.'
g.trace('pyplot_backend.py is not a plugin.')
return False | 2,428,046,564,228,245,500 | Return True if the plugin has loaded successfully. | leo/plugins/pyplot_backend.py | init | ATikhonov2/leo-editor | python | def init():
g.trace('pyplot_backend.py is not a plugin.')
return False |
def new_figure_manager(num, *args, **kwargs):
'\n Create a new figure manager instance\n '
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig) | -4,321,160,556,889,542,700 | Create a new figure manager instance | leo/plugins/pyplot_backend.py | new_figure_manager | ATikhonov2/leo-editor | python | def new_figure_manager(num, *args, **kwargs):
'\n \n '
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig) |
def new_figure_manager_given_figure(num, figure):
'\n Create a new figure manager instance for the given figure.\n '
canvas = FigureCanvasQTAgg(figure)
return LeoFigureManagerQT(canvas, num) | -3,158,270,832,078,468,000 | Create a new figure manager instance for the given figure. | leo/plugins/pyplot_backend.py | new_figure_manager_given_figure | ATikhonov2/leo-editor | python | def new_figure_manager_given_figure(num, figure):
'\n \n '
canvas = FigureCanvasQTAgg(figure)
return LeoFigureManagerQT(canvas, num) |
def __init__(self, canvas, num):
'Ctor for the LeoFigureManagerQt class.'
self.c = c = g.app.log.c
super().__init__(canvas, num)
self.canvas = canvas
self.vr_controller = vc = vr.controllers.get(c.hash())
self.splitter = c.free_layout.get_top_splitter()
self.frame = w = QtWidgets.QFrame()
... | -1,373,600,437,377,754,600 | Ctor for the LeoFigureManagerQt class. | leo/plugins/pyplot_backend.py | __init__ | ATikhonov2/leo-editor | python | def __init__(self, canvas, num):
self.c = c = g.app.log.c
super().__init__(canvas, num)
self.canvas = canvas
self.vr_controller = vc = vr.controllers.get(c.hash())
self.splitter = c.free_layout.get_top_splitter()
self.frame = w = QtWidgets.QFrame()
w.setLayout(QtWidgets.QVBoxLayout())
... |
def main():
'Main program code.'
window = MyGame()
window.setup()
arcade.run() | 294,195,495,317,205,760 | Main program code. | multiple_levels.py | main | casadina/py_arcade | python | def main():
window = MyGame()
window.setup()
arcade.run() |
def tick(self):
'Determine tick amount.'
t_1 = time.perf_counter()
dt = (t_1 - self.time)
self.time = t_1
self.frame_times.append(dt) | 8,592,838,661,354,698,000 | Determine tick amount. | multiple_levels.py | tick | casadina/py_arcade | python | def tick(self):
t_1 = time.perf_counter()
dt = (t_1 - self.time)
self.time = t_1
self.frame_times.append(dt) |
def get_fps(self) -> float:
'Return FPS as a float.'
total_time = sum(self.frame_times)
if (total_time == 0):
return 0
return (len(self.frame_times) / sum(self.frame_times)) | -3,622,362,377,545,486,300 | Return FPS as a float. | multiple_levels.py | get_fps | casadina/py_arcade | python | def get_fps(self) -> float:
total_time = sum(self.frame_times)
if (total_time == 0):
return 0
return (len(self.frame_times) / sum(self.frame_times)) |
def update(self):
' Move the player'
self.left = max(self.left, 0) | -6,030,875,653,913,213,000 | Move the player | multiple_levels.py | update | casadina/py_arcade | python | def update(self):
' '
self.left = max(self.left, 0) |
def __init__(self):
'Call the parent class and set up the window.'
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
(self.scene, self.player_sprite) = (None, None)
self.physics_engine = None
self.left_pressed = False
self.right_pressed = False
self.camera = None
self.gui_camer... | -1,055,211,858,887,127,900 | Call the parent class and set up the window. | multiple_levels.py | __init__ | casadina/py_arcade | python | def __init__(self):
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
(self.scene, self.player_sprite) = (None, None)
self.physics_engine = None
self.left_pressed = False
self.right_pressed = False
self.camera = None
self.gui_camera = None
self.score = 0
self.lives_lef... |
def setup(self):
'Set-up the game here. Call this function to restart the game.'
self.camera = arcade.Camera(self.width, self.height)
self.gui_camera = arcade.Camera(self.width, self.height)
map_name = f':resources:tiled_maps/map2_level_{self.level}.json'
layer_options = {LAYER_NAME_PLATFORMS: {'use... | 4,101,371,736,262,876,700 | Set-up the game here. Call this function to restart the game. | multiple_levels.py | setup | casadina/py_arcade | python | def setup(self):
self.camera = arcade.Camera(self.width, self.height)
self.gui_camera = arcade.Camera(self.width, self.height)
map_name = f':resources:tiled_maps/map2_level_{self.level}.json'
layer_options = {LAYER_NAME_PLATFORMS: {'use_spatial_hash': True}, LAYER_NAME_COINS: {'use_spatial_hash': T... |
@property
def current_fps(self) -> float:
'Determine current fps.'
return self.fps.get_fps() | 1,849,623,787,745,285,400 | Determine current fps. | multiple_levels.py | current_fps | casadina/py_arcade | python | @property
def current_fps(self) -> float:
return self.fps.get_fps() |
@property
def coins_left(self) -> int:
'Determine coins remaining.'
return len(self.scene['Coins']) | -1,729,096,299,829,627,600 | Determine coins remaining. | multiple_levels.py | coins_left | casadina/py_arcade | python | @property
def coins_left(self) -> int:
return len(self.scene['Coins']) |
@staticmethod
def gui_label(text: str, var: any, x: int, y: int):
"\n Simplify arcade.draw_text.\n\n Keyword arguments:\n text -- This is the label.\n var -- This is the variable value.\n x -- This is the percent point of the screen's x x that it will start at.\n y -- This ... | 1,918,866,859,303,684,400 | Simplify arcade.draw_text.
Keyword arguments:
text -- This is the label.
var -- This is the variable value.
x -- This is the percent point of the screen's x x that it will start at.
y -- This is the percent point of the screen's y it will start at. | multiple_levels.py | gui_label | casadina/py_arcade | python | @staticmethod
def gui_label(text: str, var: any, x: int, y: int):
"\n Simplify arcade.draw_text.\n\n Keyword arguments:\n text -- This is the label.\n var -- This is the variable value.\n x -- This is the percent point of the screen's x x that it will start at.\n y -- This ... |
def display_gui_info(self):
'Display GUI information.'
arcade.draw_rectangle_filled(center_x=(SCREEN_WIDTH / 14), center_y=(SCREEN_HEIGHT - (SCREEN_HEIGHT / 10)), width=(SCREEN_WIDTH / 7), height=(SCREEN_HEIGHT / 4), color=arcade.color.IRRESISTIBLE)
self.gui_label('Score', self.score, 0, 95)
self.gui_la... | -7,317,001,881,754,198,000 | Display GUI information. | multiple_levels.py | display_gui_info | casadina/py_arcade | python | def display_gui_info(self):
arcade.draw_rectangle_filled(center_x=(SCREEN_WIDTH / 14), center_y=(SCREEN_HEIGHT - (SCREEN_HEIGHT / 10)), width=(SCREEN_WIDTH / 7), height=(SCREEN_HEIGHT / 4), color=arcade.color.IRRESISTIBLE)
self.gui_label('Score', self.score, 0, 95)
self.gui_label('Coins Left', self.coi... |
def on_draw(self):
'Render the screen.'
arcade.start_render()
self.camera.use()
self.scene.draw()
self.gui_camera.use()
self.display_gui_info()
self.fps.tick() | 4,505,006,218,272,286,700 | Render the screen. | multiple_levels.py | on_draw | casadina/py_arcade | python | def on_draw(self):
arcade.start_render()
self.camera.use()
self.scene.draw()
self.gui_camera.use()
self.display_gui_info()
self.fps.tick() |
def on_key_press(self, button: int, modifiers: int):
'Called whenever a key is pressed.'
if ((button in self.up) and self.physics_engine.can_jump()):
self.player_sprite.change_y = PLAYER_JUMP_SPEED
arcade.play_sound(self.jump_sound)
elif (button in self.left):
self.left_pressed = Tru... | 531,593,586,049,197,250 | Called whenever a key is pressed. | multiple_levels.py | on_key_press | casadina/py_arcade | python | def on_key_press(self, button: int, modifiers: int):
if ((button in self.up) and self.physics_engine.can_jump()):
self.player_sprite.change_y = PLAYER_JUMP_SPEED
arcade.play_sound(self.jump_sound)
elif (button in self.left):
self.left_pressed = True
elif (button in self.right):
... |
def on_key_release(self, button: int, modifiers: int):
'Called when the user releases a key.'
if (button in self.left):
self.left_pressed = False
elif (button in self.right):
self.right_pressed = False | -5,128,810,662,760,468,000 | Called when the user releases a key. | multiple_levels.py | on_key_release | casadina/py_arcade | python | def on_key_release(self, button: int, modifiers: int):
if (button in self.left):
self.left_pressed = False
elif (button in self.right):
self.right_pressed = False |
def update_player_velocity(self):
'Update velocity based on key state.'
if (self.left_pressed and (not self.right_pressed)):
self.player_sprite.change_x = (- PLAYER_MOVEMENT_SPEED)
elif (self.right_pressed and (not self.left_pressed)):
self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
... | -6,462,452,232,308,232,000 | Update velocity based on key state. | multiple_levels.py | update_player_velocity | casadina/py_arcade | python | def update_player_velocity(self):
if (self.left_pressed and (not self.right_pressed)):
self.player_sprite.change_x = (- PLAYER_MOVEMENT_SPEED)
elif (self.right_pressed and (not self.left_pressed)):
self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
else:
self.player_sprite.chan... |
def center_camera_to_player(self):
'Ensure the camera is centered on the player.'
screen_center_x = (self.player_sprite.center_x - (self.camera.viewport_width / 2))
screen_center_y = (self.player_sprite.center_y - (self.camera.viewport_height / 2))
if (screen_center_x < 0):
screen_center_x = 0
... | -1,353,567,521,603,266,800 | Ensure the camera is centered on the player. | multiple_levels.py | center_camera_to_player | casadina/py_arcade | python | def center_camera_to_player(self):
screen_center_x = (self.player_sprite.center_x - (self.camera.viewport_width / 2))
screen_center_y = (self.player_sprite.center_y - (self.camera.viewport_height / 2))
if (screen_center_x < 0):
screen_center_x = 0
if (screen_center_y < 0):
screen_ce... |
def player_coin_collision(self):
'\n Detects player collision with coins, then removes the coin sprite.\n This will play a sound and add 1 to the score.\n '
coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.scene['Coins'])
for coin in coin_hit_list:
c... | -4,846,683,211,798,819,000 | Detects player collision with coins, then removes the coin sprite.
This will play a sound and add 1 to the score. | multiple_levels.py | player_coin_collision | casadina/py_arcade | python | def player_coin_collision(self):
'\n Detects player collision with coins, then removes the coin sprite.\n This will play a sound and add 1 to the score.\n '
coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.scene['Coins'])
for coin in coin_hit_list:
c... |
def reset_player(self):
"Reset's player to start position."
self.player_sprite.center_x = PLAYER_START_X
self.player_sprite.center_y = PLAYER_START_Y | -6,883,142,112,036,425,000 | Reset's player to start position. | multiple_levels.py | reset_player | casadina/py_arcade | python | def reset_player(self):
self.player_sprite.center_x = PLAYER_START_X
self.player_sprite.center_y = PLAYER_START_Y |
def stop_player(self):
'Stop player movement.'
self.player_sprite.change_x = 0
self.player_sprite.change_y = 0 | -764,573,933,544,241,300 | Stop player movement. | multiple_levels.py | stop_player | casadina/py_arcade | python | def stop_player(self):
self.player_sprite.change_x = 0
self.player_sprite.change_y = 0 |
def game_over(self):
'Sets game over and resets position.'
self.stop_player()
self.reset_player()
self.lives_left -= 1
arcade.play_sound(self.game_over_sound) | 6,663,112,794,571,538,000 | Sets game over and resets position. | multiple_levels.py | game_over | casadina/py_arcade | python | def game_over(self):
self.stop_player()
self.reset_player()
self.lives_left -= 1
arcade.play_sound(self.game_over_sound) |
def fell_off_map(self):
'Detect if the player fell off the map and then reset position if so.'
if (self.player_sprite.center_y < (- 100)):
self.game_over() | -8,257,541,033,313,706,000 | Detect if the player fell off the map and then reset position if so. | multiple_levels.py | fell_off_map | casadina/py_arcade | python | def fell_off_map(self):
if (self.player_sprite.center_y < (- 100)):
self.game_over() |
def touched_dont_touch(self):
"Detect collision on Don't Touch layer. Reset player if collision."
if arcade.check_for_collision_with_list(self.player_sprite, self.scene[LAYER_NAME_DONT_TOUCH]):
self.game_over() | -3,392,554,248,256,127,500 | Detect collision on Don't Touch layer. Reset player if collision. | multiple_levels.py | touched_dont_touch | casadina/py_arcade | python | def touched_dont_touch(self):
if arcade.check_for_collision_with_list(self.player_sprite, self.scene[LAYER_NAME_DONT_TOUCH]):
self.game_over() |
def at_end_of_level(self):
'Checks if player at end of level, and if so, load the next level.'
if (self.player_sprite.center_x >= self.end_of_map):
self.level += 1
self.setup() | -3,506,122,557,746,076,700 | Checks if player at end of level, and if so, load the next level. | multiple_levels.py | at_end_of_level | casadina/py_arcade | python | def at_end_of_level(self):
if (self.player_sprite.center_x >= self.end_of_map):
self.level += 1
self.setup() |
def on_update(self, delta_time: float):
'Movement and game logic.'
self.timer += delta_time
self.update_player_velocity()
self.player_sprite.update()
self.physics_engine.update()
self.player_coin_collision()
self.fell_off_map()
self.touched_dont_touch()
self.at_end_of_level()
sel... | 3,231,113,912,894,307,300 | Movement and game logic. | multiple_levels.py | on_update | casadina/py_arcade | python | def on_update(self, delta_time: float):
self.timer += delta_time
self.update_player_velocity()
self.player_sprite.update()
self.physics_engine.update()
self.player_coin_collision()
self.fell_off_map()
self.touched_dont_touch()
self.at_end_of_level()
self.center_camera_to_player(... |
def default_stream_factory(total_content_length, filename, content_type, content_length=None):
'The stream factory that is used per default.'
if (total_content_length > (1024 * 500)):
return TemporaryFile('wb+')
return StringIO() | 3,775,995,986,324,513,000 | The stream factory that is used per default. | werkzeug/formparser.py | default_stream_factory | Chitrank-Dixit/werkzeug | python | def default_stream_factory(total_content_length, filename, content_type, content_length=None):
if (total_content_length > (1024 * 500)):
return TemporaryFile('wb+')
return StringIO() |
def parse_form_data(environ, stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True):
'Parse the form data in the environ and return it as tuple in the form\n ``(stream, form, files)``. You should only call this method if the\n transp... | 1,399,098,653,220,583,700 | Parse the form data in the environ and return it as tuple in the form
``(stream, form, files)``. You should only call this method if the
transport method is `POST`, `PUT`, or `PATCH`.
If the mimetype of the data transmitted is `multipart/form-data` the
files multidict will be filled with `FileStorage` objects. If th... | werkzeug/formparser.py | parse_form_data | Chitrank-Dixit/werkzeug | python | def parse_form_data(environ, stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True):
'Parse the form data in the environ and return it as tuple in the form\n ``(stream, form, files)``. You should only call this method if the\n transp... |
def exhaust_stream(f):
'Helper decorator for methods that exhausts the stream on return.'
def wrapper(self, stream, *args, **kwargs):
try:
return f(self, stream, *args, **kwargs)
finally:
stream.exhaust()
return update_wrapper(wrapper, f) | 2,898,723,767,904,656,000 | Helper decorator for methods that exhausts the stream on return. | werkzeug/formparser.py | exhaust_stream | Chitrank-Dixit/werkzeug | python | def exhaust_stream(f):
def wrapper(self, stream, *args, **kwargs):
try:
return f(self, stream, *args, **kwargs)
finally:
stream.exhaust()
return update_wrapper(wrapper, f) |
def is_valid_multipart_boundary(boundary):
'Checks if the string given is a valid multipart boundary.'
return (_multipart_boundary_re.match(boundary) is not None) | -8,237,246,297,276,212,000 | Checks if the string given is a valid multipart boundary. | werkzeug/formparser.py | is_valid_multipart_boundary | Chitrank-Dixit/werkzeug | python | def is_valid_multipart_boundary(boundary):
return (_multipart_boundary_re.match(boundary) is not None) |
def _line_parse(line):
'Removes line ending characters and returns a tuple (`stripped_line`,\n `is_terminated`).\n '
if (line[(- 2):] == '\r\n'):
return (line[:(- 2)], True)
elif (line[(- 1):] in '\r\n'):
return (line[:(- 1)], True)
return (line, False) | 2,266,841,580,460,052,500 | Removes line ending characters and returns a tuple (`stripped_line`,
`is_terminated`). | werkzeug/formparser.py | _line_parse | Chitrank-Dixit/werkzeug | python | def _line_parse(line):
'Removes line ending characters and returns a tuple (`stripped_line`,\n `is_terminated`).\n '
if (line[(- 2):] == '\r\n'):
return (line[:(- 2)], True)
elif (line[(- 1):] in '\r\n'):
return (line[:(- 1)], True)
return (line, False) |
def parse_multipart_headers(iterable):
'Parses multipart headers from an iterable that yields lines (including\n the trailing newline symbol). The iterable has to be newline terminated.\n\n The iterable will stop at the line where the headers ended so it can be\n further consumed.\n\n :param iterable: ... | -2,176,537,027,926,288,600 | Parses multipart headers from an iterable that yields lines (including
the trailing newline symbol). The iterable has to be newline terminated.
The iterable will stop at the line where the headers ended so it can be
further consumed.
:param iterable: iterable of strings that are newline terminated | werkzeug/formparser.py | parse_multipart_headers | Chitrank-Dixit/werkzeug | python | def parse_multipart_headers(iterable):
'Parses multipart headers from an iterable that yields lines (including\n the trailing newline symbol). The iterable has to be newline terminated.\n\n The iterable will stop at the line where the headers ended so it can be\n further consumed.\n\n :param iterable: ... |
def parse_from_environ(self, environ):
'Parses the information from the environment as form data.\n\n :param environ: the WSGI environment to be used for parsing.\n :return: A tuple in the form ``(stream, form, files)``.\n '
content_type = environ.get('CONTENT_TYPE', '')
(mimetype, opti... | -5,458,521,010,198,014,000 | Parses the information from the environment as form data.
:param environ: the WSGI environment to be used for parsing.
:return: A tuple in the form ``(stream, form, files)``. | werkzeug/formparser.py | parse_from_environ | Chitrank-Dixit/werkzeug | python | def parse_from_environ(self, environ):
'Parses the information from the environment as form data.\n\n :param environ: the WSGI environment to be used for parsing.\n :return: A tuple in the form ``(stream, form, files)``.\n '
content_type = environ.get('CONTENT_TYPE', )
(mimetype, option... |
def parse(self, stream, mimetype, content_length, options=None):
'Parses the information from the given stream, mimetype,\n content length and mimetype parameters.\n\n :param stream: an input stream\n :param mimetype: the mimetype of the data\n :param content_length: the content length o... | 5,671,949,490,822,148,000 | Parses the information from the given stream, mimetype,
content length and mimetype parameters.
:param stream: an input stream
:param mimetype: the mimetype of the data
:param content_length: the content length of the incoming data
:param options: optional mimetype parameters (used for
the multipart bo... | werkzeug/formparser.py | parse | Chitrank-Dixit/werkzeug | python | def parse(self, stream, mimetype, content_length, options=None):
'Parses the information from the given stream, mimetype,\n content length and mimetype parameters.\n\n :param stream: an input stream\n :param mimetype: the mimetype of the data\n :param content_length: the content length o... |
def _fix_ie_filename(self, filename):
'Internet Explorer 6 transmits the full file name if a file is\n uploaded. This function strips the full path if it thinks the\n filename is Windows-like absolute.\n '
if ((filename[1:3] == ':\\') or (filename[:2] == '\\\\')):
return filename.s... | 4,052,912,053,183,255,600 | Internet Explorer 6 transmits the full file name if a file is
uploaded. This function strips the full path if it thinks the
filename is Windows-like absolute. | werkzeug/formparser.py | _fix_ie_filename | Chitrank-Dixit/werkzeug | python | def _fix_ie_filename(self, filename):
'Internet Explorer 6 transmits the full file name if a file is\n uploaded. This function strips the full path if it thinks the\n filename is Windows-like absolute.\n '
if ((filename[1:3] == ':\\') or (filename[:2] == '\\\\')):
return filename.s... |
def _find_terminator(self, iterator):
'The terminator might have some additional newlines before it.\n There is at least one application that sends additional newlines\n before headers (the python setuptools package).\n '
for line in iterator:
if (not line):
break
... | 2,901,900,155,092,777,000 | The terminator might have some additional newlines before it.
There is at least one application that sends additional newlines
before headers (the python setuptools package). | werkzeug/formparser.py | _find_terminator | Chitrank-Dixit/werkzeug | python | def _find_terminator(self, iterator):
'The terminator might have some additional newlines before it.\n There is at least one application that sends additional newlines\n before headers (the python setuptools package).\n '
for line in iterator:
if (not line):
break
... |
def parse_lines(self, file, boundary, content_length):
"Generate parts of\n ``('begin_form', (headers, name))``\n ``('begin_file', (headers, name, filename))``\n ``('cont', bytestring)``\n ``('end', None)``\n\n Always obeys the grammar\n parts = ( begin_form cont* end |\n ... | -1,307,323,556,561,785,000 | Generate parts of
``('begin_form', (headers, name))``
``('begin_file', (headers, name, filename))``
``('cont', bytestring)``
``('end', None)``
Always obeys the grammar
parts = ( begin_form cont* end |
begin_file cont* end )* | werkzeug/formparser.py | parse_lines | Chitrank-Dixit/werkzeug | python | def parse_lines(self, file, boundary, content_length):
"Generate parts of\n ``('begin_form', (headers, name))``\n ``('begin_file', (headers, name, filename))``\n ``('cont', bytestring)``\n ``('end', None)``\n\n Always obeys the grammar\n parts = ( begin_form cont* end |\n ... |
def parse_parts(self, file, boundary, content_length):
"Generate `('file', (name, val))` and `('form', (name\n ,val))` parts.\n "
in_memory = 0
for (ellt, ell) in self.parse_lines(file, boundary, content_length):
if (ellt == _begin_file):
(headers, name, filename) = ell
... | -1,497,096,617,322,765,800 | Generate `('file', (name, val))` and `('form', (name
,val))` parts. | werkzeug/formparser.py | parse_parts | Chitrank-Dixit/werkzeug | python | def parse_parts(self, file, boundary, content_length):
"Generate `('file', (name, val))` and `('form', (name\n ,val))` parts.\n "
in_memory = 0
for (ellt, ell) in self.parse_lines(file, boundary, content_length):
if (ellt == _begin_file):
(headers, name, filename) = ell
... |
def createMatrices(file, word2Idx, maxSentenceLen=100):
'Creates matrices for the events and sentence for the given file'
labels = []
positionMatrix1 = []
positionMatrix2 = []
tokenMatrix = []
for line in open(file):
splits = line.strip().split('\t')
label = splits[0]
pos... | -3,162,865,911,030,710,300 | Creates matrices for the events and sentence for the given file | 2017-07_Seminar/Session 3 - Relation CNN/code/preprocess.py | createMatrices | BhuvaneshwaranK/deeplearning4nlp-tutorial | python | def createMatrices(file, word2Idx, maxSentenceLen=100):
labels = []
positionMatrix1 = []
positionMatrix2 = []
tokenMatrix = []
for line in open(file):
splits = line.strip().split('\t')
label = splits[0]
pos1 = splits[1]
pos2 = splits[2]
sentence = splits[... |
def getWordIdx(token, word2Idx):
'Returns from the word2Idex table the word index for a given token'
if (token in word2Idx):
return word2Idx[token]
elif (token.lower() in word2Idx):
return word2Idx[token.lower()]
return word2Idx['UNKNOWN_TOKEN'] | -500,736,905,236,166,900 | Returns from the word2Idex table the word index for a given token | 2017-07_Seminar/Session 3 - Relation CNN/code/preprocess.py | getWordIdx | BhuvaneshwaranK/deeplearning4nlp-tutorial | python | def getWordIdx(token, word2Idx):
if (token in word2Idx):
return word2Idx[token]
elif (token.lower() in word2Idx):
return word2Idx[token.lower()]
return word2Idx['UNKNOWN_TOKEN'] |
def _handle_mark_groups_arg_for_clustering(mark_groups, clustering):
"Handles the mark_groups=... keyword argument in plotting methods of\n clusterings.\n\n This is an internal method, you shouldn't need to mess around with it.\n Its purpose is to handle the extended semantics of the mark_groups=...\n k... | -5,505,528,020,700,937,000 | Handles the mark_groups=... keyword argument in plotting methods of
clusterings.
This is an internal method, you shouldn't need to mess around with it.
Its purpose is to handle the extended semantics of the mark_groups=...
keyword argument in the C{__plot__} method of L{VertexClustering} and
L{VertexCover} instances, ... | igraph/clustering.py | _handle_mark_groups_arg_for_clustering | tuandnvn/ecat_learning | python | def _handle_mark_groups_arg_for_clustering(mark_groups, clustering):
"Handles the mark_groups=... keyword argument in plotting methods of\n clusterings.\n\n This is an internal method, you shouldn't need to mess around with it.\n Its purpose is to handle the extended semantics of the mark_groups=...\n k... |
def _prepare_community_comparison(comm1, comm2, remove_none=False):
'Auxiliary method that takes two community structures either as\n membership lists or instances of L{Clustering}, and returns a\n tuple whose two elements are membership lists.\n\n This is used by L{compare_communities} and L{split_join_di... | -1,930,164,210,523,227,600 | Auxiliary method that takes two community structures either as
membership lists or instances of L{Clustering}, and returns a
tuple whose two elements are membership lists.
This is used by L{compare_communities} and L{split_join_distance}.
@param comm1: the first community structure as a membership list or
as a L{Cl... | igraph/clustering.py | _prepare_community_comparison | tuandnvn/ecat_learning | python | def _prepare_community_comparison(comm1, comm2, remove_none=False):
'Auxiliary method that takes two community structures either as\n membership lists or instances of L{Clustering}, and returns a\n tuple whose two elements are membership lists.\n\n This is used by L{compare_communities} and L{split_join_di... |
def compare_communities(comm1, comm2, method='vi', remove_none=False):
'Compares two community structures using various distance measures.\n\n @param comm1: the first community structure as a membership list or\n as a L{Clustering} object.\n @param comm2: the second community structure as a membership li... | 6,305,604,480,575,149,000 | Compares two community structures using various distance measures.
@param comm1: the first community structure as a membership list or
as a L{Clustering} object.
@param comm2: the second community structure as a membership list or
as a L{Clustering} object.
@param method: the measure to use. C{"vi"} or C{"meila"} ... | igraph/clustering.py | compare_communities | tuandnvn/ecat_learning | python | def compare_communities(comm1, comm2, method='vi', remove_none=False):
'Compares two community structures using various distance measures.\n\n @param comm1: the first community structure as a membership list or\n as a L{Clustering} object.\n @param comm2: the second community structure as a membership li... |
def split_join_distance(comm1, comm2, remove_none=False):
'Calculates the split-join distance between two community structures.\n\n The split-join distance is a distance measure defined on the space of\n partitions of a given set. It is the sum of the projection distance of\n one partition from the other a... | -4,521,227,686,832,673,300 | Calculates the split-join distance between two community structures.
The split-join distance is a distance measure defined on the space of
partitions of a given set. It is the sum of the projection distance of
one partition from the other and vice versa, where the projection
number of A from B is if calculated as foll... | igraph/clustering.py | split_join_distance | tuandnvn/ecat_learning | python | def split_join_distance(comm1, comm2, remove_none=False):
'Calculates the split-join distance between two community structures.\n\n The split-join distance is a distance measure defined on the space of\n partitions of a given set. It is the sum of the projection distance of\n one partition from the other a... |
def __init__(self, membership, params=None):
"Constructor.\n\n @param membership: the membership list -- that is, the cluster\n index in which each element of the set belongs to.\n @param params: additional parameters to be stored in this\n object's dictionary."
self._membership ... | -3,012,367,874,068,840,000 | Constructor.
@param membership: the membership list -- that is, the cluster
index in which each element of the set belongs to.
@param params: additional parameters to be stored in this
object's dictionary. | igraph/clustering.py | __init__ | tuandnvn/ecat_learning | python | def __init__(self, membership, params=None):
"Constructor.\n\n @param membership: the membership list -- that is, the cluster\n index in which each element of the set belongs to.\n @param params: additional parameters to be stored in this\n object's dictionary."
self._membership ... |
def __getitem__(self, idx):
'Returns the members of the specified cluster.\n\n @param idx: the index of the cluster\n @return: the members of the specified cluster as a list\n @raise IndexError: if the index is out of bounds'
if ((idx < 0) or (idx >= self._len)):
raise IndexError('c... | 3,332,638,273,974,701,600 | Returns the members of the specified cluster.
@param idx: the index of the cluster
@return: the members of the specified cluster as a list
@raise IndexError: if the index is out of bounds | igraph/clustering.py | __getitem__ | tuandnvn/ecat_learning | python | def __getitem__(self, idx):
'Returns the members of the specified cluster.\n\n @param idx: the index of the cluster\n @return: the members of the specified cluster as a list\n @raise IndexError: if the index is out of bounds'
if ((idx < 0) or (idx >= self._len)):
raise IndexError('c... |
def __iter__(self):
'Iterates over the clusters in this clustering.\n\n This method will return a generator that generates the clusters\n one by one.'
clusters = [[] for _ in xrange(self._len)]
for (idx, cluster) in enumerate(self._membership):
clusters[cluster].append(idx)
return ... | 7,846,816,968,255,388,000 | Iterates over the clusters in this clustering.
This method will return a generator that generates the clusters
one by one. | igraph/clustering.py | __iter__ | tuandnvn/ecat_learning | python | def __iter__(self):
'Iterates over the clusters in this clustering.\n\n This method will return a generator that generates the clusters\n one by one.'
clusters = [[] for _ in xrange(self._len)]
for (idx, cluster) in enumerate(self._membership):
clusters[cluster].append(idx)
return ... |
def __len__(self):
'Returns the number of clusters.\n\n @return: the number of clusters\n '
return self._len | -5,451,640,488,408,298 | Returns the number of clusters.
@return: the number of clusters | igraph/clustering.py | __len__ | tuandnvn/ecat_learning | python | def __len__(self):
'Returns the number of clusters.\n\n @return: the number of clusters\n '
return self._len |
def as_cover(self):
'Returns a L{Cover} that contains the same clusters as this clustering.'
return Cover(self._graph, self) | 8,436,789,138,042,786,000 | Returns a L{Cover} that contains the same clusters as this clustering. | igraph/clustering.py | as_cover | tuandnvn/ecat_learning | python | def as_cover(self):
return Cover(self._graph, self) |
def compare_to(self, other, *args, **kwds):
'Compares this clustering to another one using some similarity or\n distance metric.\n\n This is a convenience method that simply calls L{compare_communities}\n with the two clusterings as arguments. Any extra positional or keyword\n argument i... | -242,300,988,132,617,400 | Compares this clustering to another one using some similarity or
distance metric.
This is a convenience method that simply calls L{compare_communities}
with the two clusterings as arguments. Any extra positional or keyword
argument is also forwarded to L{compare_communities}. | igraph/clustering.py | compare_to | tuandnvn/ecat_learning | python | def compare_to(self, other, *args, **kwds):
'Compares this clustering to another one using some similarity or\n distance metric.\n\n This is a convenience method that simply calls L{compare_communities}\n with the two clusterings as arguments. Any extra positional or keyword\n argument i... |
@property
def membership(self):
'Returns the membership vector.'
return self._membership[:] | 6,664,867,578,842,224,000 | Returns the membership vector. | igraph/clustering.py | membership | tuandnvn/ecat_learning | python | @property
def membership(self):
return self._membership[:] |
@property
def n(self):
'Returns the number of elements covered by this clustering.'
return len(self._membership) | 6,145,121,453,949,917,000 | Returns the number of elements covered by this clustering. | igraph/clustering.py | n | tuandnvn/ecat_learning | python | @property
def n(self):
return len(self._membership) |
def size(self, idx):
'Returns the size of a given cluster.\n\n @param idx: the cluster in which we are interested.\n '
return len(self[idx]) | -2,611,264,052,909,075,500 | Returns the size of a given cluster.
@param idx: the cluster in which we are interested. | igraph/clustering.py | size | tuandnvn/ecat_learning | python | def size(self, idx):
'Returns the size of a given cluster.\n\n @param idx: the cluster in which we are interested.\n '
return len(self[idx]) |
def sizes(self, *args):
'Returns the size of given clusters.\n\n The indices are given as positional arguments. If there are no\n positional arguments, the function will return the sizes of all clusters.\n '
counts = ([0] * len(self))
for x in self._membership:
counts[x] += 1
... | 2,385,789,323,031,367,700 | Returns the size of given clusters.
The indices are given as positional arguments. If there are no
positional arguments, the function will return the sizes of all clusters. | igraph/clustering.py | sizes | tuandnvn/ecat_learning | python | def sizes(self, *args):
'Returns the size of given clusters.\n\n The indices are given as positional arguments. If there are no\n positional arguments, the function will return the sizes of all clusters.\n '
counts = ([0] * len(self))
for x in self._membership:
counts[x] += 1
... |
def size_histogram(self, bin_width=1):
'Returns the histogram of cluster sizes.\n\n @param bin_width: the bin width of the histogram\n @return: a L{Histogram} object\n '
return Histogram(bin_width, self.sizes()) | -2,461,763,455,575,568,000 | Returns the histogram of cluster sizes.
@param bin_width: the bin width of the histogram
@return: a L{Histogram} object | igraph/clustering.py | size_histogram | tuandnvn/ecat_learning | python | def size_histogram(self, bin_width=1):
'Returns the histogram of cluster sizes.\n\n @param bin_width: the bin width of the histogram\n @return: a L{Histogram} object\n '
return Histogram(bin_width, self.sizes()) |
def summary(self, verbosity=0, width=None):
'Returns the summary of the clustering.\n\n The summary includes the number of items and clusters, and also the\n list of members for each of the clusters if the verbosity is nonzero.\n\n @param verbosity: determines whether the cluster members should... | -4,108,578,556,226,028,500 | Returns the summary of the clustering.
The summary includes the number of items and clusters, and also the
list of members for each of the clusters if the verbosity is nonzero.
@param verbosity: determines whether the cluster members should be
printed. Zero verbosity prints the number of items and clusters only.
@r... | igraph/clustering.py | summary | tuandnvn/ecat_learning | python | def summary(self, verbosity=0, width=None):
'Returns the summary of the clustering.\n\n The summary includes the number of items and clusters, and also the\n list of members for each of the clusters if the verbosity is nonzero.\n\n @param verbosity: determines whether the cluster members should... |
def _formatted_cluster_iterator(self):
'Iterates over the clusters and formats them into a string to be\n presented in the summary.'
for cluster in self:
(yield ', '.join((str(member) for member in cluster))) | 810,895,616,325,758,500 | Iterates over the clusters and formats them into a string to be
presented in the summary. | igraph/clustering.py | _formatted_cluster_iterator | tuandnvn/ecat_learning | python | def _formatted_cluster_iterator(self):
'Iterates over the clusters and formats them into a string to be\n presented in the summary.'
for cluster in self:
(yield ', '.join((str(member) for member in cluster))) |
def __init__(self, graph, membership=None, modularity=None, params=None, modularity_params=None):
'Creates a clustering object for a given graph.\n\n @param graph: the graph that will be associated to the clustering\n @param membership: the membership list. The length of the list must\n be eq... | 1,624,140,130,461,915,000 | Creates a clustering object for a given graph.
@param graph: the graph that will be associated to the clustering
@param membership: the membership list. The length of the list must
be equal to the number of vertices in the graph. If C{None}, every
vertex is assumed to belong to the same cluster.
@param modularity:... | igraph/clustering.py | __init__ | tuandnvn/ecat_learning | python | def __init__(self, graph, membership=None, modularity=None, params=None, modularity_params=None):
'Creates a clustering object for a given graph.\n\n @param graph: the graph that will be associated to the clustering\n @param membership: the membership list. The length of the list must\n be eq... |
@classmethod
def FromAttribute(cls, graph, attribute, intervals=None, params=None):
'Creates a vertex clustering based on the value of a vertex attribute.\n\n Vertices having the same attribute will correspond to the same cluster.\n\n @param graph: the graph on which we are working\n @param att... | -3,112,355,477,865,406,000 | Creates a vertex clustering based on the value of a vertex attribute.
Vertices having the same attribute will correspond to the same cluster.
@param graph: the graph on which we are working
@param attribute: name of the attribute on which the clustering
is based.
@param intervals: for numeric attributes, you can ... | igraph/clustering.py | FromAttribute | tuandnvn/ecat_learning | python | @classmethod
def FromAttribute(cls, graph, attribute, intervals=None, params=None):
'Creates a vertex clustering based on the value of a vertex attribute.\n\n Vertices having the same attribute will correspond to the same cluster.\n\n @param graph: the graph on which we are working\n @param att... |
def as_cover(self):
'Returns a L{VertexCover} that contains the same clusters as this\n clustering.'
return VertexCover(self._graph, self) | 6,069,732,515,534,388,000 | Returns a L{VertexCover} that contains the same clusters as this
clustering. | igraph/clustering.py | as_cover | tuandnvn/ecat_learning | python | def as_cover(self):
'Returns a L{VertexCover} that contains the same clusters as this\n clustering.'
return VertexCover(self._graph, self) |
def cluster_graph(self, combine_vertices=None, combine_edges=None):
'Returns a graph where each cluster is contracted into a single\n vertex.\n\n In the resulting graph, vertex M{i} represents cluster M{i} in this\n clustering. Vertex M{i} and M{j} will be connected if there was\n at lea... | -5,948,843,330,100,500,000 | Returns a graph where each cluster is contracted into a single
vertex.
In the resulting graph, vertex M{i} represents cluster M{i} in this
clustering. Vertex M{i} and M{j} will be connected if there was
at least one connected vertex pair M{(a, b)} in the original graph such
that vertex M{a} was in cluster M{i} and ver... | igraph/clustering.py | cluster_graph | tuandnvn/ecat_learning | python | def cluster_graph(self, combine_vertices=None, combine_edges=None):
'Returns a graph where each cluster is contracted into a single\n vertex.\n\n In the resulting graph, vertex M{i} represents cluster M{i} in this\n clustering. Vertex M{i} and M{j} will be connected if there was\n at lea... |
def crossing(self):
'Returns a boolean vector where element M{i} is C{True} iff edge\n M{i} lies between clusters, C{False} otherwise.'
membership = self.membership
return [(membership[v1] != membership[v2]) for (v1, v2) in self.graph.get_edgelist()] | 1,045,636,364,997,920,800 | Returns a boolean vector where element M{i} is C{True} iff edge
M{i} lies between clusters, C{False} otherwise. | igraph/clustering.py | crossing | tuandnvn/ecat_learning | python | def crossing(self):
'Returns a boolean vector where element M{i} is C{True} iff edge\n M{i} lies between clusters, C{False} otherwise.'
membership = self.membership
return [(membership[v1] != membership[v2]) for (v1, v2) in self.graph.get_edgelist()] |
@property
def modularity(self):
'Returns the modularity score'
if self._modularity_dirty:
return self._recalculate_modularity_safe()
return self._modularity | -3,664,254,341,804,715,000 | Returns the modularity score | igraph/clustering.py | modularity | tuandnvn/ecat_learning | python | @property
def modularity(self):
if self._modularity_dirty:
return self._recalculate_modularity_safe()
return self._modularity |
@property
def graph(self):
'Returns the graph belonging to this object'
return self._graph | -6,013,293,917,706,169,000 | Returns the graph belonging to this object | igraph/clustering.py | graph | tuandnvn/ecat_learning | python | @property
def graph(self):
return self._graph |
def recalculate_modularity(self):
'Recalculates the stored modularity value.\n\n This method must be called before querying the modularity score of the\n clustering through the class member C{modularity} or C{q} if the\n graph has been modified (edges have been added or removed) since the\n ... | 1,722,162,046,988,135,400 | Recalculates the stored modularity value.
This method must be called before querying the modularity score of the
clustering through the class member C{modularity} or C{q} if the
graph has been modified (edges have been added or removed) since the
creation of the L{VertexClustering} object.
@return: the new modularity... | igraph/clustering.py | recalculate_modularity | tuandnvn/ecat_learning | python | def recalculate_modularity(self):
'Recalculates the stored modularity value.\n\n This method must be called before querying the modularity score of the\n clustering through the class member C{modularity} or C{q} if the\n graph has been modified (edges have been added or removed) since the\n ... |
def _recalculate_modularity_safe(self):
'Recalculates the stored modularity value and swallows all exceptions\n raised by the modularity function (if any).\n\n @return: the new modularity score or C{None} if the modularity function\n could not be calculated.\n '
try:
return s... | -3,958,502,414,622,825,500 | Recalculates the stored modularity value and swallows all exceptions
raised by the modularity function (if any).
@return: the new modularity score or C{None} if the modularity function
could not be calculated. | igraph/clustering.py | _recalculate_modularity_safe | tuandnvn/ecat_learning | python | def _recalculate_modularity_safe(self):
'Recalculates the stored modularity value and swallows all exceptions\n raised by the modularity function (if any).\n\n @return: the new modularity score or C{None} if the modularity function\n could not be calculated.\n '
try:
return s... |
def subgraph(self, idx):
"Get the subgraph belonging to a given cluster.\n\n @param idx: the cluster index\n @return: a copy of the subgraph\n @precondition: the vertex set of the graph hasn't been modified since\n the moment the clustering was constructed.\n "
return self._... | 4,888,167,428,059,338,000 | Get the subgraph belonging to a given cluster.
@param idx: the cluster index
@return: a copy of the subgraph
@precondition: the vertex set of the graph hasn't been modified since
the moment the clustering was constructed. | igraph/clustering.py | subgraph | tuandnvn/ecat_learning | python | def subgraph(self, idx):
"Get the subgraph belonging to a given cluster.\n\n @param idx: the cluster index\n @return: a copy of the subgraph\n @precondition: the vertex set of the graph hasn't been modified since\n the moment the clustering was constructed.\n "
return self._... |
def subgraphs(self):
"Gets all the subgraphs belonging to each of the clusters.\n\n @return: a list containing copies of the subgraphs\n @precondition: the vertex set of the graph hasn't been modified since\n the moment the clustering was constructed.\n "
return [self._graph.subgra... | 397,228,615,663,400,600 | Gets all the subgraphs belonging to each of the clusters.
@return: a list containing copies of the subgraphs
@precondition: the vertex set of the graph hasn't been modified since
the moment the clustering was constructed. | igraph/clustering.py | subgraphs | tuandnvn/ecat_learning | python | def subgraphs(self):
"Gets all the subgraphs belonging to each of the clusters.\n\n @return: a list containing copies of the subgraphs\n @precondition: the vertex set of the graph hasn't been modified since\n the moment the clustering was constructed.\n "
return [self._graph.subgra... |
def giant(self):
"Returns the giant community of the clustered graph.\n\n The giant component a community for which no larger community exists.\n @note: there can be multiple giant communities, this method will return\n the copy of an arbitrary one if there are multiple giant communities.\n\n... | 5,153,737,018,873,520,000 | Returns the giant community of the clustered graph.
The giant component a community for which no larger community exists.
@note: there can be multiple giant communities, this method will return
the copy of an arbitrary one if there are multiple giant communities.
@return: a copy of the giant community.
@preconditio... | igraph/clustering.py | giant | tuandnvn/ecat_learning | python | def giant(self):
"Returns the giant community of the clustered graph.\n\n The giant component a community for which no larger community exists.\n @note: there can be multiple giant communities, this method will return\n the copy of an arbitrary one if there are multiple giant communities.\n\n... |
def __plot__(self, context, bbox, palette, *args, **kwds):
'Plots the clustering to the given Cairo context in the given\n bounding box.\n\n This is done by calling L{Graph.__plot__()} with the same arguments, but\n coloring the graph vertices according to the current clustering (unless\n ... | 626,841,932,283,767,200 | Plots the clustering to the given Cairo context in the given
bounding box.
This is done by calling L{Graph.__plot__()} with the same arguments, but
coloring the graph vertices according to the current clustering (unless
overridden by the C{vertex_color} argument explicitly).
This method understands all the positional... | igraph/clustering.py | __plot__ | tuandnvn/ecat_learning | python | def __plot__(self, context, bbox, palette, *args, **kwds):
'Plots the clustering to the given Cairo context in the given\n bounding box.\n\n This is done by calling L{Graph.__plot__()} with the same arguments, but\n coloring the graph vertices according to the current clustering (unless\n ... |
def _formatted_cluster_iterator(self):
'Iterates over the clusters and formats them into a string to be\n presented in the summary.'
if self._graph.is_named():
names = self._graph.vs['name']
for cluster in self:
(yield ', '.join((str(names[member]) for member in cluster)))
... | 6,838,424,363,819,696,000 | Iterates over the clusters and formats them into a string to be
presented in the summary. | igraph/clustering.py | _formatted_cluster_iterator | tuandnvn/ecat_learning | python | def _formatted_cluster_iterator(self):
'Iterates over the clusters and formats them into a string to be\n presented in the summary.'
if self._graph.is_named():
names = self._graph.vs['name']
for cluster in self:
(yield ', '.join((str(names[member]) for member in cluster)))
... |
def __init__(self, merges):
'Creates a hierarchical clustering.\n\n @param merges: the merge history either in matrix or tuple format'
self._merges = [tuple(pair) for pair in merges]
self._nmerges = len(self._merges)
if self._nmerges:
self._nitems = ((max(self._merges[(- 1)]) - self._nmer... | 3,493,641,226,356,949,500 | Creates a hierarchical clustering.
@param merges: the merge history either in matrix or tuple format | igraph/clustering.py | __init__ | tuandnvn/ecat_learning | python | def __init__(self, merges):
'Creates a hierarchical clustering.\n\n @param merges: the merge history either in matrix or tuple format'
self._merges = [tuple(pair) for pair in merges]
self._nmerges = len(self._merges)
if self._nmerges:
self._nitems = ((max(self._merges[(- 1)]) - self._nmer... |
@staticmethod
def _convert_matrix_to_tuple_repr(merges, n=None):
'Converts the matrix representation of a clustering to a tuple\n representation.\n\n @param merges: the matrix representation of the clustering\n @return: the tuple representation of the clustering\n '
if (n is None):
... | 2,679,342,802,674,906,600 | Converts the matrix representation of a clustering to a tuple
representation.
@param merges: the matrix representation of the clustering
@return: the tuple representation of the clustering | igraph/clustering.py | _convert_matrix_to_tuple_repr | tuandnvn/ecat_learning | python | @staticmethod
def _convert_matrix_to_tuple_repr(merges, n=None):
'Converts the matrix representation of a clustering to a tuple\n representation.\n\n @param merges: the matrix representation of the clustering\n @return: the tuple representation of the clustering\n '
if (n is None):
... |
def _traverse_inorder(self):
'Conducts an inorder traversal of the merge tree.\n\n The inorder traversal returns the nodes on the last level in the order\n they should be drawn so that no edges cross each other.\n\n @return: the result of the inorder traversal in a list.'
result = []
se... | -8,123,607,309,487,676,000 | Conducts an inorder traversal of the merge tree.
The inorder traversal returns the nodes on the last level in the order
they should be drawn so that no edges cross each other.
@return: the result of the inorder traversal in a list. | igraph/clustering.py | _traverse_inorder | tuandnvn/ecat_learning | python | def _traverse_inorder(self):
'Conducts an inorder traversal of the merge tree.\n\n The inorder traversal returns the nodes on the last level in the order\n they should be drawn so that no edges cross each other.\n\n @return: the result of the inorder traversal in a list.'
result = []
se... |
def format(self, format='newick'):
'Formats the dendrogram in a foreign format.\n\n Currently only the Newick format is supported.\n\n Example:\n\n >>> d = Dendrogram([(2, 3), (0, 1), (4, 5)])\n >>> d.format()\n \'((2,3)4,(0,1)5)6;\'\n >>> d.names = list("AB... | 285,569,044,303,103,330 | Formats the dendrogram in a foreign format.
Currently only the Newick format is supported.
Example:
>>> d = Dendrogram([(2, 3), (0, 1), (4, 5)])
>>> d.format()
'((2,3)4,(0,1)5)6;'
>>> d.names = list("ABCDEFG")
>>> d.format()
'((C,D)E,(A,B)F)G;' | igraph/clustering.py | format | tuandnvn/ecat_learning | python | def format(self, format='newick'):
'Formats the dendrogram in a foreign format.\n\n Currently only the Newick format is supported.\n\n Example:\n\n >>> d = Dendrogram([(2, 3), (0, 1), (4, 5)])\n >>> d.format()\n \'((2,3)4,(0,1)5)6;\'\n >>> d.names = list("AB... |
def summary(self, verbosity=0, max_leaf_count=40):
'Returns the summary of the dendrogram.\n\n The summary includes the number of leafs and branches, and also an\n ASCII art representation of the dendrogram unless it is too large.\n\n @param verbosity: determines whether the ASCII representatio... | 2,575,065,336,735,225,000 | Returns the summary of the dendrogram.
The summary includes the number of leafs and branches, and also an
ASCII art representation of the dendrogram unless it is too large.
@param verbosity: determines whether the ASCII representation of the
dendrogram should be printed. Zero verbosity prints only the number
of l... | igraph/clustering.py | summary | tuandnvn/ecat_learning | python | def summary(self, verbosity=0, max_leaf_count=40):
'Returns the summary of the dendrogram.\n\n The summary includes the number of leafs and branches, and also an\n ASCII art representation of the dendrogram unless it is too large.\n\n @param verbosity: determines whether the ASCII representatio... |
def _item_box_size(self, context, horiz, idx):
'Calculates the amount of space needed for drawing an\n individual vertex at the bottom of the dendrogram.'
if ((self._names is None) or (self._names[idx] is None)):
(x_bearing, _, _, height, x_advance, _) = context.text_extents('')
else:
... | -6,424,601,739,130,504,000 | Calculates the amount of space needed for drawing an
individual vertex at the bottom of the dendrogram. | igraph/clustering.py | _item_box_size | tuandnvn/ecat_learning | python | def _item_box_size(self, context, horiz, idx):
'Calculates the amount of space needed for drawing an\n individual vertex at the bottom of the dendrogram.'
if ((self._names is None) or (self._names[idx] is None)):
(x_bearing, _, _, height, x_advance, _) = context.text_extents()
else:
(... |
def _plot_item(self, context, horiz, idx, x, y):
'Plots a dendrogram item to the given Cairo context\n\n @param context: the Cairo context we are plotting on\n @param horiz: whether the dendrogram is horizontally oriented\n @param idx: the index of the item\n @param x: the X position of ... | -9,049,214,614,630,723,000 | Plots a dendrogram item to the given Cairo context
@param context: the Cairo context we are plotting on
@param horiz: whether the dendrogram is horizontally oriented
@param idx: the index of the item
@param x: the X position of the item
@param y: the Y position of the item | igraph/clustering.py | _plot_item | tuandnvn/ecat_learning | python | def _plot_item(self, context, horiz, idx, x, y):
'Plots a dendrogram item to the given Cairo context\n\n @param context: the Cairo context we are plotting on\n @param horiz: whether the dendrogram is horizontally oriented\n @param idx: the index of the item\n @param x: the X position of ... |
def __plot__(self, context, bbox, palette, *args, **kwds):
'Draws the dendrogram on the given Cairo context\n\n Supported keyword arguments are:\n\n - C{orientation}: the orientation of the dendrogram. Must be one of\n the following values: C{left-right}, C{bottom-top}, C{right-left}\n ... | -2,328,309,552,966,241,300 | Draws the dendrogram on the given Cairo context
Supported keyword arguments are:
- C{orientation}: the orientation of the dendrogram. Must be one of
the following values: C{left-right}, C{bottom-top}, C{right-left}
or C{top-bottom}. Individual elements are always placed at the
former edge and merges are... | igraph/clustering.py | __plot__ | tuandnvn/ecat_learning | python | def __plot__(self, context, bbox, palette, *args, **kwds):
'Draws the dendrogram on the given Cairo context\n\n Supported keyword arguments are:\n\n - C{orientation}: the orientation of the dendrogram. Must be one of\n the following values: C{left-right}, C{bottom-top}, C{right-left}\n ... |
@property
def merges(self):
'Returns the performed merges in matrix format'
return deepcopy(self._merges) | -5,628,481,384,864,011,000 | Returns the performed merges in matrix format | igraph/clustering.py | merges | tuandnvn/ecat_learning | python | @property
def merges(self):
return deepcopy(self._merges) |
@property
def names(self):
'Returns the names of the nodes in the dendrogram'
return self._names | -9,158,098,303,931,814,000 | Returns the names of the nodes in the dendrogram | igraph/clustering.py | names | tuandnvn/ecat_learning | python | @property
def names(self):
return self._names |
@names.setter
def names(self, items):
'Sets the names of the nodes in the dendrogram'
if (items is None):
self._names = None
return
items = list(items)
if (len(items) < self._nitems):
raise ValueError(('must specify at least %d names' % self._nitems))
n = (self._nitems + self... | 7,007,590,815,281,501,000 | Sets the names of the nodes in the dendrogram | igraph/clustering.py | names | tuandnvn/ecat_learning | python | @names.setter
def names(self, items):
if (items is None):
self._names = None
return
items = list(items)
if (len(items) < self._nitems):
raise ValueError(('must specify at least %d names' % self._nitems))
n = (self._nitems + self._nmerges)
self._names = items[:n]
if (... |
def __init__(self, graph, merges, optimal_count=None, params=None, modularity_params=None):
'Creates a dendrogram object for a given graph.\n\n @param graph: the graph that will be associated to the clustering\n @param merges: the merges performed given in matrix form.\n @param optimal_count: t... | -3,161,577,109,791,939,600 | Creates a dendrogram object for a given graph.
@param graph: the graph that will be associated to the clustering
@param merges: the merges performed given in matrix form.
@param optimal_count: the optimal number of clusters where the
dendrogram should be cut. This is a hint usually provided by the
clustering algor... | igraph/clustering.py | __init__ | tuandnvn/ecat_learning | python | def __init__(self, graph, merges, optimal_count=None, params=None, modularity_params=None):
'Creates a dendrogram object for a given graph.\n\n @param graph: the graph that will be associated to the clustering\n @param merges: the merges performed given in matrix form.\n @param optimal_count: t... |
def as_clustering(self, n=None):
'Cuts the dendrogram at the given level and returns a corresponding\n L{VertexClustering} object.\n\n @param n: the desired number of clusters. Merges are replayed from the\n beginning until the membership vector has exactly M{n} distinct elements\n o... | -4,594,129,517,684,349,400 | Cuts the dendrogram at the given level and returns a corresponding
L{VertexClustering} object.
@param n: the desired number of clusters. Merges are replayed from the
beginning until the membership vector has exactly M{n} distinct elements
or until there are no more recorded merges, whichever happens first.
If C{... | igraph/clustering.py | as_clustering | tuandnvn/ecat_learning | python | def as_clustering(self, n=None):
'Cuts the dendrogram at the given level and returns a corresponding\n L{VertexClustering} object.\n\n @param n: the desired number of clusters. Merges are replayed from the\n beginning until the membership vector has exactly M{n} distinct elements\n o... |
@property
def optimal_count(self):
'Returns the optimal number of clusters for this dendrogram.\n\n If an optimal count hint was given at construction time, this\n property simply returns the hint. If such a count was not given,\n this method calculates the optimal number of clusters by maximiz... | 8,939,029,117,350,291,000 | Returns the optimal number of clusters for this dendrogram.
If an optimal count hint was given at construction time, this
property simply returns the hint. If such a count was not given,
this method calculates the optimal number of clusters by maximizing
the modularity along all the possible cuts in the dendrogram. | igraph/clustering.py | optimal_count | tuandnvn/ecat_learning | python | @property
def optimal_count(self):
'Returns the optimal number of clusters for this dendrogram.\n\n If an optimal count hint was given at construction time, this\n property simply returns the hint. If such a count was not given,\n this method calculates the optimal number of clusters by maximiz... |
def __plot__(self, context, bbox, palette, *args, **kwds):
'Draws the vertex dendrogram on the given Cairo context\n\n See L{Dendrogram.__plot__} for the list of supported keyword\n arguments.'
from igraph.drawing.metamagic import AttributeCollectorBase
class VisualVertexBuilder(AttributeColl... | 4,141,242,726,377,235,500 | Draws the vertex dendrogram on the given Cairo context
See L{Dendrogram.__plot__} for the list of supported keyword
arguments. | igraph/clustering.py | __plot__ | tuandnvn/ecat_learning | python | def __plot__(self, context, bbox, palette, *args, **kwds):
'Draws the vertex dendrogram on the given Cairo context\n\n See L{Dendrogram.__plot__} for the list of supported keyword\n arguments.'
from igraph.drawing.metamagic import AttributeCollectorBase
class VisualVertexBuilder(AttributeColl... |
def __init__(self, clusters, n=0):
'Constructs a cover with the given clusters.\n\n @param clusters: the clusters in this cover, as a list or iterable.\n Each cluster is specified by a list or tuple that contains the\n IDs of the items in this cluster. IDs start from zero.\n\n @param... | -5,700,276,278,546,979,000 | Constructs a cover with the given clusters.
@param clusters: the clusters in this cover, as a list or iterable.
Each cluster is specified by a list or tuple that contains the
IDs of the items in this cluster. IDs start from zero.
@param n: the total number of elements in the set that is covered
by this cover. I... | igraph/clustering.py | __init__ | tuandnvn/ecat_learning | python | def __init__(self, clusters, n=0):
'Constructs a cover with the given clusters.\n\n @param clusters: the clusters in this cover, as a list or iterable.\n Each cluster is specified by a list or tuple that contains the\n IDs of the items in this cluster. IDs start from zero.\n\n @param... |
def __getitem__(self, index):
'Returns the cluster with the given index.'
return self._clusters[index] | -9,141,471,715,622,353,000 | Returns the cluster with the given index. | igraph/clustering.py | __getitem__ | tuandnvn/ecat_learning | python | def __getitem__(self, index):
return self._clusters[index] |
def __iter__(self):
'Iterates over the clusters in this cover.'
return iter(self._clusters) | -8,856,924,646,904,825,000 | Iterates over the clusters in this cover. | igraph/clustering.py | __iter__ | tuandnvn/ecat_learning | python | def __iter__(self):
return iter(self._clusters) |
def __len__(self):
'Returns the number of clusters in this cover.'
return len(self._clusters) | 46,158,193,321,388,264 | Returns the number of clusters in this cover. | igraph/clustering.py | __len__ | tuandnvn/ecat_learning | python | def __len__(self):
return len(self._clusters) |
def __str__(self):
'Returns a string representation of the cover.'
return self.summary(verbosity=1, width=78) | 5,406,004,662,587,039,000 | Returns a string representation of the cover. | igraph/clustering.py | __str__ | tuandnvn/ecat_learning | python | def __str__(self):
return self.summary(verbosity=1, width=78) |
@property
def membership(self):
'Returns the membership vector of this cover.\n\n The membership vector of a cover covering I{n} elements is a list of\n length I{n}, where element I{i} contains the cluster indices of the\n I{i}th item.\n '
result = [[] for _ in xrange(self._n)]
f... | -7,302,082,719,879,950,000 | Returns the membership vector of this cover.
The membership vector of a cover covering I{n} elements is a list of
length I{n}, where element I{i} contains the cluster indices of the
I{i}th item. | igraph/clustering.py | membership | tuandnvn/ecat_learning | python | @property
def membership(self):
'Returns the membership vector of this cover.\n\n The membership vector of a cover covering I{n} elements is a list of\n length I{n}, where element I{i} contains the cluster indices of the\n I{i}th item.\n '
result = [[] for _ in xrange(self._n)]
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.