body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
f82932794e54730de2d35bbae25c64a28cda887cc25dc5b1c5cd681531e3a6ae | @strawpollset.command(name='dupcheck', pass_context=True, no_pm=True)
async def dupcheck(self, ctx, option):
'Toggles between Normal, Permissive, or Disabled values\n Normal - Multiple choice is available\n Permissive - Multiple choice is available\n Disabled - Multiple choice is not available'
option = option.lower()
options = {'normal', 'permissive', 'disabled'}
if (self.settings['dupcheck'] == option):
(await self.bot.say('Choose another option.'))
elif (option not in options):
(await self.bot.say('Choose an actual option.'))
else:
self.settings['dupcheck'] = option
if (option == 'normal'):
(await self.bot.say('Dupcheck will now be enforced for duplicate votes.'))
elif (option == 'permissive'):
(await self.bot.say('Dupcheck will now be more lenient on duplicate vote handling.'))
else:
(await self.bot.say('Dupcheck is now disabled.'))
dataIO.save_json(self.fp, self.settings) | Toggles between Normal, Permissive, or Disabled values
Normal - Multiple choice is available
Permissive - Multiple choice is available
Disabled - Multiple choice is not available | strawpoll/strawpoll.py | dupcheck | crossedfall/ax-cogs | 0 | python | @strawpollset.command(name='dupcheck', pass_context=True, no_pm=True)
async def dupcheck(self, ctx, option):
'Toggles between Normal, Permissive, or Disabled values\n Normal - Multiple choice is available\n Permissive - Multiple choice is available\n Disabled - Multiple choice is not available'
option = option.lower()
options = {'normal', 'permissive', 'disabled'}
if (self.settings['dupcheck'] == option):
(await self.bot.say('Choose another option.'))
elif (option not in options):
(await self.bot.say('Choose an actual option.'))
else:
self.settings['dupcheck'] = option
if (option == 'normal'):
(await self.bot.say('Dupcheck will now be enforced for duplicate votes.'))
elif (option == 'permissive'):
(await self.bot.say('Dupcheck will now be more lenient on duplicate vote handling.'))
else:
(await self.bot.say('Dupcheck is now disabled.'))
dataIO.save_json(self.fp, self.settings) | @strawpollset.command(name='dupcheck', pass_context=True, no_pm=True)
async def dupcheck(self, ctx, option):
'Toggles between Normal, Permissive, or Disabled values\n Normal - Multiple choice is available\n Permissive - Multiple choice is available\n Disabled - Multiple choice is not available'
option = option.lower()
options = {'normal', 'permissive', 'disabled'}
if (self.settings['dupcheck'] == option):
(await self.bot.say('Choose another option.'))
elif (option not in options):
(await self.bot.say('Choose an actual option.'))
else:
self.settings['dupcheck'] = option
if (option == 'normal'):
(await self.bot.say('Dupcheck will now be enforced for duplicate votes.'))
elif (option == 'permissive'):
(await self.bot.say('Dupcheck will now be more lenient on duplicate vote handling.'))
else:
(await self.bot.say('Dupcheck is now disabled.'))
dataIO.save_json(self.fp, self.settings)<|docstring|>Toggles between Normal, Permissive, or Disabled values
Normal - Multiple choice is available
Permissive - Multiple choice is available
Disabled - Multiple choice is not available<|endoftext|> |
0e68f67446f595425b39cb25958e8583a7e1937d2b5382b02f3c743b2f13af4c | @strawpollset.command(name='captcha', pass_context=True, no_pm=True)
async def captcha(self, ctx):
'Toggles between True and False values\n True - Voters will have to do a captcha\n False - Voters will not have to a captcha'
if (self.settings['captcha'] == 'true'):
self.settings['captcha'] = 'false'
(await self.bot.say('Voters will no longer have to do a captcha to vote.'))
else:
self.settings['captcha'] = 'true'
(await self.bot.say('Voters will have to do a captcha to vote.'))
dataIO.save_json(self.fp, self.settings) | Toggles between True and False values
True - Voters will have to do a captcha
False - Voters will not have to a captcha | strawpoll/strawpoll.py | captcha | crossedfall/ax-cogs | 0 | python | @strawpollset.command(name='captcha', pass_context=True, no_pm=True)
async def captcha(self, ctx):
'Toggles between True and False values\n True - Voters will have to do a captcha\n False - Voters will not have to a captcha'
if (self.settings['captcha'] == 'true'):
self.settings['captcha'] = 'false'
(await self.bot.say('Voters will no longer have to do a captcha to vote.'))
else:
self.settings['captcha'] = 'true'
(await self.bot.say('Voters will have to do a captcha to vote.'))
dataIO.save_json(self.fp, self.settings) | @strawpollset.command(name='captcha', pass_context=True, no_pm=True)
async def captcha(self, ctx):
'Toggles between True and False values\n True - Voters will have to do a captcha\n False - Voters will not have to a captcha'
if (self.settings['captcha'] == 'true'):
self.settings['captcha'] = 'false'
(await self.bot.say('Voters will no longer have to do a captcha to vote.'))
else:
self.settings['captcha'] = 'true'
(await self.bot.say('Voters will have to do a captcha to vote.'))
dataIO.save_json(self.fp, self.settings)<|docstring|>Toggles between True and False values
True - Voters will have to do a captcha
False - Voters will not have to a captcha<|endoftext|> |
8b89dd3478512e81bed9e02c2a3d60806e7389ec1533e836d684562272251e0a | def _applicable_weight_based_methods(weight, qs):
'Return weight based shipping methods that are applicable for the total weight.'
qs = qs.weight_based()
min_weight_matched = Q(minimum_order_weight__lte=weight)
no_weight_limit = Q(maximum_order_weight__isnull=True)
max_weight_matched = Q(maximum_order_weight__gte=weight)
return qs.filter((min_weight_matched & (no_weight_limit | max_weight_matched))) | Return weight based shipping methods that are applicable for the total weight. | saleor/shipping/models.py | _applicable_weight_based_methods | rainerioagbayani/golftee-core | 4 | python | def _applicable_weight_based_methods(weight, qs):
qs = qs.weight_based()
min_weight_matched = Q(minimum_order_weight__lte=weight)
no_weight_limit = Q(maximum_order_weight__isnull=True)
max_weight_matched = Q(maximum_order_weight__gte=weight)
return qs.filter((min_weight_matched & (no_weight_limit | max_weight_matched))) | def _applicable_weight_based_methods(weight, qs):
qs = qs.weight_based()
min_weight_matched = Q(minimum_order_weight__lte=weight)
no_weight_limit = Q(maximum_order_weight__isnull=True)
max_weight_matched = Q(maximum_order_weight__gte=weight)
return qs.filter((min_weight_matched & (no_weight_limit | max_weight_matched)))<|docstring|>Return weight based shipping methods that are applicable for the total weight.<|endoftext|> |
b331913b7f58891797db5a2f1485ecf39df3a91724d61c251a776d0fe0ca5ec4 | def _applicable_price_based_methods(price: Money, qs):
'Return price based shipping methods that are applicable for the given total.'
qs = qs.price_based()
min_price_matched = Q(minimum_order_price_amount__lte=price.amount)
no_price_limit = Q(maximum_order_price_amount__isnull=True)
max_price_matched = Q(maximum_order_price_amount__gte=price.amount)
return qs.filter((min_price_matched & (no_price_limit | max_price_matched))) | Return price based shipping methods that are applicable for the given total. | saleor/shipping/models.py | _applicable_price_based_methods | rainerioagbayani/golftee-core | 4 | python | def _applicable_price_based_methods(price: Money, qs):
qs = qs.price_based()
min_price_matched = Q(minimum_order_price_amount__lte=price.amount)
no_price_limit = Q(maximum_order_price_amount__isnull=True)
max_price_matched = Q(maximum_order_price_amount__gte=price.amount)
return qs.filter((min_price_matched & (no_price_limit | max_price_matched))) | def _applicable_price_based_methods(price: Money, qs):
qs = qs.price_based()
min_price_matched = Q(minimum_order_price_amount__lte=price.amount)
no_price_limit = Q(maximum_order_price_amount__isnull=True)
max_price_matched = Q(maximum_order_price_amount__gte=price.amount)
return qs.filter((min_price_matched & (no_price_limit | max_price_matched)))<|docstring|>Return price based shipping methods that are applicable for the given total.<|endoftext|> |
26b2b5f959cd3c652b8cda5c3ac4634ea3d4d8cd6601159424f893f60d4663b1 | def applicable_shipping_methods(self, price: Money, weight, country_code):
'Return the ShippingMethods that can be used on an order with shipment.\n\n It is based on the given country code, and by shipping methods that are\n applicable to the given price & weight total.\n '
qs = self.filter(shipping_zone__countries__contains=country_code, currency=price.currency)
qs = qs.prefetch_related('shipping_zone').order_by('price_amount')
price_based_methods = _applicable_price_based_methods(price, qs)
weight_based_methods = _applicable_weight_based_methods(weight, qs)
return (price_based_methods | weight_based_methods) | Return the ShippingMethods that can be used on an order with shipment.
It is based on the given country code, and by shipping methods that are
applicable to the given price & weight total. | saleor/shipping/models.py | applicable_shipping_methods | rainerioagbayani/golftee-core | 4 | python | def applicable_shipping_methods(self, price: Money, weight, country_code):
'Return the ShippingMethods that can be used on an order with shipment.\n\n It is based on the given country code, and by shipping methods that are\n applicable to the given price & weight total.\n '
qs = self.filter(shipping_zone__countries__contains=country_code, currency=price.currency)
qs = qs.prefetch_related('shipping_zone').order_by('price_amount')
price_based_methods = _applicable_price_based_methods(price, qs)
weight_based_methods = _applicable_weight_based_methods(weight, qs)
return (price_based_methods | weight_based_methods) | def applicable_shipping_methods(self, price: Money, weight, country_code):
'Return the ShippingMethods that can be used on an order with shipment.\n\n It is based on the given country code, and by shipping methods that are\n applicable to the given price & weight total.\n '
qs = self.filter(shipping_zone__countries__contains=country_code, currency=price.currency)
qs = qs.prefetch_related('shipping_zone').order_by('price_amount')
price_based_methods = _applicable_price_based_methods(price, qs)
weight_based_methods = _applicable_weight_based_methods(weight, qs)
return (price_based_methods | weight_based_methods)<|docstring|>Return the ShippingMethods that can be used on an order with shipment.
It is based on the given country code, and by shipping methods that are
applicable to the given price & weight total.<|endoftext|> |
49312ae923af3ba54327a593063ada67ea0b2539648a23cc6743d6d688e4b8f5 | def find_all_baseinverses(board: Board) -> Set[Baseinverse]:
'find_all_baseinverses takes a Board and returns a set of Baseinverses for it.\n\n It makes no assumptions about whose turn it is or who is the controller of the Zugzwang.\n\n Args:\n board (Board): a Board instance.\n\n Returns:\n baseinverses (set<Baseinverse>): a set of Baseinverses for board.\n '
baseinverses = set()
playable_squares = board.playable_squares()
for playable1 in playable_squares:
for playable2 in playable_squares:
if ((playable1 != playable2) and connection.is_possible(a=playable1, b=playable2)):
baseinverses.add(Baseinverse(playable1=playable1, playable2=playable2))
return baseinverses | find_all_baseinverses takes a Board and returns a set of Baseinverses for it.
It makes no assumptions about whose turn it is or who is the controller of the Zugzwang.
Args:
board (Board): a Board instance.
Returns:
baseinverses (set<Baseinverse>): a set of Baseinverses for board. | connect_four/evaluation/victor/rules/baseinverse.py | find_all_baseinverses | rpachauri/connect4 | 0 | python | def find_all_baseinverses(board: Board) -> Set[Baseinverse]:
'find_all_baseinverses takes a Board and returns a set of Baseinverses for it.\n\n It makes no assumptions about whose turn it is or who is the controller of the Zugzwang.\n\n Args:\n board (Board): a Board instance.\n\n Returns:\n baseinverses (set<Baseinverse>): a set of Baseinverses for board.\n '
baseinverses = set()
playable_squares = board.playable_squares()
for playable1 in playable_squares:
for playable2 in playable_squares:
if ((playable1 != playable2) and connection.is_possible(a=playable1, b=playable2)):
baseinverses.add(Baseinverse(playable1=playable1, playable2=playable2))
return baseinverses | def find_all_baseinverses(board: Board) -> Set[Baseinverse]:
'find_all_baseinverses takes a Board and returns a set of Baseinverses for it.\n\n It makes no assumptions about whose turn it is or who is the controller of the Zugzwang.\n\n Args:\n board (Board): a Board instance.\n\n Returns:\n baseinverses (set<Baseinverse>): a set of Baseinverses for board.\n '
baseinverses = set()
playable_squares = board.playable_squares()
for playable1 in playable_squares:
for playable2 in playable_squares:
if ((playable1 != playable2) and connection.is_possible(a=playable1, b=playable2)):
baseinverses.add(Baseinverse(playable1=playable1, playable2=playable2))
return baseinverses<|docstring|>find_all_baseinverses takes a Board and returns a set of Baseinverses for it.
It makes no assumptions about whose turn it is or who is the controller of the Zugzwang.
Args:
board (Board): a Board instance.
Returns:
baseinverses (set<Baseinverse>): a set of Baseinverses for board.<|endoftext|> |
2452634e7c3b4624bbad9994556d7c06fb86aeda65b39e320e461a8cd87b74ed | def find_problems_solved(self, groups_by_square_by_player: List[List[List[Set[Group]]]]) -> Set[Group]:
'Finds all Problems this Rule solves.\n\n Args:\n groups_by_square_by_player (List[List[List[Set[Group]]]]): a 3D array of a Set of Groups.\n 1. The first dimension is the player.\n 2. The second dimension is the row.\n 3. The third dimension is the col.\n\n For a given player and a given (row, col),\n you can retrieve all Groups that player can win from that Square with:\n set_of_possible_winning_groups_at_player_row_col = groups_by_square_by_player[player][row][col]\n\n Returns:\n problems_solved (Set[Group]): All Problems in square_to_groups this Rule solves.\n '
warnings.warn('find_problems_solved is deprecated. use solves() instead', DeprecationWarning)
white_problems_solved = self.find_problems_solved_for_player(groups_by_square=groups_by_square_by_player[0])
black_problems_solved = self.find_problems_solved_for_player(groups_by_square=groups_by_square_by_player[1])
return white_problems_solved.union(black_problems_solved) | Finds all Problems this Rule solves.
Args:
groups_by_square_by_player (List[List[List[Set[Group]]]]): a 3D array of a Set of Groups.
1. The first dimension is the player.
2. The second dimension is the row.
3. The third dimension is the col.
For a given player and a given (row, col),
you can retrieve all Groups that player can win from that Square with:
set_of_possible_winning_groups_at_player_row_col = groups_by_square_by_player[player][row][col]
Returns:
problems_solved (Set[Group]): All Problems in square_to_groups this Rule solves. | connect_four/evaluation/victor/rules/baseinverse.py | find_problems_solved | rpachauri/connect4 | 0 | python | def find_problems_solved(self, groups_by_square_by_player: List[List[List[Set[Group]]]]) -> Set[Group]:
'Finds all Problems this Rule solves.\n\n Args:\n groups_by_square_by_player (List[List[List[Set[Group]]]]): a 3D array of a Set of Groups.\n 1. The first dimension is the player.\n 2. The second dimension is the row.\n 3. The third dimension is the col.\n\n For a given player and a given (row, col),\n you can retrieve all Groups that player can win from that Square with:\n set_of_possible_winning_groups_at_player_row_col = groups_by_square_by_player[player][row][col]\n\n Returns:\n problems_solved (Set[Group]): All Problems in square_to_groups this Rule solves.\n '
warnings.warn('find_problems_solved is deprecated. use solves() instead', DeprecationWarning)
white_problems_solved = self.find_problems_solved_for_player(groups_by_square=groups_by_square_by_player[0])
black_problems_solved = self.find_problems_solved_for_player(groups_by_square=groups_by_square_by_player[1])
return white_problems_solved.union(black_problems_solved) | def find_problems_solved(self, groups_by_square_by_player: List[List[List[Set[Group]]]]) -> Set[Group]:
'Finds all Problems this Rule solves.\n\n Args:\n groups_by_square_by_player (List[List[List[Set[Group]]]]): a 3D array of a Set of Groups.\n 1. The first dimension is the player.\n 2. The second dimension is the row.\n 3. The third dimension is the col.\n\n For a given player and a given (row, col),\n you can retrieve all Groups that player can win from that Square with:\n set_of_possible_winning_groups_at_player_row_col = groups_by_square_by_player[player][row][col]\n\n Returns:\n problems_solved (Set[Group]): All Problems in square_to_groups this Rule solves.\n '
warnings.warn('find_problems_solved is deprecated. use solves() instead', DeprecationWarning)
white_problems_solved = self.find_problems_solved_for_player(groups_by_square=groups_by_square_by_player[0])
black_problems_solved = self.find_problems_solved_for_player(groups_by_square=groups_by_square_by_player[1])
return white_problems_solved.union(black_problems_solved)<|docstring|>Finds all Problems this Rule solves.
Args:
groups_by_square_by_player (List[List[List[Set[Group]]]]): a 3D array of a Set of Groups.
1. The first dimension is the player.
2. The second dimension is the row.
3. The third dimension is the col.
For a given player and a given (row, col),
you can retrieve all Groups that player can win from that Square with:
set_of_possible_winning_groups_at_player_row_col = groups_by_square_by_player[player][row][col]
Returns:
problems_solved (Set[Group]): All Problems in square_to_groups this Rule solves.<|endoftext|> |
a344c08d9ceb68632d1605ddc6384334ce35b03fcd888c589c4fa3a33b5df6ce | def __init__(self, board: Board):
'Initializes the BaseinverseManager.\n\n Args:\n board (Board): a Board instance.\n '
self.baseinverses = find_all_baseinverses(board=board) | Initializes the BaseinverseManager.
Args:
board (Board): a Board instance. | connect_four/evaluation/victor/rules/baseinverse.py | __init__ | rpachauri/connect4 | 0 | python | def __init__(self, board: Board):
'Initializes the BaseinverseManager.\n\n Args:\n board (Board): a Board instance.\n '
self.baseinverses = find_all_baseinverses(board=board) | def __init__(self, board: Board):
'Initializes the BaseinverseManager.\n\n Args:\n board (Board): a Board instance.\n '
self.baseinverses = find_all_baseinverses(board=board)<|docstring|>Initializes the BaseinverseManager.
Args:
board (Board): a Board instance.<|endoftext|> |
785916289b0a510d943a5fe3fb63579f746083653f3861ad5a1588d262d359f3 | def move(self, square: Square, playable_squares: Set[Square]) -> (Set[Baseinverse], Set[Baseinverse]):
'Moves the internal state of the BaseinverseManager to after this square has been played.\n\n Args:\n square (Square): the square being played.\n playable_squares (Set[Square]): the set of directly playable squares, including square.\n\n Returns:\n removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.\n added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.\n '
removed_baseinverses = set()
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square, b=other_square)):
baseinverse = Baseinverse(playable1=square, playable2=other_square)
self.baseinverses.remove(baseinverse)
removed_baseinverses.add(baseinverse)
added_baseinverses = set()
if (square.row > 0):
square_above = Square(row=(square.row - 1), col=square.col)
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square_above, b=other_square)):
baseinverse = Baseinverse(playable1=square_above, playable2=other_square)
self.baseinverses.add(baseinverse)
added_baseinverses.add(baseinverse)
return (removed_baseinverses, added_baseinverses) | Moves the internal state of the BaseinverseManager to after this square has been played.
Args:
square (Square): the square being played.
playable_squares (Set[Square]): the set of directly playable squares, including square.
Returns:
removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.
added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added. | connect_four/evaluation/victor/rules/baseinverse.py | move | rpachauri/connect4 | 0 | python | def move(self, square: Square, playable_squares: Set[Square]) -> (Set[Baseinverse], Set[Baseinverse]):
'Moves the internal state of the BaseinverseManager to after this square has been played.\n\n Args:\n square (Square): the square being played.\n playable_squares (Set[Square]): the set of directly playable squares, including square.\n\n Returns:\n removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.\n added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.\n '
removed_baseinverses = set()
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square, b=other_square)):
baseinverse = Baseinverse(playable1=square, playable2=other_square)
self.baseinverses.remove(baseinverse)
removed_baseinverses.add(baseinverse)
added_baseinverses = set()
if (square.row > 0):
square_above = Square(row=(square.row - 1), col=square.col)
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square_above, b=other_square)):
baseinverse = Baseinverse(playable1=square_above, playable2=other_square)
self.baseinverses.add(baseinverse)
added_baseinverses.add(baseinverse)
return (removed_baseinverses, added_baseinverses) | def move(self, square: Square, playable_squares: Set[Square]) -> (Set[Baseinverse], Set[Baseinverse]):
'Moves the internal state of the BaseinverseManager to after this square has been played.\n\n Args:\n square (Square): the square being played.\n playable_squares (Set[Square]): the set of directly playable squares, including square.\n\n Returns:\n removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.\n added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.\n '
removed_baseinverses = set()
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square, b=other_square)):
baseinverse = Baseinverse(playable1=square, playable2=other_square)
self.baseinverses.remove(baseinverse)
removed_baseinverses.add(baseinverse)
added_baseinverses = set()
if (square.row > 0):
square_above = Square(row=(square.row - 1), col=square.col)
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square_above, b=other_square)):
baseinverse = Baseinverse(playable1=square_above, playable2=other_square)
self.baseinverses.add(baseinverse)
added_baseinverses.add(baseinverse)
return (removed_baseinverses, added_baseinverses)<|docstring|>Moves the internal state of the BaseinverseManager to after this square has been played.
Args:
square (Square): the square being played.
playable_squares (Set[Square]): the set of directly playable squares, including square.
Returns:
removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.
added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.<|endoftext|> |
58e57f8f3f4f304c4fc0a9cf106327f18cd10cae0a5876bf082e912444911abd | def undo_move(self, square: Square, playable_squares: Set[Square]) -> (Set[Baseinverse], Set[Baseinverse]):
'Undoes the most recent move, updating the set of Baseinverses.\n\n Args:\n square (Square): the square being undone.\n playable_squares (Set[Square]): the set of directly playable squares, including square.\n\n Returns:\n added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.\n removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.\n '
added_baseinverses = set()
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square, b=other_square)):
baseinverse = Baseinverse(playable1=square, playable2=other_square)
self.baseinverses.add(baseinverse)
added_baseinverses.add(baseinverse)
removed_baseinverses = set()
if (square.row > 0):
square_above = Square(row=(square.row - 1), col=square.col)
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square_above, b=other_square)):
baseinverse = Baseinverse(playable1=square_above, playable2=other_square)
self.baseinverses.remove(baseinverse)
removed_baseinverses.add(baseinverse)
return (added_baseinverses, removed_baseinverses) | Undoes the most recent move, updating the set of Baseinverses.
Args:
square (Square): the square being undone.
playable_squares (Set[Square]): the set of directly playable squares, including square.
Returns:
added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.
removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed. | connect_four/evaluation/victor/rules/baseinverse.py | undo_move | rpachauri/connect4 | 0 | python | def undo_move(self, square: Square, playable_squares: Set[Square]) -> (Set[Baseinverse], Set[Baseinverse]):
'Undoes the most recent move, updating the set of Baseinverses.\n\n Args:\n square (Square): the square being undone.\n playable_squares (Set[Square]): the set of directly playable squares, including square.\n\n Returns:\n added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.\n removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.\n '
added_baseinverses = set()
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square, b=other_square)):
baseinverse = Baseinverse(playable1=square, playable2=other_square)
self.baseinverses.add(baseinverse)
added_baseinverses.add(baseinverse)
removed_baseinverses = set()
if (square.row > 0):
square_above = Square(row=(square.row - 1), col=square.col)
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square_above, b=other_square)):
baseinverse = Baseinverse(playable1=square_above, playable2=other_square)
self.baseinverses.remove(baseinverse)
removed_baseinverses.add(baseinverse)
return (added_baseinverses, removed_baseinverses) | def undo_move(self, square: Square, playable_squares: Set[Square]) -> (Set[Baseinverse], Set[Baseinverse]):
'Undoes the most recent move, updating the set of Baseinverses.\n\n Args:\n square (Square): the square being undone.\n playable_squares (Set[Square]): the set of directly playable squares, including square.\n\n Returns:\n added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.\n removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.\n '
added_baseinverses = set()
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square, b=other_square)):
baseinverse = Baseinverse(playable1=square, playable2=other_square)
self.baseinverses.add(baseinverse)
added_baseinverses.add(baseinverse)
removed_baseinverses = set()
if (square.row > 0):
square_above = Square(row=(square.row - 1), col=square.col)
for other_square in playable_squares:
if ((other_square != square) and connection.is_possible(a=square_above, b=other_square)):
baseinverse = Baseinverse(playable1=square_above, playable2=other_square)
self.baseinverses.remove(baseinverse)
removed_baseinverses.add(baseinverse)
return (added_baseinverses, removed_baseinverses)<|docstring|>Undoes the most recent move, updating the set of Baseinverses.
Args:
square (Square): the square being undone.
playable_squares (Set[Square]): the set of directly playable squares, including square.
Returns:
added_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being added.
removed_baseinverses (Set[Baseinverse]): the set of Baseinverses Claimeven being removed.<|endoftext|> |
ad70b597c7c0d8cc7262e1b25231d7a9057669e3eff3a1912769c3d954dca805 | def get(self, key, d=None):
'Get the document entity given its key.\n\n Args:\n key (str): The key for the document entity.\n d (any, optional): Defaults to None. The default value\n\n Returns:\n any: The data value.\n '
return self.data.get(key, d) | Get the document entity given its key.
Args:
key (str): The key for the document entity.
d (any, optional): Defaults to None. The default value
Returns:
any: The data value. | app/lti_app/core/text_processing/document.py | get | oss6/scriba | 0 | python | def get(self, key, d=None):
'Get the document entity given its key.\n\n Args:\n key (str): The key for the document entity.\n d (any, optional): Defaults to None. The default value\n\n Returns:\n any: The data value.\n '
return self.data.get(key, d) | def get(self, key, d=None):
'Get the document entity given its key.\n\n Args:\n key (str): The key for the document entity.\n d (any, optional): Defaults to None. The default value\n\n Returns:\n any: The data value.\n '
return self.data.get(key, d)<|docstring|>Get the document entity given its key.
Args:
key (str): The key for the document entity.
d (any, optional): Defaults to None. The default value
Returns:
any: The data value.<|endoftext|> |
5864ee4ff66d626b4d0ee4da1b346be83b0ec2ec847425068ea4111108d82d23 | def put(self, key, data):
'Add a key-data mapping to the document.\n\n Args:\n key (str): The key associated with the value.\n data (any): The value.\n '
self.data[key] = data | Add a key-data mapping to the document.
Args:
key (str): The key associated with the value.
data (any): The value. | app/lti_app/core/text_processing/document.py | put | oss6/scriba | 0 | python | def put(self, key, data):
'Add a key-data mapping to the document.\n\n Args:\n key (str): The key associated with the value.\n data (any): The value.\n '
self.data[key] = data | def put(self, key, data):
'Add a key-data mapping to the document.\n\n Args:\n key (str): The key associated with the value.\n data (any): The value.\n '
self.data[key] = data<|docstring|>Add a key-data mapping to the document.
Args:
key (str): The key associated with the value.
data (any): The value.<|endoftext|> |
33f29af45dffd04bf04473fb25b644ea29d288a75bde7add2d7679dfd27c977e | def __init__(self, cid, name='Esp', manufacturer='Espressif', model='Esp32', serial_number='00112233445566', firmware_revision='1.0.0', hardware_revision='1.0.0', product_version='1.0'):
' Constructor ' | Constructor | modules/simul/homekit_.py | __init__ | yansinan/pycameresp | 28 | python | def __init__(self, cid, name='Esp', manufacturer='Espressif', model='Esp32', serial_number='00112233445566', firmware_revision='1.0.0', hardware_revision='1.0.0', product_version='1.0'):
' ' | def __init__(self, cid, name='Esp', manufacturer='Espressif', model='Esp32', serial_number='00112233445566', firmware_revision='1.0.0', hardware_revision='1.0.0', product_version='1.0'):
' '<|docstring|>Constructor<|endoftext|> |
7a4c6c9de352ff6b0abda67e4562a4676a8e59c7c25be7235b6f24c20b8f1761 | def __del__(self):
' Destructor ' | Destructor | modules/simul/homekit_.py | __del__ | yansinan/pycameresp | 28 | python | def __del__(self):
' ' | def __del__(self):
' '<|docstring|>Destructor<|endoftext|> |
5feee0292b0fff3ec14aad95df1d0939360888d2302ef1c13913ea52c1def242 | def deinit(self):
' Deinitialize ' | Deinitialize | modules/simul/homekit_.py | deinit | yansinan/pycameresp | 28 | python | def deinit(self):
' ' | def deinit(self):
' '<|docstring|>Deinitialize<|endoftext|> |
efb3bfaaafd0c331888edf0b5fd46b1de5229d121570278d6ebdd031d521cd8c | def add_server(self, server):
' Add server ' | Add server | modules/simul/homekit_.py | add_server | yansinan/pycameresp | 28 | python | def add_server(self, server):
' ' | def add_server(self, server):
' '<|docstring|>Add server<|endoftext|> |
b8ea5f867554f6b35092bf80556d6965e850332d3b70057a2c96855c55064b4b | def set_identify_callback(self, callback):
' Set identify callback ' | Set identify callback | modules/simul/homekit_.py | set_identify_callback | yansinan/pycameresp | 28 | python | def set_identify_callback(self, callback):
' ' | def set_identify_callback(self, callback):
' '<|docstring|>Set identify callback<|endoftext|> |
63ebd22e1d75ac6fa09e6e5239f85b5936c59e6788f707f7a54fae9da652c2ee | def set_product_data(self, data):
' Set product data ' | Set product data | modules/simul/homekit_.py | set_product_data | yansinan/pycameresp | 28 | python | def set_product_data(self, data):
' ' | def set_product_data(self, data):
' '<|docstring|>Set product data<|endoftext|> |
a197a7e0d44d6baa70e53b98db017ef1019651157b80775c64236e7b44b55a43 | def __init__(self, server_uuid):
' Constructor ' | Constructor | modules/simul/homekit_.py | __init__ | yansinan/pycameresp | 28 | python | def __init__(self, server_uuid):
' ' | def __init__(self, server_uuid):
' '<|docstring|>Constructor<|endoftext|> |
5feee0292b0fff3ec14aad95df1d0939360888d2302ef1c13913ea52c1def242 | def deinit(self):
' Deinitialize ' | Deinitialize | modules/simul/homekit_.py | deinit | yansinan/pycameresp | 28 | python | def deinit(self):
' ' | def deinit(self):
' '<|docstring|>Deinitialize<|endoftext|> |
14e0adcb26f5db18c6df4d5fe5993efe4a2577a51a551f2a54ff8d36b803a9da | def add_charact(self, charact):
' Add characteristic ' | Add characteristic | modules/simul/homekit_.py | add_charact | yansinan/pycameresp | 28 | python | def add_charact(self, charact):
' ' | def add_charact(self, charact):
' '<|docstring|>Add characteristic<|endoftext|> |
dc968c4d692c04a459e674b45ea6624d2ca18f428b3de65620faa766ea152d49 | def __init__(self, uuid, typ, perm, value):
' Constructor ' | Constructor | modules/simul/homekit_.py | __init__ | yansinan/pycameresp | 28 | python | def __init__(self, uuid, typ, perm, value):
' ' | def __init__(self, uuid, typ, perm, value):
' '<|docstring|>Constructor<|endoftext|> |
5feee0292b0fff3ec14aad95df1d0939360888d2302ef1c13913ea52c1def242 | def deinit(self):
' Deinitialize ' | Deinitialize | modules/simul/homekit_.py | deinit | yansinan/pycameresp | 28 | python | def deinit(self):
' ' | def deinit(self):
' '<|docstring|>Deinitialize<|endoftext|> |
3af19239aa5060b88ec3578dd28623b260667857ee94639a0ead5f297b16f17a | def set_unit(self, unit):
' Set unit ' | Set unit | modules/simul/homekit_.py | set_unit | yansinan/pycameresp | 28 | python | def set_unit(self, unit):
' ' | def set_unit(self, unit):
' '<|docstring|>Set unit<|endoftext|> |
1282bc9ca068d95d0e0ed31680263ac4731f55c74d365167abeef6e09f8395b4 | def set_description(self, description):
' Set description ' | Set description | modules/simul/homekit_.py | set_description | yansinan/pycameresp | 28 | python | def set_description(self, description):
' ' | def set_description(self, description):
' '<|docstring|>Set description<|endoftext|> |
25a47c5cece8e45e59102ca1bd0dd16144d0170d18b996692ec881c7798f92ea | def set_constraint(self, mini, maxi):
' Set min and max constraint ' | Set min and max constraint | modules/simul/homekit_.py | set_constraint | yansinan/pycameresp | 28 | python | def set_constraint(self, mini, maxi):
' ' | def set_constraint(self, mini, maxi):
' '<|docstring|>Set min and max constraint<|endoftext|> |
2743762851969b455e791023a14bd0ad7b716a4ff366275c2dad408f7fb19db1 | def set_step(self, step):
' Set step ' | Set step | modules/simul/homekit_.py | set_step | yansinan/pycameresp | 28 | python | def set_step(self, step):
' ' | def set_step(self, step):
' '<|docstring|>Set step<|endoftext|> |
e8f113195e549a31a1e6532be4a99305bdc192f49b3922951b66d371a9ecb19c | def set_value(self, value):
' Set value ' | Set value | modules/simul/homekit_.py | set_value | yansinan/pycameresp | 28 | python | def set_value(self, value):
' ' | def set_value(self, value):
' '<|docstring|>Set value<|endoftext|> |
0f0902f8ef558d96e5165eb0aa6e3f6051b0a0fa87991ccc35bff502d1a112de | def get_value(self):
' Get value ' | Get value | modules/simul/homekit_.py | get_value | yansinan/pycameresp | 28 | python | def get_value(self):
' ' | def get_value(self):
' '<|docstring|>Get value<|endoftext|> |
526d1ec8b96873ceb9843947bd595d197eed01d27f53b4a8b2fa09bee8f50e7e | def set_read_callback(self, callback):
' Set read callback ' | Set read callback | modules/simul/homekit_.py | set_read_callback | yansinan/pycameresp | 28 | python | def set_read_callback(self, callback):
' ' | def set_read_callback(self, callback):
' '<|docstring|>Set read callback<|endoftext|> |
20d3f7656ea0a344919446623d846b07cb0ffbc17ce425735a07e423f6541cd7 | def set_write_callback(self, callback):
' Set write callback ' | Set write callback | modules/simul/homekit_.py | set_write_callback | yansinan/pycameresp | 28 | python | def set_write_callback(self, callback):
' ' | def set_write_callback(self, callback):
' '<|docstring|>Set write callback<|endoftext|> |
d385ca53924f22015d11e005e5cd8fa234dbb88aa11d149e3f9aa8983c7cf624 | @login_required
def Home(request):
'\n If user is authenticated, he can access the page. If he has\n accessible themes, he can see the one where his access is \n granted.\n '
themes = Theme.objects.filter(authorized_user=request.user).order_by('name')
context = {'page_title': 'Themes', 'themes': themes, 'page_title': 'Feuilles de route'}
template = loader.get_template('roadmap/home.html')
return HttpResponse(template.render(context, request)) | If user is authenticated, he can access the page. If he has
accessible themes, he can see the one where his access is
granted. | views.py | Home | j-ollivier/vaste-roadmap | 0 | python | @login_required
def Home(request):
'\n If user is authenticated, he can access the page. If he has\n accessible themes, he can see the one where his access is \n granted.\n '
themes = Theme.objects.filter(authorized_user=request.user).order_by('name')
context = {'page_title': 'Themes', 'themes': themes, 'page_title': 'Feuilles de route'}
template = loader.get_template('roadmap/home.html')
return HttpResponse(template.render(context, request)) | @login_required
def Home(request):
'\n If user is authenticated, he can access the page. If he has\n accessible themes, he can see the one where his access is \n granted.\n '
themes = Theme.objects.filter(authorized_user=request.user).order_by('name')
context = {'page_title': 'Themes', 'themes': themes, 'page_title': 'Feuilles de route'}
template = loader.get_template('roadmap/home.html')
return HttpResponse(template.render(context, request))<|docstring|>If user is authenticated, he can access the page. If he has
accessible themes, he can see the one where his access is
granted.<|endoftext|> |
e8e09ac4227de328204a5452514d30610e9e062fdffa6d96c881503324af6473 | @login_required
def ThemeView(request, theme_uid):
'\n Display the content of the folder linked to the Galery object\n '
theme = Theme.objects.get(pk=theme_uid)
if (request.user in theme.authorized_user.all()):
context = {'theme': theme, 'new_sub_theme_form': NewSubThemeForm(), 'subthemes': SubTheme.objects.filter(theme=theme).order_by('order').select_related(), 'page_title': theme.name}
template = loader.get_template('roadmap/theme_view.html')
return HttpResponse(template.render(context, request))
else:
return HttpResponseRedirect('/nope') | Display the content of the folder linked to the Galery object | views.py | ThemeView | j-ollivier/vaste-roadmap | 0 | python | @login_required
def ThemeView(request, theme_uid):
'\n \n '
theme = Theme.objects.get(pk=theme_uid)
if (request.user in theme.authorized_user.all()):
context = {'theme': theme, 'new_sub_theme_form': NewSubThemeForm(), 'subthemes': SubTheme.objects.filter(theme=theme).order_by('order').select_related(), 'page_title': theme.name}
template = loader.get_template('roadmap/theme_view.html')
return HttpResponse(template.render(context, request))
else:
return HttpResponseRedirect('/nope') | @login_required
def ThemeView(request, theme_uid):
'\n \n '
theme = Theme.objects.get(pk=theme_uid)
if (request.user in theme.authorized_user.all()):
context = {'theme': theme, 'new_sub_theme_form': NewSubThemeForm(), 'subthemes': SubTheme.objects.filter(theme=theme).order_by('order').select_related(), 'page_title': theme.name}
template = loader.get_template('roadmap/theme_view.html')
return HttpResponse(template.render(context, request))
else:
return HttpResponseRedirect('/nope')<|docstring|>Display the content of the folder linked to the Galery object<|endoftext|> |
1275bd272523e07bc50bed9094d458f52eb44060ca70b8003693480c5ece7d7e | @login_required
def AddItem(request, subtheme_uid):
'\n Display the content of the folder linked to the Galery object\n '
subtheme = SubTheme.objects.get(pk=subtheme_uid)
if ((request.method == 'POST') and (request.user in subtheme.theme.authorized_user.all())):
form = NewItemForm(request.POST)
if form.is_valid():
new_item = Item()
new_item.name = form.cleaned_data['name']
new_item.subtheme = subtheme
new_item.is_active = True
new_item.created_date = timezone.now()
theme = subtheme.theme
new_item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.value = str(new_item.name)[0:40]
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Création'
log.theme = theme
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
context = {'subtheme': subtheme, 'new_item_form': NewItemForm(), 'page_title': 'Nouvel item'}
template = loader.get_template('roadmap/add_item.html')
return HttpResponse(template.render(context, request)) | Display the content of the folder linked to the Galery object | views.py | AddItem | j-ollivier/vaste-roadmap | 0 | python | @login_required
def AddItem(request, subtheme_uid):
'\n \n '
subtheme = SubTheme.objects.get(pk=subtheme_uid)
if ((request.method == 'POST') and (request.user in subtheme.theme.authorized_user.all())):
form = NewItemForm(request.POST)
if form.is_valid():
new_item = Item()
new_item.name = form.cleaned_data['name']
new_item.subtheme = subtheme
new_item.is_active = True
new_item.created_date = timezone.now()
theme = subtheme.theme
new_item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.value = str(new_item.name)[0:40]
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Création'
log.theme = theme
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
context = {'subtheme': subtheme, 'new_item_form': NewItemForm(), 'page_title': 'Nouvel item'}
template = loader.get_template('roadmap/add_item.html')
return HttpResponse(template.render(context, request)) | @login_required
def AddItem(request, subtheme_uid):
'\n \n '
subtheme = SubTheme.objects.get(pk=subtheme_uid)
if ((request.method == 'POST') and (request.user in subtheme.theme.authorized_user.all())):
form = NewItemForm(request.POST)
if form.is_valid():
new_item = Item()
new_item.name = form.cleaned_data['name']
new_item.subtheme = subtheme
new_item.is_active = True
new_item.created_date = timezone.now()
theme = subtheme.theme
new_item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.value = str(new_item.name)[0:40]
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Création'
log.theme = theme
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
context = {'subtheme': subtheme, 'new_item_form': NewItemForm(), 'page_title': 'Nouvel item'}
template = loader.get_template('roadmap/add_item.html')
return HttpResponse(template.render(context, request))<|docstring|>Display the content of the folder linked to the Galery object<|endoftext|> |
144e31fd079be38338e5acc83a43b1335607ef2771813f04b89bc2ec454e4bda | @login_required
def AddItemComment(request, item_uid):
'\n Display the content of the folder linked to the Galery object\n '
item = Item.objects.get(pk=item_uid)
subtheme = item.subtheme
if ((request.method == 'POST') and (request.user in subtheme.theme.authorized_user.all())):
form = NewItemCommentForm(request.POST)
if form.is_valid():
new_item = ItemComment()
new_item.name = form.cleaned_data['name']
new_item.item = item
new_item.author = User.objects.get(pk=request.user.id)
new_item.timestamp = timezone.now()
new_item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'commentaire'
log.entity_uid = ItemComment.objects.all().order_by('created_date').last().uid
log.value = str(new_item.name)[0:40]
log.action = 'Création'
log.theme = subtheme.theme
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(item.subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
context = {'item': item, 'new_item_comment_form': NewItemCommentForm(), 'page_title': 'Nouveau commentaire'}
template = loader.get_template('roadmap/add_item_comment.html')
return HttpResponse(template.render(context, request)) | Display the content of the folder linked to the Galery object | views.py | AddItemComment | j-ollivier/vaste-roadmap | 0 | python | @login_required
def AddItemComment(request, item_uid):
'\n \n '
item = Item.objects.get(pk=item_uid)
subtheme = item.subtheme
if ((request.method == 'POST') and (request.user in subtheme.theme.authorized_user.all())):
form = NewItemCommentForm(request.POST)
if form.is_valid():
new_item = ItemComment()
new_item.name = form.cleaned_data['name']
new_item.item = item
new_item.author = User.objects.get(pk=request.user.id)
new_item.timestamp = timezone.now()
new_item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'commentaire'
log.entity_uid = ItemComment.objects.all().order_by('created_date').last().uid
log.value = str(new_item.name)[0:40]
log.action = 'Création'
log.theme = subtheme.theme
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(item.subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
context = {'item': item, 'new_item_comment_form': NewItemCommentForm(), 'page_title': 'Nouveau commentaire'}
template = loader.get_template('roadmap/add_item_comment.html')
return HttpResponse(template.render(context, request)) | @login_required
def AddItemComment(request, item_uid):
'\n \n '
item = Item.objects.get(pk=item_uid)
subtheme = item.subtheme
if ((request.method == 'POST') and (request.user in subtheme.theme.authorized_user.all())):
form = NewItemCommentForm(request.POST)
if form.is_valid():
new_item = ItemComment()
new_item.name = form.cleaned_data['name']
new_item.item = item
new_item.author = User.objects.get(pk=request.user.id)
new_item.timestamp = timezone.now()
new_item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'commentaire'
log.entity_uid = ItemComment.objects.all().order_by('created_date').last().uid
log.value = str(new_item.name)[0:40]
log.action = 'Création'
log.theme = subtheme.theme
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(item.subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
context = {'item': item, 'new_item_comment_form': NewItemCommentForm(), 'page_title': 'Nouveau commentaire'}
template = loader.get_template('roadmap/add_item_comment.html')
return HttpResponse(template.render(context, request))<|docstring|>Display the content of the folder linked to the Galery object<|endoftext|> |
283151f599d17fc910e6e55b25db688dad9bc2b36c1c0b7a4b5416de52d97a6b | @login_required
def AddSubTheme(request, theme_uid):
'\n Display the content of the folder linked to the Galery object\n '
theme = Theme.objects.get(pk=theme_uid)
if ((request.method == 'POST') and (request.user in theme.authorized_user.all())):
form = NewSubThemeForm(request.POST)
if form.is_valid():
new_subtheme = SubTheme()
new_subtheme.name = form.cleaned_data['name']
new_subtheme.order = 0
new_subtheme.author = User.objects.get(pk=request.user.id)
new_subtheme.theme = theme
new_subtheme.timestamp = timezone.now()
new_subtheme.theme = theme
new_subtheme.save()
for subtheme in SubTheme.objects.filter(theme=theme):
subtheme.order += 1
subtheme.save()
log = EventLog()
log.author = request.user
log.entity_type = 'sous-thème'
log.entity_uid = SubTheme.objects.all().order_by('created_date').last().uid
log.action = 'Création'
log.theme = theme
log.value = str(new_subtheme.name)[0:40]
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid)) | Display the content of the folder linked to the Galery object | views.py | AddSubTheme | j-ollivier/vaste-roadmap | 0 | python | @login_required
def AddSubTheme(request, theme_uid):
'\n \n '
theme = Theme.objects.get(pk=theme_uid)
if ((request.method == 'POST') and (request.user in theme.authorized_user.all())):
form = NewSubThemeForm(request.POST)
if form.is_valid():
new_subtheme = SubTheme()
new_subtheme.name = form.cleaned_data['name']
new_subtheme.order = 0
new_subtheme.author = User.objects.get(pk=request.user.id)
new_subtheme.theme = theme
new_subtheme.timestamp = timezone.now()
new_subtheme.theme = theme
new_subtheme.save()
for subtheme in SubTheme.objects.filter(theme=theme):
subtheme.order += 1
subtheme.save()
log = EventLog()
log.author = request.user
log.entity_type = 'sous-thème'
log.entity_uid = SubTheme.objects.all().order_by('created_date').last().uid
log.action = 'Création'
log.theme = theme
log.value = str(new_subtheme.name)[0:40]
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid)) | @login_required
def AddSubTheme(request, theme_uid):
'\n \n '
theme = Theme.objects.get(pk=theme_uid)
if ((request.method == 'POST') and (request.user in theme.authorized_user.all())):
form = NewSubThemeForm(request.POST)
if form.is_valid():
new_subtheme = SubTheme()
new_subtheme.name = form.cleaned_data['name']
new_subtheme.order = 0
new_subtheme.author = User.objects.get(pk=request.user.id)
new_subtheme.theme = theme
new_subtheme.timestamp = timezone.now()
new_subtheme.theme = theme
new_subtheme.save()
for subtheme in SubTheme.objects.filter(theme=theme):
subtheme.order += 1
subtheme.save()
log = EventLog()
log.author = request.user
log.entity_type = 'sous-thème'
log.entity_uid = SubTheme.objects.all().order_by('created_date').last().uid
log.action = 'Création'
log.theme = theme
log.value = str(new_subtheme.name)[0:40]
log.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid))
else:
return HttpResponseRedirect('/nope')
else:
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid))<|docstring|>Display the content of the folder linked to the Galery object<|endoftext|> |
299683895bba02fc2d6ef75c982b36a7ed8bb73e548bda0085a5dc76ea6fdce6 | @login_required
def ItemStatusSwitch(request, item_uid, item_action):
'\n An todo item is_active status can be switched with this view.\n '
item = Item.objects.get(pk=item_uid)
subtheme = item.subtheme
theme = subtheme.theme
if ((item_action == 'active_switch') and (request.user in theme.authorized_user.all())):
if (item.is_active == True):
item.is_active = False
item.is_important = False
item.completed_date = timezone.now()
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Complétion'
log.theme = theme
log.save()
else:
item.is_active = True
item.completed_date = None
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Réactivation'
log.theme = theme
log.save()
elif ((item_action == 'importance_switch') and (request.user in theme.authorized_user.all())):
if (item.is_important == True):
item.is_important = False
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Priorité abaissée'
log.theme = theme
log.save()
else:
item.is_important = True
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Priorité élevée'
log.theme = theme
log.save()
else:
return HttpResponseRedirect('/nope')
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid)) | An todo item is_active status can be switched with this view. | views.py | ItemStatusSwitch | j-ollivier/vaste-roadmap | 0 | python | @login_required
def ItemStatusSwitch(request, item_uid, item_action):
'\n \n '
item = Item.objects.get(pk=item_uid)
subtheme = item.subtheme
theme = subtheme.theme
if ((item_action == 'active_switch') and (request.user in theme.authorized_user.all())):
if (item.is_active == True):
item.is_active = False
item.is_important = False
item.completed_date = timezone.now()
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Complétion'
log.theme = theme
log.save()
else:
item.is_active = True
item.completed_date = None
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Réactivation'
log.theme = theme
log.save()
elif ((item_action == 'importance_switch') and (request.user in theme.authorized_user.all())):
if (item.is_important == True):
item.is_important = False
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Priorité abaissée'
log.theme = theme
log.save()
else:
item.is_important = True
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Priorité élevée'
log.theme = theme
log.save()
else:
return HttpResponseRedirect('/nope')
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid)) | @login_required
def ItemStatusSwitch(request, item_uid, item_action):
'\n \n '
item = Item.objects.get(pk=item_uid)
subtheme = item.subtheme
theme = subtheme.theme
if ((item_action == 'active_switch') and (request.user in theme.authorized_user.all())):
if (item.is_active == True):
item.is_active = False
item.is_important = False
item.completed_date = timezone.now()
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Complétion'
log.theme = theme
log.save()
else:
item.is_active = True
item.completed_date = None
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Réactivation'
log.theme = theme
log.save()
elif ((item_action == 'importance_switch') and (request.user in theme.authorized_user.all())):
if (item.is_important == True):
item.is_important = False
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Priorité abaissée'
log.theme = theme
log.save()
else:
item.is_important = True
item.save()
log = EventLog()
log.author = request.user
log.entity_type = 'item'
log.entity_uid = Item.objects.all().order_by('created_date').last().uid
log.action = 'Priorité élevée'
log.theme = theme
log.save()
else:
return HttpResponseRedirect('/nope')
return HttpResponseRedirect('/roadmap/view/{}'.format(theme.uid))<|docstring|>An todo item is_active status can be switched with this view.<|endoftext|> |
105da44c1d07706e16e5b4ad7024c3e0b2b76e40900e5ed385888521e2ff6e41 | @login_required
def SubThemeOrderChange(request, subtheme_uid, subtheme_action):
'\n Users are allowed to change the order of subthemes.\n This view handles the ordrer change and the order change \n of the other subthemes to adapt to the new order value of \n the changed subtheme.\n '
subtheme = SubTheme.objects.get(pk=subtheme_uid)
if (subtheme_action == 'to_up'):
order_modificator = (- 1)
elif (subtheme_action == 'to_down'):
order_modificator = 1
else:
return HttpResponseRedirect('/nope')
if (request.user in subtheme.theme.authorized_user.all()):
if (subtheme.order <= 1):
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
pass
try:
subtheme.order += order_modificator
subtheme_to_swap = SubTheme.objects.get(theme=subtheme.theme, order=subtheme.order)
subtheme.save()
except ObjectDoesNotExist:
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
subtheme_to_swap.order += (- order_modificator)
subtheme_to_swap.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope') | Users are allowed to change the order of subthemes.
This view handles the ordrer change and the order change
of the other subthemes to adapt to the new order value of
the changed subtheme. | views.py | SubThemeOrderChange | j-ollivier/vaste-roadmap | 0 | python | @login_required
def SubThemeOrderChange(request, subtheme_uid, subtheme_action):
'\n Users are allowed to change the order of subthemes.\n This view handles the ordrer change and the order change \n of the other subthemes to adapt to the new order value of \n the changed subtheme.\n '
subtheme = SubTheme.objects.get(pk=subtheme_uid)
if (subtheme_action == 'to_up'):
order_modificator = (- 1)
elif (subtheme_action == 'to_down'):
order_modificator = 1
else:
return HttpResponseRedirect('/nope')
if (request.user in subtheme.theme.authorized_user.all()):
if (subtheme.order <= 1):
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
pass
try:
subtheme.order += order_modificator
subtheme_to_swap = SubTheme.objects.get(theme=subtheme.theme, order=subtheme.order)
subtheme.save()
except ObjectDoesNotExist:
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
subtheme_to_swap.order += (- order_modificator)
subtheme_to_swap.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope') | @login_required
def SubThemeOrderChange(request, subtheme_uid, subtheme_action):
'\n Users are allowed to change the order of subthemes.\n This view handles the ordrer change and the order change \n of the other subthemes to adapt to the new order value of \n the changed subtheme.\n '
subtheme = SubTheme.objects.get(pk=subtheme_uid)
if (subtheme_action == 'to_up'):
order_modificator = (- 1)
elif (subtheme_action == 'to_down'):
order_modificator = 1
else:
return HttpResponseRedirect('/nope')
if (request.user in subtheme.theme.authorized_user.all()):
if (subtheme.order <= 1):
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
pass
try:
subtheme.order += order_modificator
subtheme_to_swap = SubTheme.objects.get(theme=subtheme.theme, order=subtheme.order)
subtheme.save()
except ObjectDoesNotExist:
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
subtheme_to_swap.order += (- order_modificator)
subtheme_to_swap.save()
return HttpResponseRedirect('/roadmap/view/{}'.format(subtheme.theme.uid))
else:
return HttpResponseRedirect('/nope')<|docstring|>Users are allowed to change the order of subthemes.
This view handles the ordrer change and the order change
of the other subthemes to adapt to the new order value of
the changed subtheme.<|endoftext|> |
bc2e01bde0feebb73efbf365750671eba2548155b7d833969aec7d8d1675ef41 | def subarray_sum_dp_prefix_sum(numbers: List[int], queries: [List[tuple]]) -> List[int]:
'\n Args:\n numbers: List of numbers\n queries: queries are in the form a tuple (start, end)\n Returns:\n '
prefix_sum = [numbers[0]]
for i in range(len(numbers)):
prefix_sum.append((prefix_sum[(- 1)] + numbers[i]))
print(f'The prefix sum is: {prefix_sum}')
return [(prefix_sum[(end + 1)] - prefix_sum[start]) for (start, end) in queries] | Args:
numbers: List of numbers
queries: queries are in the form a tuple (start, end)
Returns: | algorithms/dynamic/subarray_sum_range_query.py | subarray_sum_dp_prefix_sum | hariharanragothaman/pymaster | 10 | python | def subarray_sum_dp_prefix_sum(numbers: List[int], queries: [List[tuple]]) -> List[int]:
'\n Args:\n numbers: List of numbers\n queries: queries are in the form a tuple (start, end)\n Returns:\n '
prefix_sum = [numbers[0]]
for i in range(len(numbers)):
prefix_sum.append((prefix_sum[(- 1)] + numbers[i]))
print(f'The prefix sum is: {prefix_sum}')
return [(prefix_sum[(end + 1)] - prefix_sum[start]) for (start, end) in queries] | def subarray_sum_dp_prefix_sum(numbers: List[int], queries: [List[tuple]]) -> List[int]:
'\n Args:\n numbers: List of numbers\n queries: queries are in the form a tuple (start, end)\n Returns:\n '
prefix_sum = [numbers[0]]
for i in range(len(numbers)):
prefix_sum.append((prefix_sum[(- 1)] + numbers[i]))
print(f'The prefix sum is: {prefix_sum}')
return [(prefix_sum[(end + 1)] - prefix_sum[start]) for (start, end) in queries]<|docstring|>Args:
numbers: List of numbers
queries: queries are in the form a tuple (start, end)
Returns:<|endoftext|> |
9fe6cb5a951603452b08d66cb05d4a094369fee6726a53b7f0f15d20625eef6b | def test_pat(self):
'Verify class functionality with personal access token.'
auth_config = PCOAuthConfig('app_id', 'secret')
self.assertIsInstance(auth_config, PCOAuthConfig, 'Class is not instnace of PCOAuthConfig!')
self.assertIsNotNone(auth_config.application_id, 'No application_id found on object!')
self.assertIsNotNone(auth_config.secret, 'No secret found on object!')
self.assertEqual(auth_config.auth_type, PCOAuthType.PAT, 'Wrong authentication type!') | Verify class functionality with personal access token. | tests/test_auth_config.py | test_pat | HobokenGrace/hg-pypco | 29 | python | def test_pat(self):
auth_config = PCOAuthConfig('app_id', 'secret')
self.assertIsInstance(auth_config, PCOAuthConfig, 'Class is not instnace of PCOAuthConfig!')
self.assertIsNotNone(auth_config.application_id, 'No application_id found on object!')
self.assertIsNotNone(auth_config.secret, 'No secret found on object!')
self.assertEqual(auth_config.auth_type, PCOAuthType.PAT, 'Wrong authentication type!') | def test_pat(self):
auth_config = PCOAuthConfig('app_id', 'secret')
self.assertIsInstance(auth_config, PCOAuthConfig, 'Class is not instnace of PCOAuthConfig!')
self.assertIsNotNone(auth_config.application_id, 'No application_id found on object!')
self.assertIsNotNone(auth_config.secret, 'No secret found on object!')
self.assertEqual(auth_config.auth_type, PCOAuthType.PAT, 'Wrong authentication type!')<|docstring|>Verify class functionality with personal access token.<|endoftext|> |
fddb473cab06ad2fadea55f601510f032c9da64a5d423b13718a2987debe1935 | def test_oauth(self):
'Verify class functionality with OAuth.'
auth_config = PCOAuthConfig(token='abcd1234')
self.assertIsInstance(auth_config, PCOAuthConfig, 'Class is not instnace of PCOAuthConfig!')
self.assertIsNotNone(auth_config.token, 'No token found on object!')
self.assertEqual(auth_config.auth_type, PCOAuthType.OAUTH, 'Wrong authentication type!') | Verify class functionality with OAuth. | tests/test_auth_config.py | test_oauth | HobokenGrace/hg-pypco | 29 | python | def test_oauth(self):
auth_config = PCOAuthConfig(token='abcd1234')
self.assertIsInstance(auth_config, PCOAuthConfig, 'Class is not instnace of PCOAuthConfig!')
self.assertIsNotNone(auth_config.token, 'No token found on object!')
self.assertEqual(auth_config.auth_type, PCOAuthType.OAUTH, 'Wrong authentication type!') | def test_oauth(self):
auth_config = PCOAuthConfig(token='abcd1234')
self.assertIsInstance(auth_config, PCOAuthConfig, 'Class is not instnace of PCOAuthConfig!')
self.assertIsNotNone(auth_config.token, 'No token found on object!')
self.assertEqual(auth_config.auth_type, PCOAuthType.OAUTH, 'Wrong authentication type!')<|docstring|>Verify class functionality with OAuth.<|endoftext|> |
f7fc8dc40fa25e499f4a3d542520e55e428923761410a37935b52c4e123b0e87 | def test_invalid_auth(self):
'Verify an error when we try to get auth type with bad auth.'
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig('bad_app_id').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(secret='bad_app_secret').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(application_id='bad_app_id', token='token').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(secret='bad_secret', token='bad_token').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig().auth_type | Verify an error when we try to get auth type with bad auth. | tests/test_auth_config.py | test_invalid_auth | HobokenGrace/hg-pypco | 29 | python | def test_invalid_auth(self):
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig('bad_app_id').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(secret='bad_app_secret').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(application_id='bad_app_id', token='token').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(secret='bad_secret', token='bad_token').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig().auth_type | def test_invalid_auth(self):
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig('bad_app_id').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(secret='bad_app_secret').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(application_id='bad_app_id', token='token').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig(secret='bad_secret', token='bad_token').auth_type
with self.assertRaises(PCOCredentialsException):
PCOAuthConfig().auth_type<|docstring|>Verify an error when we try to get auth type with bad auth.<|endoftext|> |
5b52c0cad20872b8e18d278e873be38b088bc7656d9cfe541db6f0802a70bf06 | def test_auth_headers(self):
'Verify that we get the correct authentication headers.'
auth_config = PCOAuthConfig('app_id', 'secret')
self.assertEqual(auth_config.auth_header, 'Basic YXBwX2lkOnNlY3JldA==', 'Invalid PAT authentication header.')
auth_config = PCOAuthConfig(token='abcd1234')
self.assertEqual(auth_config.auth_header, 'Bearer abcd1234', 'Invalid OAUTH authentication header.') | Verify that we get the correct authentication headers. | tests/test_auth_config.py | test_auth_headers | HobokenGrace/hg-pypco | 29 | python | def test_auth_headers(self):
auth_config = PCOAuthConfig('app_id', 'secret')
self.assertEqual(auth_config.auth_header, 'Basic YXBwX2lkOnNlY3JldA==', 'Invalid PAT authentication header.')
auth_config = PCOAuthConfig(token='abcd1234')
self.assertEqual(auth_config.auth_header, 'Bearer abcd1234', 'Invalid OAUTH authentication header.') | def test_auth_headers(self):
auth_config = PCOAuthConfig('app_id', 'secret')
self.assertEqual(auth_config.auth_header, 'Basic YXBwX2lkOnNlY3JldA==', 'Invalid PAT authentication header.')
auth_config = PCOAuthConfig(token='abcd1234')
self.assertEqual(auth_config.auth_header, 'Bearer abcd1234', 'Invalid OAUTH authentication header.')<|docstring|>Verify that we get the correct authentication headers.<|endoftext|> |
92db6e8af60cddc75aaf27cc80a4bc22c0c576db40646e45472a797bfa080937 | def train_step(x1_batch, x2_batch, y_batch):
'\n A single training step\n :param x1_batch:\n :param x2_batch:\n :param y_batch:\n :return:\n '
feed_dict = {siameseModel.input_x1: x1_batch, siameseModel.input_x2: x2_batch, siameseModel.input_y: y_batch, siameseModel.dropout_keep_prob: DROPOUT_KEEP_PROB}
(_, step, loss, accuracy, f1, dist, sim, summaries) = sess.run([tr_op_set, global_step, siameseModel.loss, siameseModel.accuracy, siameseModel.f1, siameseModel.distance, siameseModel.temp_sim, train_summary_op], feed_dict)
time_str = datetime.datetime.now().isoformat()
print('TRAIN {}: step {}, loss {:g}, acc {:g}, f1 {:g}'.format(time_str, step, loss, accuracy, f1))
train_summary_writer.add_summary(summaries, step)
print(y_batch, dist, sim) | A single training step
:param x1_batch:
:param x2_batch:
:param y_batch:
:return: | Chatbot_Model/Text_Similarity/train.py | train_step | chenpocufa/Chatbot_CN | 8 | python | def train_step(x1_batch, x2_batch, y_batch):
'\n A single training step\n :param x1_batch:\n :param x2_batch:\n :param y_batch:\n :return:\n '
feed_dict = {siameseModel.input_x1: x1_batch, siameseModel.input_x2: x2_batch, siameseModel.input_y: y_batch, siameseModel.dropout_keep_prob: DROPOUT_KEEP_PROB}
(_, step, loss, accuracy, f1, dist, sim, summaries) = sess.run([tr_op_set, global_step, siameseModel.loss, siameseModel.accuracy, siameseModel.f1, siameseModel.distance, siameseModel.temp_sim, train_summary_op], feed_dict)
time_str = datetime.datetime.now().isoformat()
print('TRAIN {}: step {}, loss {:g}, acc {:g}, f1 {:g}'.format(time_str, step, loss, accuracy, f1))
train_summary_writer.add_summary(summaries, step)
print(y_batch, dist, sim) | def train_step(x1_batch, x2_batch, y_batch):
'\n A single training step\n :param x1_batch:\n :param x2_batch:\n :param y_batch:\n :return:\n '
feed_dict = {siameseModel.input_x1: x1_batch, siameseModel.input_x2: x2_batch, siameseModel.input_y: y_batch, siameseModel.dropout_keep_prob: DROPOUT_KEEP_PROB}
(_, step, loss, accuracy, f1, dist, sim, summaries) = sess.run([tr_op_set, global_step, siameseModel.loss, siameseModel.accuracy, siameseModel.f1, siameseModel.distance, siameseModel.temp_sim, train_summary_op], feed_dict)
time_str = datetime.datetime.now().isoformat()
print('TRAIN {}: step {}, loss {:g}, acc {:g}, f1 {:g}'.format(time_str, step, loss, accuracy, f1))
train_summary_writer.add_summary(summaries, step)
print(y_batch, dist, sim)<|docstring|>A single training step
:param x1_batch:
:param x2_batch:
:param y_batch:
:return:<|endoftext|> |
2d567da0aac6aa70f01c83d3357ac78985ffe8fa5dddf3865a9f794de54d8d6d | def get_specific_config(prefix):
'Retrieve config based on the format [<prefix>:<value>].\n\n returns: a dict, {<UUID>: {<key1>:<value1>, <key2>:<value2>, ...}}\n '
conf_dict = {}
multi_parser = cfg.MultiConfigParser()
read_ok = multi_parser.read(cfg.CONF.config_file)
if (len(read_ok) != len(cfg.CONF.config_file)):
raise cfg.Error(_('Some config files were not parsed properly'))
for parsed_file in multi_parser.parsed:
for parsed_item in parsed_file.keys():
p_i = parsed_item.lower()
if p_i.startswith(prefix):
(section_type, uuid) = p_i.split(':')
if (section_type == prefix):
conf_dict[uuid] = {k: v[0] for (k, v) in parsed_file[parsed_item].items()}
return conf_dict | Retrieve config based on the format [<prefix>:<value>].
returns: a dict, {<UUID>: {<key1>:<value1>, <key2>:<value2>, ...}} | networking_cisco/plugins/cisco/device_manager/config.py | get_specific_config | CiscoSystems/networking-cisco | 8 | python | def get_specific_config(prefix):
'Retrieve config based on the format [<prefix>:<value>].\n\n returns: a dict, {<UUID>: {<key1>:<value1>, <key2>:<value2>, ...}}\n '
conf_dict = {}
multi_parser = cfg.MultiConfigParser()
read_ok = multi_parser.read(cfg.CONF.config_file)
if (len(read_ok) != len(cfg.CONF.config_file)):
raise cfg.Error(_('Some config files were not parsed properly'))
for parsed_file in multi_parser.parsed:
for parsed_item in parsed_file.keys():
p_i = parsed_item.lower()
if p_i.startswith(prefix):
(section_type, uuid) = p_i.split(':')
if (section_type == prefix):
conf_dict[uuid] = {k: v[0] for (k, v) in parsed_file[parsed_item].items()}
return conf_dict | def get_specific_config(prefix):
'Retrieve config based on the format [<prefix>:<value>].\n\n returns: a dict, {<UUID>: {<key1>:<value1>, <key2>:<value2>, ...}}\n '
conf_dict = {}
multi_parser = cfg.MultiConfigParser()
read_ok = multi_parser.read(cfg.CONF.config_file)
if (len(read_ok) != len(cfg.CONF.config_file)):
raise cfg.Error(_('Some config files were not parsed properly'))
for parsed_file in multi_parser.parsed:
for parsed_item in parsed_file.keys():
p_i = parsed_item.lower()
if p_i.startswith(prefix):
(section_type, uuid) = p_i.split(':')
if (section_type == prefix):
conf_dict[uuid] = {k: v[0] for (k, v) in parsed_file[parsed_item].items()}
return conf_dict<|docstring|>Retrieve config based on the format [<prefix>:<value>].
returns: a dict, {<UUID>: {<key1>:<value1>, <key2>:<value2>, ...}}<|endoftext|> |
58d081093d3e92e9cab94d73168f9e3c6e1602236451325280fc05d14f51aa70 | def verify_resource_dict(res_dict, is_create, attr_info):
"Verifies required attributes are in resource dictionary, res_dict.\n\n Also checking that an attribute is only specified if it is allowed\n for the given operation (create/update).\n\n Attribute with default values are considered to be optional.\n\n This function contains code taken from function 'prepare_request_body' in\n attributes.py.\n "
if is_create:
for (attr, attr_vals) in six.iteritems(attr_info):
if attr_vals['allow_post']:
if (('default' not in attr_vals) and (attr not in res_dict)):
msg = (_("Failed to parse request. Required attribute '%s' not specified") % attr)
raise webob.exc.HTTPBadRequest(msg)
res_dict[attr] = res_dict.get(attr, attr_vals.get('default'))
elif (attr in res_dict):
msg = (_("Attribute '%s' not allowed in POST") % attr)
raise webob.exc.HTTPBadRequest(msg)
else:
for (attr, attr_vals) in six.iteritems(attr_info):
if ((attr in res_dict) and (not attr_vals['allow_put'])):
msg = (_('Cannot update read-only attribute %s') % attr)
raise webob.exc.HTTPBadRequest(msg)
for (attr, attr_vals) in six.iteritems(attr_info):
if ((attr not in res_dict) or (res_dict[attr] is attributes.ATTR_NOT_SPECIFIED)):
continue
if ('convert_to' in attr_vals):
res_dict[attr] = attr_vals['convert_to'](res_dict[attr])
if ('validate' not in attr_vals):
continue
for rule in attr_vals['validate']:
_ensure_format(rule, attr, res_dict)
res = attributes.validators[rule](res_dict[attr], attr_vals['validate'][rule])
if res:
msg_dict = dict(attr=attr, reason=res)
msg = (_('Invalid input for %(attr)s. Reason: %(reason)s.') % msg_dict)
raise webob.exc.HTTPBadRequest(msg)
return res_dict | Verifies required attributes are in resource dictionary, res_dict.
Also checking that an attribute is only specified if it is allowed
for the given operation (create/update).
Attribute with default values are considered to be optional.
This function contains code taken from function 'prepare_request_body' in
attributes.py. | networking_cisco/plugins/cisco/device_manager/config.py | verify_resource_dict | CiscoSystems/networking-cisco | 8 | python | def verify_resource_dict(res_dict, is_create, attr_info):
"Verifies required attributes are in resource dictionary, res_dict.\n\n Also checking that an attribute is only specified if it is allowed\n for the given operation (create/update).\n\n Attribute with default values are considered to be optional.\n\n This function contains code taken from function 'prepare_request_body' in\n attributes.py.\n "
if is_create:
for (attr, attr_vals) in six.iteritems(attr_info):
if attr_vals['allow_post']:
if (('default' not in attr_vals) and (attr not in res_dict)):
msg = (_("Failed to parse request. Required attribute '%s' not specified") % attr)
raise webob.exc.HTTPBadRequest(msg)
res_dict[attr] = res_dict.get(attr, attr_vals.get('default'))
elif (attr in res_dict):
msg = (_("Attribute '%s' not allowed in POST") % attr)
raise webob.exc.HTTPBadRequest(msg)
else:
for (attr, attr_vals) in six.iteritems(attr_info):
if ((attr in res_dict) and (not attr_vals['allow_put'])):
msg = (_('Cannot update read-only attribute %s') % attr)
raise webob.exc.HTTPBadRequest(msg)
for (attr, attr_vals) in six.iteritems(attr_info):
if ((attr not in res_dict) or (res_dict[attr] is attributes.ATTR_NOT_SPECIFIED)):
continue
if ('convert_to' in attr_vals):
res_dict[attr] = attr_vals['convert_to'](res_dict[attr])
if ('validate' not in attr_vals):
continue
for rule in attr_vals['validate']:
_ensure_format(rule, attr, res_dict)
res = attributes.validators[rule](res_dict[attr], attr_vals['validate'][rule])
if res:
msg_dict = dict(attr=attr, reason=res)
msg = (_('Invalid input for %(attr)s. Reason: %(reason)s.') % msg_dict)
raise webob.exc.HTTPBadRequest(msg)
return res_dict | def verify_resource_dict(res_dict, is_create, attr_info):
"Verifies required attributes are in resource dictionary, res_dict.\n\n Also checking that an attribute is only specified if it is allowed\n for the given operation (create/update).\n\n Attribute with default values are considered to be optional.\n\n This function contains code taken from function 'prepare_request_body' in\n attributes.py.\n "
if is_create:
for (attr, attr_vals) in six.iteritems(attr_info):
if attr_vals['allow_post']:
if (('default' not in attr_vals) and (attr not in res_dict)):
msg = (_("Failed to parse request. Required attribute '%s' not specified") % attr)
raise webob.exc.HTTPBadRequest(msg)
res_dict[attr] = res_dict.get(attr, attr_vals.get('default'))
elif (attr in res_dict):
msg = (_("Attribute '%s' not allowed in POST") % attr)
raise webob.exc.HTTPBadRequest(msg)
else:
for (attr, attr_vals) in six.iteritems(attr_info):
if ((attr in res_dict) and (not attr_vals['allow_put'])):
msg = (_('Cannot update read-only attribute %s') % attr)
raise webob.exc.HTTPBadRequest(msg)
for (attr, attr_vals) in six.iteritems(attr_info):
if ((attr not in res_dict) or (res_dict[attr] is attributes.ATTR_NOT_SPECIFIED)):
continue
if ('convert_to' in attr_vals):
res_dict[attr] = attr_vals['convert_to'](res_dict[attr])
if ('validate' not in attr_vals):
continue
for rule in attr_vals['validate']:
_ensure_format(rule, attr, res_dict)
res = attributes.validators[rule](res_dict[attr], attr_vals['validate'][rule])
if res:
msg_dict = dict(attr=attr, reason=res)
msg = (_('Invalid input for %(attr)s. Reason: %(reason)s.') % msg_dict)
raise webob.exc.HTTPBadRequest(msg)
return res_dict<|docstring|>Verifies required attributes are in resource dictionary, res_dict.
Also checking that an attribute is only specified if it is allowed
for the given operation (create/update).
Attribute with default values are considered to be optional.
This function contains code taken from function 'prepare_request_body' in
attributes.py.<|endoftext|> |
33ea9d0d7665104d15126d408935187286317f43d1b540a46f5a57c72a57b071 | def uuidify(val):
'Takes an integer and transforms it to a UUID format.\n\n returns: UUID formatted version of input.\n '
if uuidutils.is_uuid_like(val):
return val
else:
try:
int_val = int(val, 16)
except ValueError:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Invalid UUID format %s. Please provide an integer in decimal (0-9) or hex (0-9a-e) format'), val)
res = str(int_val)
num = (12 - len(res))
return (('00000000-0000-0000-0000-' + ('0' * num)) + res) | Takes an integer and transforms it to a UUID format.
returns: UUID formatted version of input. | networking_cisco/plugins/cisco/device_manager/config.py | uuidify | CiscoSystems/networking-cisco | 8 | python | def uuidify(val):
'Takes an integer and transforms it to a UUID format.\n\n returns: UUID formatted version of input.\n '
if uuidutils.is_uuid_like(val):
return val
else:
try:
int_val = int(val, 16)
except ValueError:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Invalid UUID format %s. Please provide an integer in decimal (0-9) or hex (0-9a-e) format'), val)
res = str(int_val)
num = (12 - len(res))
return (('00000000-0000-0000-0000-' + ('0' * num)) + res) | def uuidify(val):
'Takes an integer and transforms it to a UUID format.\n\n returns: UUID formatted version of input.\n '
if uuidutils.is_uuid_like(val):
return val
else:
try:
int_val = int(val, 16)
except ValueError:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Invalid UUID format %s. Please provide an integer in decimal (0-9) or hex (0-9a-e) format'), val)
res = str(int_val)
num = (12 - len(res))
return (('00000000-0000-0000-0000-' + ('0' * num)) + res)<|docstring|>Takes an integer and transforms it to a UUID format.
returns: UUID formatted version of input.<|endoftext|> |
e0257e1e4c95b8802f22cc0d57f4e9cbdf5f1c02790a6135686a33fdebaba558 | def _ensure_format(rule, attribute, res_dict):
"Verifies that attribute in res_dict is properly formatted.\n\n Since, in the .ini-files, lists are specified as ':' separated text and\n UUID values can be plain integers we need to transform any such values\n into proper format. Empty strings are converted to None if validator\n specifies that None value is accepted.\n "
if ((rule == 'type:uuid') or ((rule == 'type:uuid_or_none') and res_dict[attribute])):
res_dict[attribute] = uuidify(res_dict[attribute])
elif (rule == 'type:uuid_list'):
if (not res_dict[attribute]):
res_dict[attribute] = []
else:
temp_list = res_dict[attribute].split(':')
res_dict[attribute] = []
for item in temp_list:
res_dict[attribute].append = uuidify(item)
elif ((rule == 'type:string_or_none') and (res_dict[attribute] == '')):
res_dict[attribute] = None | Verifies that attribute in res_dict is properly formatted.
Since, in the .ini-files, lists are specified as ':' separated text and
UUID values can be plain integers we need to transform any such values
into proper format. Empty strings are converted to None if validator
specifies that None value is accepted. | networking_cisco/plugins/cisco/device_manager/config.py | _ensure_format | CiscoSystems/networking-cisco | 8 | python | def _ensure_format(rule, attribute, res_dict):
"Verifies that attribute in res_dict is properly formatted.\n\n Since, in the .ini-files, lists are specified as ':' separated text and\n UUID values can be plain integers we need to transform any such values\n into proper format. Empty strings are converted to None if validator\n specifies that None value is accepted.\n "
if ((rule == 'type:uuid') or ((rule == 'type:uuid_or_none') and res_dict[attribute])):
res_dict[attribute] = uuidify(res_dict[attribute])
elif (rule == 'type:uuid_list'):
if (not res_dict[attribute]):
res_dict[attribute] = []
else:
temp_list = res_dict[attribute].split(':')
res_dict[attribute] = []
for item in temp_list:
res_dict[attribute].append = uuidify(item)
elif ((rule == 'type:string_or_none') and (res_dict[attribute] == )):
res_dict[attribute] = None | def _ensure_format(rule, attribute, res_dict):
"Verifies that attribute in res_dict is properly formatted.\n\n Since, in the .ini-files, lists are specified as ':' separated text and\n UUID values can be plain integers we need to transform any such values\n into proper format. Empty strings are converted to None if validator\n specifies that None value is accepted.\n "
if ((rule == 'type:uuid') or ((rule == 'type:uuid_or_none') and res_dict[attribute])):
res_dict[attribute] = uuidify(res_dict[attribute])
elif (rule == 'type:uuid_list'):
if (not res_dict[attribute]):
res_dict[attribute] = []
else:
temp_list = res_dict[attribute].split(':')
res_dict[attribute] = []
for item in temp_list:
res_dict[attribute].append = uuidify(item)
elif ((rule == 'type:string_or_none') and (res_dict[attribute] == )):
res_dict[attribute] = None<|docstring|>Verifies that attribute in res_dict is properly formatted.
Since, in the .ini-files, lists are specified as ':' separated text and
UUID values can be plain integers we need to transform any such values
into proper format. Empty strings are converted to None if validator
specifies that None value is accepted.<|endoftext|> |
022d9b7eadad504a7813b452d3e9c70a17b1782b27725b3d3893e86ccd43482e | def plot_grid(self, colname, cmap=cm.jet, fname=None):
'\n @param colname: column to be plotted\n @param fname: dest for plot\n '
StateGrid(self.merged_data, colname.lower(), cmap)
if fname:
plt.savefig(fname)
else:
plt.show() | @param colname: column to be plotted
@param fname: dest for plot | stategrid/statedata.py | plot_grid | iamdavehawkins/StateGrid | 1 | python | def plot_grid(self, colname, cmap=cm.jet, fname=None):
'\n @param colname: column to be plotted\n @param fname: dest for plot\n '
StateGrid(self.merged_data, colname.lower(), cmap)
if fname:
plt.savefig(fname)
else:
plt.show() | def plot_grid(self, colname, cmap=cm.jet, fname=None):
'\n @param colname: column to be plotted\n @param fname: dest for plot\n '
StateGrid(self.merged_data, colname.lower(), cmap)
if fname:
plt.savefig(fname)
else:
plt.show()<|docstring|>@param colname: column to be plotted
@param fname: dest for plot<|endoftext|> |
7dd6d3b268b6ac4cffcaadabd9eb3034ff8d9a31d9840ef29c6dc87379bd86bc | def __init__(self, data, colname, cmap=cm.jet):
'\n @param user_data - pandas.DataFrame containing state location and values to plot\n @param colname - str column to be plotted, must be numeric user_data\n TODO: implement factor user_data, may already be some pandas built-in for this?\n '
self.data = data
self.colname = colname
self.cmap = cmap
self.mn = min(self.data[self.colname].dropna().astype(float))
self.mx = max(self.data[self.colname].dropna().astype(float))
self.fig = plt.figure()
self._build_states()
self._build_colorbar()
self._color_states()
self._recolor_state_labels() | @param user_data - pandas.DataFrame containing state location and values to plot
@param colname - str column to be plotted, must be numeric user_data
TODO: implement factor user_data, may already be some pandas built-in for this? | stategrid/statedata.py | __init__ | iamdavehawkins/StateGrid | 1 | python | def __init__(self, data, colname, cmap=cm.jet):
'\n @param user_data - pandas.DataFrame containing state location and values to plot\n @param colname - str column to be plotted, must be numeric user_data\n TODO: implement factor user_data, may already be some pandas built-in for this?\n '
self.data = data
self.colname = colname
self.cmap = cmap
self.mn = min(self.data[self.colname].dropna().astype(float))
self.mx = max(self.data[self.colname].dropna().astype(float))
self.fig = plt.figure()
self._build_states()
self._build_colorbar()
self._color_states()
self._recolor_state_labels() | def __init__(self, data, colname, cmap=cm.jet):
'\n @param user_data - pandas.DataFrame containing state location and values to plot\n @param colname - str column to be plotted, must be numeric user_data\n TODO: implement factor user_data, may already be some pandas built-in for this?\n '
self.data = data
self.colname = colname
self.cmap = cmap
self.mn = min(self.data[self.colname].dropna().astype(float))
self.mx = max(self.data[self.colname].dropna().astype(float))
self.fig = plt.figure()
self._build_states()
self._build_colorbar()
self._color_states()
self._recolor_state_labels()<|docstring|>@param user_data - pandas.DataFrame containing state location and values to plot
@param colname - str column to be plotted, must be numeric user_data
TODO: implement factor user_data, may already be some pandas built-in for this?<|endoftext|> |
8143cbb111bc6467e9b00f2aeaae5f3703da62c5b3c30b178935a1b4695f26d8 | def _recolor_state_labels(self):
'invert labels if cell background too dark'
pass | invert labels if cell background too dark | stategrid/statedata.py | _recolor_state_labels | iamdavehawkins/StateGrid | 1 | python | def _recolor_state_labels(self):
pass | def _recolor_state_labels(self):
pass<|docstring|>invert labels if cell background too dark<|endoftext|> |
0f15e973f58145f0215c5648a6b39c1b08d3dbcd3677aa868fc98e7c0ec2cf04 | def aggregateOneFileData(M06_file, M03_file):
"Aggregate one file from MYD06_L2 and its corresponding file from MYD03. Read 'Cloud_Mask_1km' variable from the MYD06_L2 file, read 'Latitude' and 'Longitude' variables from the MYD03 file. Group Cloud_Mask_1km values based on their (lat, lon) grid.\n\tArgs:\n\t\tM06_file (string): File path for M06_file.\n\t\tM03_file (string): File path for corresponding M03_file.\n\t\t\n\tReturns:\n\t\t(cloud_pix, total_pix) (tuple): cloud_pix is an 2D(180*360) numpy array for cloud pixel count of each grid, total_pix is an 2D(180*360) numpy array for total pixel count of each grid.\n "
var_list = ['Scan Offset', 'Track Offset', 'Height Offset', 'Height', 'SensorZenith', 'Range', 'SolarZenith', 'SolarAzimuth', 'Land/SeaMask', 'WaterPresent', 'gflags', 'Scan number', 'EV frames', 'Scan Type', 'EV start time', 'SD start time', 'SV start time', 'EV center time', 'Mirror side', 'SD Sun zenith', 'SD Sun azimuth', 'Moon Vector', 'orb_pos', 'orb_vel', 'T_inst2ECR', 'attitude_angles', 'sun_ref', 'impulse_enc', 'impulse_time', 'thermal_correction', 'SensorAzimuth']
total_pix = np.zeros((180, 360))
cloud_pix = np.zeros((180, 360))
with xr.open_dataset(M06_file, drop_variables='Scan Type') as ds_06:
d06 = ds_06['Cloud_Mask_1km'][(:, :, 0)].values
d06CM = d06[(::3, ::3)]
ds06_decoded = ((np.array(d06CM, dtype='byte') & 6) >> 1)
with xr.open_dataset(M03_file, drop_variables=var_list) as ds_03:
d03_lat = ds_03['Latitude'][(:, :)].values
d03_lon = ds_03['Longitude'][(:, :)].values
lat = (d03_lat[(::3, ::3)].ravel() + 89.5).astype(int)
lon = (d03_lon[(::3, ::3)].ravel() + 179.5).astype(int)
lat = np.where((lat > (- 1)), lat, 0)
lon = np.where((lon > (- 1)), lon, 0)
for (i, j) in zip(lat, lon):
total_pix[(i, j)] += 1
index = np.nonzero((ds06_decoded.ravel() == 0))
cloud_lon = [lon[i] for i in index[0]]
cloud_lat = [lat[i] for i in index[0]]
for (x, y) in zip(cloud_lat, cloud_lon):
cloud_pix[(x, y)] += 1
return (cloud_pix, total_pix) | Aggregate one file from MYD06_L2 and its corresponding file from MYD03. Read 'Cloud_Mask_1km' variable from the MYD06_L2 file, read 'Latitude' and 'Longitude' variables from the MYD03 file. Group Cloud_Mask_1km values based on their (lat, lon) grid.
Args:
M06_file (string): File path for M06_file.
M03_file (string): File path for corresponding M03_file.
Returns:
(cloud_pix, total_pix) (tuple): cloud_pix is an 2D(180*360) numpy array for cloud pixel count of each grid, total_pix is an 2D(180*360) numpy array for total pixel count of each grid. | benchmarking/baseline/monthly-aggregation-file-level-for-loop.py | aggregateOneFileData | supriyascode/MODIS-Aggregation | 0 | python | def aggregateOneFileData(M06_file, M03_file):
"Aggregate one file from MYD06_L2 and its corresponding file from MYD03. Read 'Cloud_Mask_1km' variable from the MYD06_L2 file, read 'Latitude' and 'Longitude' variables from the MYD03 file. Group Cloud_Mask_1km values based on their (lat, lon) grid.\n\tArgs:\n\t\tM06_file (string): File path for M06_file.\n\t\tM03_file (string): File path for corresponding M03_file.\n\t\t\n\tReturns:\n\t\t(cloud_pix, total_pix) (tuple): cloud_pix is an 2D(180*360) numpy array for cloud pixel count of each grid, total_pix is an 2D(180*360) numpy array for total pixel count of each grid.\n "
var_list = ['Scan Offset', 'Track Offset', 'Height Offset', 'Height', 'SensorZenith', 'Range', 'SolarZenith', 'SolarAzimuth', 'Land/SeaMask', 'WaterPresent', 'gflags', 'Scan number', 'EV frames', 'Scan Type', 'EV start time', 'SD start time', 'SV start time', 'EV center time', 'Mirror side', 'SD Sun zenith', 'SD Sun azimuth', 'Moon Vector', 'orb_pos', 'orb_vel', 'T_inst2ECR', 'attitude_angles', 'sun_ref', 'impulse_enc', 'impulse_time', 'thermal_correction', 'SensorAzimuth']
total_pix = np.zeros((180, 360))
cloud_pix = np.zeros((180, 360))
with xr.open_dataset(M06_file, drop_variables='Scan Type') as ds_06:
d06 = ds_06['Cloud_Mask_1km'][(:, :, 0)].values
d06CM = d06[(::3, ::3)]
ds06_decoded = ((np.array(d06CM, dtype='byte') & 6) >> 1)
with xr.open_dataset(M03_file, drop_variables=var_list) as ds_03:
d03_lat = ds_03['Latitude'][(:, :)].values
d03_lon = ds_03['Longitude'][(:, :)].values
lat = (d03_lat[(::3, ::3)].ravel() + 89.5).astype(int)
lon = (d03_lon[(::3, ::3)].ravel() + 179.5).astype(int)
lat = np.where((lat > (- 1)), lat, 0)
lon = np.where((lon > (- 1)), lon, 0)
for (i, j) in zip(lat, lon):
total_pix[(i, j)] += 1
index = np.nonzero((ds06_decoded.ravel() == 0))
cloud_lon = [lon[i] for i in index[0]]
cloud_lat = [lat[i] for i in index[0]]
for (x, y) in zip(cloud_lat, cloud_lon):
cloud_pix[(x, y)] += 1
return (cloud_pix, total_pix) | def aggregateOneFileData(M06_file, M03_file):
"Aggregate one file from MYD06_L2 and its corresponding file from MYD03. Read 'Cloud_Mask_1km' variable from the MYD06_L2 file, read 'Latitude' and 'Longitude' variables from the MYD03 file. Group Cloud_Mask_1km values based on their (lat, lon) grid.\n\tArgs:\n\t\tM06_file (string): File path for M06_file.\n\t\tM03_file (string): File path for corresponding M03_file.\n\t\t\n\tReturns:\n\t\t(cloud_pix, total_pix) (tuple): cloud_pix is an 2D(180*360) numpy array for cloud pixel count of each grid, total_pix is an 2D(180*360) numpy array for total pixel count of each grid.\n "
var_list = ['Scan Offset', 'Track Offset', 'Height Offset', 'Height', 'SensorZenith', 'Range', 'SolarZenith', 'SolarAzimuth', 'Land/SeaMask', 'WaterPresent', 'gflags', 'Scan number', 'EV frames', 'Scan Type', 'EV start time', 'SD start time', 'SV start time', 'EV center time', 'Mirror side', 'SD Sun zenith', 'SD Sun azimuth', 'Moon Vector', 'orb_pos', 'orb_vel', 'T_inst2ECR', 'attitude_angles', 'sun_ref', 'impulse_enc', 'impulse_time', 'thermal_correction', 'SensorAzimuth']
total_pix = np.zeros((180, 360))
cloud_pix = np.zeros((180, 360))
with xr.open_dataset(M06_file, drop_variables='Scan Type') as ds_06:
d06 = ds_06['Cloud_Mask_1km'][(:, :, 0)].values
d06CM = d06[(::3, ::3)]
ds06_decoded = ((np.array(d06CM, dtype='byte') & 6) >> 1)
with xr.open_dataset(M03_file, drop_variables=var_list) as ds_03:
d03_lat = ds_03['Latitude'][(:, :)].values
d03_lon = ds_03['Longitude'][(:, :)].values
lat = (d03_lat[(::3, ::3)].ravel() + 89.5).astype(int)
lon = (d03_lon[(::3, ::3)].ravel() + 179.5).astype(int)
lat = np.where((lat > (- 1)), lat, 0)
lon = np.where((lon > (- 1)), lon, 0)
for (i, j) in zip(lat, lon):
total_pix[(i, j)] += 1
index = np.nonzero((ds06_decoded.ravel() == 0))
cloud_lon = [lon[i] for i in index[0]]
cloud_lat = [lat[i] for i in index[0]]
for (x, y) in zip(cloud_lat, cloud_lon):
cloud_pix[(x, y)] += 1
return (cloud_pix, total_pix)<|docstring|>Aggregate one file from MYD06_L2 and its corresponding file from MYD03. Read 'Cloud_Mask_1km' variable from the MYD06_L2 file, read 'Latitude' and 'Longitude' variables from the MYD03 file. Group Cloud_Mask_1km values based on their (lat, lon) grid.
Args:
M06_file (string): File path for M06_file.
M03_file (string): File path for corresponding M03_file.
Returns:
(cloud_pix, total_pix) (tuple): cloud_pix is an 2D(180*360) numpy array for cloud pixel count of each grid, total_pix is an 2D(180*360) numpy array for total pixel count of each grid.<|endoftext|> |
d99f437e2c9cf05aebb530705c00d1cc718f6e40ce104048d45e5fd2194cf705 | def on_subscribe(self, handler: Callable) -> Callable[(..., Any)]:
'\n Decorator method is used to obtain subscribed topics and properties.\n '
log_info.info('on_subscribe handler accepted')
self.client.on_subscribe = handler
return handler | Decorator method is used to obtain subscribed topics and properties. | fastapi_mqtt/handlers.py | on_subscribe | mblo/fastapi-mqtt | 0 | python | def on_subscribe(self, handler: Callable) -> Callable[(..., Any)]:
'\n \n '
log_info.info('on_subscribe handler accepted')
self.client.on_subscribe = handler
return handler | def on_subscribe(self, handler: Callable) -> Callable[(..., Any)]:
'\n \n '
log_info.info('on_subscribe handler accepted')
self.client.on_subscribe = handler
return handler<|docstring|>Decorator method is used to obtain subscribed topics and properties.<|endoftext|> |
44585e090da18840680814d5012590ec59d5d5d9c3912e220941dd2169644e4b | def get_square(img, pos):
'\n Get one patch of the image based on position\n Arg:\n img: numpy array\n pos: tuple, shape_like = (row, column)\n Returns:\n a patch\n '
h = img.shape[0]
w = img.shape[1]
h_patch = int((h / num_patch))
w_patch = int((w / num_patch))
return img[((pos[0] * h_patch):((pos[0] + 1) * h_patch), (pos[1] * w_patch):((pos[1] + 1) * w_patch))] | Get one patch of the image based on position
Arg:
img: numpy array
pos: tuple, shape_like = (row, column)
Returns:
a patch | src/unet/util_image.py | get_square | roycezhou/Anomaly-detection-and-classification-with-deep-learning | 0 | python | def get_square(img, pos):
'\n Get one patch of the image based on position\n Arg:\n img: numpy array\n pos: tuple, shape_like = (row, column)\n Returns:\n a patch\n '
h = img.shape[0]
w = img.shape[1]
h_patch = int((h / num_patch))
w_patch = int((w / num_patch))
return img[((pos[0] * h_patch):((pos[0] + 1) * h_patch), (pos[1] * w_patch):((pos[1] + 1) * w_patch))] | def get_square(img, pos):
'\n Get one patch of the image based on position\n Arg:\n img: numpy array\n pos: tuple, shape_like = (row, column)\n Returns:\n a patch\n '
h = img.shape[0]
w = img.shape[1]
h_patch = int((h / num_patch))
w_patch = int((w / num_patch))
return img[((pos[0] * h_patch):((pos[0] + 1) * h_patch), (pos[1] * w_patch):((pos[1] + 1) * w_patch))]<|docstring|>Get one patch of the image based on position
Arg:
img: numpy array
pos: tuple, shape_like = (row, column)
Returns:
a patch<|endoftext|> |
e739dcd5aa31a3d7433ebd27a51e4e793dfd0e4f3b3bfaae014923b471ba2fc3 | def merge_masks(prob_list, image_shape):
'\n Merge patches of masks\n ----\n Arg:\n prob_list:\n image_shape: tuple, size=(h,w)\n '
new = np.zeros(image_shape, np.float32)
(h_patch, w_patch) = (int((image_shape[0] / num_patch)), int((image_shape[1] / num_patch)))
counter = 0
for i in range(num_patch):
for j in range(num_patch):
new[((i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] = prob_list[counter]
counter += 1
return new | Merge patches of masks
----
Arg:
prob_list:
image_shape: tuple, size=(h,w) | src/unet/util_image.py | merge_masks | roycezhou/Anomaly-detection-and-classification-with-deep-learning | 0 | python | def merge_masks(prob_list, image_shape):
'\n Merge patches of masks\n ----\n Arg:\n prob_list:\n image_shape: tuple, size=(h,w)\n '
new = np.zeros(image_shape, np.float32)
(h_patch, w_patch) = (int((image_shape[0] / num_patch)), int((image_shape[1] / num_patch)))
counter = 0
for i in range(num_patch):
for j in range(num_patch):
new[((i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] = prob_list[counter]
counter += 1
return new | def merge_masks(prob_list, image_shape):
'\n Merge patches of masks\n ----\n Arg:\n prob_list:\n image_shape: tuple, size=(h,w)\n '
new = np.zeros(image_shape, np.float32)
(h_patch, w_patch) = (int((image_shape[0] / num_patch)), int((image_shape[1] / num_patch)))
counter = 0
for i in range(num_patch):
for j in range(num_patch):
new[((i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] = prob_list[counter]
counter += 1
return new<|docstring|>Merge patches of masks
----
Arg:
prob_list:
image_shape: tuple, size=(h,w)<|endoftext|> |
a01a34f1024d5e08c544393c1ab5595b8c3ee5bcc2524c4490e89d34fb3fc5b1 | def get_row_batches(img, mask, num_patch):
' Divide 2048 by 2048 raw image into a list of row patches\n Arg:\n ------\n img: shape=(c, h, w)\n '
h = img.shape[1]
w = img.shape[2]
h_patch = int((h / num_patch[0]))
w_patch = int((w / num_patch[1]))
return (np.array([[img[(:, (i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] for j in range(num_patch[1])] for i in range(num_patch[0])]), np.array([[mask[((i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] for j in range(num_patch[1])] for i in range(num_patch[0])])) | Divide 2048 by 2048 raw image into a list of row patches
Arg:
------
img: shape=(c, h, w) | src/unet/util_image.py | get_row_batches | roycezhou/Anomaly-detection-and-classification-with-deep-learning | 0 | python | def get_row_batches(img, mask, num_patch):
' Divide 2048 by 2048 raw image into a list of row patches\n Arg:\n ------\n img: shape=(c, h, w)\n '
h = img.shape[1]
w = img.shape[2]
h_patch = int((h / num_patch[0]))
w_patch = int((w / num_patch[1]))
return (np.array([[img[(:, (i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] for j in range(num_patch[1])] for i in range(num_patch[0])]), np.array([[mask[((i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] for j in range(num_patch[1])] for i in range(num_patch[0])])) | def get_row_batches(img, mask, num_patch):
' Divide 2048 by 2048 raw image into a list of row patches\n Arg:\n ------\n img: shape=(c, h, w)\n '
h = img.shape[1]
w = img.shape[2]
h_patch = int((h / num_patch[0]))
w_patch = int((w / num_patch[1]))
return (np.array([[img[(:, (i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] for j in range(num_patch[1])] for i in range(num_patch[0])]), np.array([[mask[((i * h_patch):((i + 1) * h_patch), (j * w_patch):((j + 1) * w_patch))] for j in range(num_patch[1])] for i in range(num_patch[0])]))<|docstring|>Divide 2048 by 2048 raw image into a list of row patches
Arg:
------
img: shape=(c, h, w)<|endoftext|> |
d719e39abef89c58e773896420aac629e2ec11f58c8586688170a00069d3b9c1 | @pytest.fixture(scope='function')
def docker_client() -> DockerClient:
'\n Client to share across tests\n '
return docker.from_env() | Client to share across tests | tests/conftest.py | docker_client | piccolo-orm/piccolo_docker | 4 | python | @pytest.fixture(scope='function')
def docker_client() -> DockerClient:
'\n \n '
return docker.from_env() | @pytest.fixture(scope='function')
def docker_client() -> DockerClient:
'\n \n '
return docker.from_env()<|docstring|>Client to share across tests<|endoftext|> |
8be0aa213f6d3f6860732e0adecb9b047d5005f8ce88d76b0bb5b6d2a47286c0 | @pytest.fixture(scope='function')
def container(docker_client: DockerClient) -> Container:
'\n The container used in the tests\n '
from dockerdb.commands.create import create
(container_name, _) = create()
container = docker_client.containers.get(container_id=container_name)
(yield container)
with suppress(NotFound):
container.remove(force=True) | The container used in the tests | tests/conftest.py | container | piccolo-orm/piccolo_docker | 4 | python | @pytest.fixture(scope='function')
def container(docker_client: DockerClient) -> Container:
'\n \n '
from dockerdb.commands.create import create
(container_name, _) = create()
container = docker_client.containers.get(container_id=container_name)
(yield container)
with suppress(NotFound):
container.remove(force=True) | @pytest.fixture(scope='function')
def container(docker_client: DockerClient) -> Container:
'\n \n '
from dockerdb.commands.create import create
(container_name, _) = create()
container = docker_client.containers.get(container_id=container_name)
(yield container)
with suppress(NotFound):
container.remove(force=True)<|docstring|>The container used in the tests<|endoftext|> |
8ff3a7b519b80f8e7c32db5a51b4302bb228215c375259d706396f8896ea9195 | @pytest.fixture(scope='function')
def unique_container_name(monkeypatch) -> Generator[(str, None, None)]:
'\n Sets the value of UNIQUE_CONTAINER_NAME for the duration of each test\n '
_unique_container_name = f'piccolo_postgres_{fake.safe_color_name()}'
monkeypatch.setenv(name='UNIQUE_CONTAINER_NAME', value=_unique_container_name)
(yield _unique_container_name)
monkeypatch.undo() | Sets the value of UNIQUE_CONTAINER_NAME for the duration of each test | tests/conftest.py | unique_container_name | piccolo-orm/piccolo_docker | 4 | python | @pytest.fixture(scope='function')
def unique_container_name(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
_unique_container_name = f'piccolo_postgres_{fake.safe_color_name()}'
monkeypatch.setenv(name='UNIQUE_CONTAINER_NAME', value=_unique_container_name)
(yield _unique_container_name)
monkeypatch.undo() | @pytest.fixture(scope='function')
def unique_container_name(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
_unique_container_name = f'piccolo_postgres_{fake.safe_color_name()}'
monkeypatch.setenv(name='UNIQUE_CONTAINER_NAME', value=_unique_container_name)
(yield _unique_container_name)
monkeypatch.undo()<|docstring|>Sets the value of UNIQUE_CONTAINER_NAME for the duration of each test<|endoftext|> |
121ea180cb0fed64f0bbdf9746714590b0b69b70f363c7e6a47ebe7510c873b1 | @pytest.fixture(scope='function')
def pg_database(monkeypatch) -> Generator[(str, None, None)]:
'\n Sets the value of PG_DATABASE for the duration of each test\n '
_pg_database = f'piccolo_{fake.safe_color_name()}'
monkeypatch.setenv(name='PG_DATABASE', value=_pg_database)
(yield _pg_database)
monkeypatch.undo() | Sets the value of PG_DATABASE for the duration of each test | tests/conftest.py | pg_database | piccolo-orm/piccolo_docker | 4 | python | @pytest.fixture(scope='function')
def pg_database(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
_pg_database = f'piccolo_{fake.safe_color_name()}'
monkeypatch.setenv(name='PG_DATABASE', value=_pg_database)
(yield _pg_database)
monkeypatch.undo() | @pytest.fixture(scope='function')
def pg_database(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
_pg_database = f'piccolo_{fake.safe_color_name()}'
monkeypatch.setenv(name='PG_DATABASE', value=_pg_database)
(yield _pg_database)
monkeypatch.undo()<|docstring|>Sets the value of PG_DATABASE for the duration of each test<|endoftext|> |
ed65745f3f45bd18e3efb1d95828997302e4e61b0a2920e2bb8de8d0bfd0b520 | @pytest.fixture(scope='function')
def pg_port(monkeypatch) -> Generator[(str, None, None)]:
'\n Sets the value of PG_PORT for the duration of each test\n '
sock = socket.socket()
sock.bind(('', 0))
available_port = sock.getsockname()[1]
monkeypatch.setenv(name='PG_PORT', value=str(available_port))
(yield str(available_port))
monkeypatch.undo() | Sets the value of PG_PORT for the duration of each test | tests/conftest.py | pg_port | piccolo-orm/piccolo_docker | 4 | python | @pytest.fixture(scope='function')
def pg_port(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
sock = socket.socket()
sock.bind((, 0))
available_port = sock.getsockname()[1]
monkeypatch.setenv(name='PG_PORT', value=str(available_port))
(yield str(available_port))
monkeypatch.undo() | @pytest.fixture(scope='function')
def pg_port(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
sock = socket.socket()
sock.bind((, 0))
available_port = sock.getsockname()[1]
monkeypatch.setenv(name='PG_PORT', value=str(available_port))
(yield str(available_port))
monkeypatch.undo()<|docstring|>Sets the value of PG_PORT for the duration of each test<|endoftext|> |
add802a035cf73868d12245628851f785ce2f79ce62a5cf9a3cc4cdce9e76d6e | @pytest.fixture(scope='function')
def pg_password(monkeypatch) -> Generator[(str, None, None)]:
'\n Sets the value of PG_PASSWORD for the duration of each test\n '
_pg_password = fake.password()
monkeypatch.setenv(name='PG_PASSWORD', value=_pg_password)
(yield _pg_password)
monkeypatch.undo() | Sets the value of PG_PASSWORD for the duration of each test | tests/conftest.py | pg_password | piccolo-orm/piccolo_docker | 4 | python | @pytest.fixture(scope='function')
def pg_password(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
_pg_password = fake.password()
monkeypatch.setenv(name='PG_PASSWORD', value=_pg_password)
(yield _pg_password)
monkeypatch.undo() | @pytest.fixture(scope='function')
def pg_password(monkeypatch) -> Generator[(str, None, None)]:
'\n \n '
_pg_password = fake.password()
monkeypatch.setenv(name='PG_PASSWORD', value=_pg_password)
(yield _pg_password)
monkeypatch.undo()<|docstring|>Sets the value of PG_PASSWORD for the duration of each test<|endoftext|> |
25ee321a7ff3b4caff2f30a3abcbd83abef0aa77dc01925162eda50816a5e25c | @pytest.fixture(scope='function')
def set_env(unique_container_name, pg_database, pg_port, pg_password) -> None:
'\n Collection fixture used for better readability in the tests\n '
return | Collection fixture used for better readability in the tests | tests/conftest.py | set_env | piccolo-orm/piccolo_docker | 4 | python | @pytest.fixture(scope='function')
def set_env(unique_container_name, pg_database, pg_port, pg_password) -> None:
'\n \n '
return | @pytest.fixture(scope='function')
def set_env(unique_container_name, pg_database, pg_port, pg_password) -> None:
'\n \n '
return<|docstring|>Collection fixture used for better readability in the tests<|endoftext|> |
4b505c10b1db24de8002722ddecbba324b8b3cf41e14f50f27623de1a441e531 | def getMetricsAtETS(self):
'\n Calculate some metrics at ETS (Every Time Step)\n '
self.R_vector.fill(0.0)
self.sR_vector.fill(0.0)
(global_V, global_V0, global_sV, global_sV0, global_D_err) = self.clsvof.calculateMetricsAtETS(self.timeIntegration.dt, self.u[0].femSpace.elementMaps.psi, self.u[0].femSpace.elementMaps.grad_psi, self.mesh.nodeArray, self.mesh.elementNodesArray, self.elementQuadratureWeights[('u', 0)], self.u[0].femSpace.psi, self.u[0].femSpace.grad_psi, self.u[0].femSpace.psi, self.mesh.nElements_global, self.mesh.nElements_owned, self.coefficients.useMetrics, self.coefficients.q_vos, self.u[0].femSpace.dofMap.l2g, self.mesh.elementDiametersArray, self.mesh.nodeDiametersArray, self.degree_polynomial, self.coefficients.epsFactHeaviside, self.u[0].dof, self.u_dof_old, self.u0_dof, self.coefficients.q_v, self.offset[0], self.stride[0], self.nFreeDOF_global[0], self.R_vector, self.sR_vector)
from proteus.Comm import globalSum
self.global_V = globalSum(global_V)
self.global_V0 = globalSum(global_V0)
self.global_sV = globalSum(global_sV)
self.global_sV0 = globalSum(global_sV0)
self.global_V_err = old_div(np.abs((self.global_V - self.global_V0)), self.global_V0)
self.global_sV_err = old_div(np.abs((self.global_sV - self.global_sV0)), self.global_sV0)
self.global_D_err = globalSum(global_D_err)
n = self.mesh.subdomainMesh.nNodes_owned
self.global_R = np.sqrt(globalSum(np.dot(self.R_vector[0:n], self.R_vector[0:n])))
self.global_sR = np.sqrt(globalSum(np.dot(self.sR_vector[0:n], self.sR_vector[0:n]))) | Calculate some metrics at ETS (Every Time Step) | proteus/mprans/CLSVOF.py | getMetricsAtETS | zhang-alvin/cleanProteus | 0 | python | def getMetricsAtETS(self):
'\n \n '
self.R_vector.fill(0.0)
self.sR_vector.fill(0.0)
(global_V, global_V0, global_sV, global_sV0, global_D_err) = self.clsvof.calculateMetricsAtETS(self.timeIntegration.dt, self.u[0].femSpace.elementMaps.psi, self.u[0].femSpace.elementMaps.grad_psi, self.mesh.nodeArray, self.mesh.elementNodesArray, self.elementQuadratureWeights[('u', 0)], self.u[0].femSpace.psi, self.u[0].femSpace.grad_psi, self.u[0].femSpace.psi, self.mesh.nElements_global, self.mesh.nElements_owned, self.coefficients.useMetrics, self.coefficients.q_vos, self.u[0].femSpace.dofMap.l2g, self.mesh.elementDiametersArray, self.mesh.nodeDiametersArray, self.degree_polynomial, self.coefficients.epsFactHeaviside, self.u[0].dof, self.u_dof_old, self.u0_dof, self.coefficients.q_v, self.offset[0], self.stride[0], self.nFreeDOF_global[0], self.R_vector, self.sR_vector)
from proteus.Comm import globalSum
self.global_V = globalSum(global_V)
self.global_V0 = globalSum(global_V0)
self.global_sV = globalSum(global_sV)
self.global_sV0 = globalSum(global_sV0)
self.global_V_err = old_div(np.abs((self.global_V - self.global_V0)), self.global_V0)
self.global_sV_err = old_div(np.abs((self.global_sV - self.global_sV0)), self.global_sV0)
self.global_D_err = globalSum(global_D_err)
n = self.mesh.subdomainMesh.nNodes_owned
self.global_R = np.sqrt(globalSum(np.dot(self.R_vector[0:n], self.R_vector[0:n])))
self.global_sR = np.sqrt(globalSum(np.dot(self.sR_vector[0:n], self.sR_vector[0:n]))) | def getMetricsAtETS(self):
'\n \n '
self.R_vector.fill(0.0)
self.sR_vector.fill(0.0)
(global_V, global_V0, global_sV, global_sV0, global_D_err) = self.clsvof.calculateMetricsAtETS(self.timeIntegration.dt, self.u[0].femSpace.elementMaps.psi, self.u[0].femSpace.elementMaps.grad_psi, self.mesh.nodeArray, self.mesh.elementNodesArray, self.elementQuadratureWeights[('u', 0)], self.u[0].femSpace.psi, self.u[0].femSpace.grad_psi, self.u[0].femSpace.psi, self.mesh.nElements_global, self.mesh.nElements_owned, self.coefficients.useMetrics, self.coefficients.q_vos, self.u[0].femSpace.dofMap.l2g, self.mesh.elementDiametersArray, self.mesh.nodeDiametersArray, self.degree_polynomial, self.coefficients.epsFactHeaviside, self.u[0].dof, self.u_dof_old, self.u0_dof, self.coefficients.q_v, self.offset[0], self.stride[0], self.nFreeDOF_global[0], self.R_vector, self.sR_vector)
from proteus.Comm import globalSum
self.global_V = globalSum(global_V)
self.global_V0 = globalSum(global_V0)
self.global_sV = globalSum(global_sV)
self.global_sV0 = globalSum(global_sV0)
self.global_V_err = old_div(np.abs((self.global_V - self.global_V0)), self.global_V0)
self.global_sV_err = old_div(np.abs((self.global_sV - self.global_sV0)), self.global_sV0)
self.global_D_err = globalSum(global_D_err)
n = self.mesh.subdomainMesh.nNodes_owned
self.global_R = np.sqrt(globalSum(np.dot(self.R_vector[0:n], self.R_vector[0:n])))
self.global_sR = np.sqrt(globalSum(np.dot(self.sR_vector[0:n], self.sR_vector[0:n])))<|docstring|>Calculate some metrics at ETS (Every Time Step)<|endoftext|> |
7b1ab137dacc51663121e607bd330cae066be01c1bd38452b024d94b6a1d2143 | def calculateElementQuadrature(self):
'\n Calculate the physical location and weights of the quadrature rules\n and the shape information at the quadrature points.\n\n This function should be called only when the mesh changes.\n '
self.u[0].femSpace.elementMaps.getValues(self.elementQuadraturePoints, self.q['x'])
self.u[0].femSpace.elementMaps.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.coefficients.initializeElementQuadrature(self.timeIntegration.t, self.q)
if (self.stabilization != None):
self.stabilization.initializeElementQuadrature(self.mesh, self.timeIntegration.t, self.q)
self.stabilization.initializeTimeIntegration(self.timeIntegration)
if (self.shockCapturing != None):
self.shockCapturing.initializeElementQuadrature(self.mesh, self.timeIntegration.t, self.q) | Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points.
This function should be called only when the mesh changes. | proteus/mprans/CLSVOF.py | calculateElementQuadrature | zhang-alvin/cleanProteus | 0 | python | def calculateElementQuadrature(self):
'\n Calculate the physical location and weights of the quadrature rules\n and the shape information at the quadrature points.\n\n This function should be called only when the mesh changes.\n '
self.u[0].femSpace.elementMaps.getValues(self.elementQuadraturePoints, self.q['x'])
self.u[0].femSpace.elementMaps.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.coefficients.initializeElementQuadrature(self.timeIntegration.t, self.q)
if (self.stabilization != None):
self.stabilization.initializeElementQuadrature(self.mesh, self.timeIntegration.t, self.q)
self.stabilization.initializeTimeIntegration(self.timeIntegration)
if (self.shockCapturing != None):
self.shockCapturing.initializeElementQuadrature(self.mesh, self.timeIntegration.t, self.q) | def calculateElementQuadrature(self):
'\n Calculate the physical location and weights of the quadrature rules\n and the shape information at the quadrature points.\n\n This function should be called only when the mesh changes.\n '
self.u[0].femSpace.elementMaps.getValues(self.elementQuadraturePoints, self.q['x'])
self.u[0].femSpace.elementMaps.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.coefficients.initializeElementQuadrature(self.timeIntegration.t, self.q)
if (self.stabilization != None):
self.stabilization.initializeElementQuadrature(self.mesh, self.timeIntegration.t, self.q)
self.stabilization.initializeTimeIntegration(self.timeIntegration)
if (self.shockCapturing != None):
self.shockCapturing.initializeElementQuadrature(self.mesh, self.timeIntegration.t, self.q)<|docstring|>Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points.
This function should be called only when the mesh changes.<|endoftext|> |
c3e6278da3803c73a3aae4a4be11f4d3d9f8d8f7e0488fdf5c8ef5a9218af221 | def calculateExteriorElementBoundaryQuadrature(self):
'\n Calculate the physical location and weights of the quadrature rules\n and the shape information at the quadrature points on global element boundaries.\n\n This function should be called only when the mesh changes.\n '
self.u[0].femSpace.elementMaps.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getValuesGlobalExteriorTrace(self.elementBoundaryQuadraturePoints, self.ebqe['x'])
self.fluxBoundaryConditionsObjectsDict = dict([(cj, FluxBoundaryConditions(self.mesh, self.nElementBoundaryQuadraturePoints_elementBoundary, self.ebqe['x'], self.advectiveFluxBoundaryConditionsSetterDict[cj], self.diffusiveFluxBoundaryConditionsSetterDictDict[cj])) for cj in list(self.advectiveFluxBoundaryConditionsSetterDict.keys())])
self.coefficients.initializeGlobalExteriorElementBoundaryQuadrature(self.timeIntegration.t, self.ebqe) | Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points on global element boundaries.
This function should be called only when the mesh changes. | proteus/mprans/CLSVOF.py | calculateExteriorElementBoundaryQuadrature | zhang-alvin/cleanProteus | 0 | python | def calculateExteriorElementBoundaryQuadrature(self):
'\n Calculate the physical location and weights of the quadrature rules\n and the shape information at the quadrature points on global element boundaries.\n\n This function should be called only when the mesh changes.\n '
self.u[0].femSpace.elementMaps.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getValuesGlobalExteriorTrace(self.elementBoundaryQuadraturePoints, self.ebqe['x'])
self.fluxBoundaryConditionsObjectsDict = dict([(cj, FluxBoundaryConditions(self.mesh, self.nElementBoundaryQuadraturePoints_elementBoundary, self.ebqe['x'], self.advectiveFluxBoundaryConditionsSetterDict[cj], self.diffusiveFluxBoundaryConditionsSetterDictDict[cj])) for cj in list(self.advectiveFluxBoundaryConditionsSetterDict.keys())])
self.coefficients.initializeGlobalExteriorElementBoundaryQuadrature(self.timeIntegration.t, self.ebqe) | def calculateExteriorElementBoundaryQuadrature(self):
'\n Calculate the physical location and weights of the quadrature rules\n and the shape information at the quadrature points on global element boundaries.\n\n This function should be called only when the mesh changes.\n '
self.u[0].femSpace.elementMaps.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getValuesGlobalExteriorTrace(self.elementBoundaryQuadraturePoints, self.ebqe['x'])
self.fluxBoundaryConditionsObjectsDict = dict([(cj, FluxBoundaryConditions(self.mesh, self.nElementBoundaryQuadraturePoints_elementBoundary, self.ebqe['x'], self.advectiveFluxBoundaryConditionsSetterDict[cj], self.diffusiveFluxBoundaryConditionsSetterDictDict[cj])) for cj in list(self.advectiveFluxBoundaryConditionsSetterDict.keys())])
self.coefficients.initializeGlobalExteriorElementBoundaryQuadrature(self.timeIntegration.t, self.ebqe)<|docstring|>Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points on global element boundaries.
This function should be called only when the mesh changes.<|endoftext|> |
f4e6f3e7541521f392ec75891a89de4be382e474419abad47167ae758d1c71fc | def simplify_undirected_as_dataframe(df: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
'\n Simplify an undirected graph stored in a dataframe.\n u –– current node –– v becomes\n u –– v and path [u - current node - v] is saved\n for each node of degree 2, if the inputs have the same highway than the outputs,\n\n Parameters\n ----------\n df : pandas dataframe\n an edge list dataframe with the following columns:\n u, v undirected couple of nodes u –– v\n osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry\n\n Returns\n -------\n dataframe : pandas Dataframe\n simplified Dataframe of the undirected graph\n '
df.reset_index(inplace=True)
g = gt.Graph(directed=False)
osm_id = g.new_edge_property('string')
highway = g.new_edge_property('string')
level = g.new_edge_property('int')
lanes = g.new_edge_property('int')
width = g.new_edge_property('float')
bicycle = g.new_edge_property('bool')
bicycle_safety = g.new_edge_property('int')
foot = g.new_edge_property('bool')
foot_safety = g.new_edge_property('int')
max_speed = g.new_edge_property('int')
motorcar = g.new_edge_property('bool')
linestring = g.new_edge_property('python::object')
edgelist = df[['u', 'v', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry']].values
nodes_id = g.add_edge_list(edgelist, hashed=True, eprops=[osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, linestring])
e_path = g.new_ep('vector<int64_t>')
for e in g.edges():
e_path[e] = []
vs = g.get_vertices()
deg_2 = (g.get_out_degrees(vs) == 2)
logging.debug('selecting degree 2 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if deg_2[i]:
u = g.get_out_neighbors(v)[0]
w = g.get_out_neighbors(v)[1]
if (u != w):
(vu, vw) = (g.edge(v, u), g.edge(v, w))
if (highway[vu] == highway[vw]):
candidates.add(v)
logging.debug('found {} degree 2 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for candidate in candidates:
if (candidate in seen):
continue
seen.add(candidate)
u = g.get_out_neighbors(candidate)[0]
w = g.get_out_neighbors(candidate)[1]
uc = g.edge(u, candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_out_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
joined_linestring = join_linestrings(linestrings)
if (joined_linestring is None):
path = list(reversed(path))
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
joined_linestring = join_linestrings(linestrings)
e = g.add_edge(source=path[0], target=path[(- 1)])
linestring[e] = joined_linestring
e_path[e] = [int(nodes_id[node]) for node in path]
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[uc], highway[uc], level[uc], lanes[uc], width[uc], bicycle[uc], bicycle_safety[uc], foot[uc], foot_safety[uc], max_speed[uc], motorcar[uc])
else:
logging.error('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}', u, w, us, ws)
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 2 simplification not finished: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
logging.debug(' linestring path')
edges_tuples = []
for e in g.edges():
(source, target, path) = (nodes_id[e.source()], nodes_id[e.target()], e_path[e])
if (len(path) == 0):
path = [source, target]
else:
path = [int(i) for i in path]
e_tuples = (g.edge_index[e], source, target, path, osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e], linestring[e])
edges_tuples.append(e_tuples)
df_edges_simplified = pd.DataFrame.from_records(edges_tuples, index='edge_id', columns=['edge_id', 'u', 'v', 'path', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry'])
df_edges_simplified.osm_id = df_edges_simplified.osm_id.str.split('-').str[0]
df_edges_simplified = gpd.GeoDataFrame(df_edges_simplified, geometry='geometry')
df_edges_simplified.crs = df.crs
return df_edges_simplified | Simplify an undirected graph stored in a dataframe.
u –– current node –– v becomes
u –– v and path [u - current node - v] is saved
for each node of degree 2, if the inputs have the same highway than the outputs,
Parameters
----------
df : pandas dataframe
an edge list dataframe with the following columns:
u, v undirected couple of nodes u –– v
osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry
Returns
-------
dataframe : pandas Dataframe
simplified Dataframe of the undirected graph | policosm/geoNetworks/simplify.py | simplify_undirected_as_dataframe | ComplexCity/policosm | 6 | python | def simplify_undirected_as_dataframe(df: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
'\n Simplify an undirected graph stored in a dataframe.\n u –– current node –– v becomes\n u –– v and path [u - current node - v] is saved\n for each node of degree 2, if the inputs have the same highway than the outputs,\n\n Parameters\n ----------\n df : pandas dataframe\n an edge list dataframe with the following columns:\n u, v undirected couple of nodes u –– v\n osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry\n\n Returns\n -------\n dataframe : pandas Dataframe\n simplified Dataframe of the undirected graph\n '
df.reset_index(inplace=True)
g = gt.Graph(directed=False)
osm_id = g.new_edge_property('string')
highway = g.new_edge_property('string')
level = g.new_edge_property('int')
lanes = g.new_edge_property('int')
width = g.new_edge_property('float')
bicycle = g.new_edge_property('bool')
bicycle_safety = g.new_edge_property('int')
foot = g.new_edge_property('bool')
foot_safety = g.new_edge_property('int')
max_speed = g.new_edge_property('int')
motorcar = g.new_edge_property('bool')
linestring = g.new_edge_property('python::object')
edgelist = df[['u', 'v', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry']].values
nodes_id = g.add_edge_list(edgelist, hashed=True, eprops=[osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, linestring])
e_path = g.new_ep('vector<int64_t>')
for e in g.edges():
e_path[e] = []
vs = g.get_vertices()
deg_2 = (g.get_out_degrees(vs) == 2)
logging.debug('selecting degree 2 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if deg_2[i]:
u = g.get_out_neighbors(v)[0]
w = g.get_out_neighbors(v)[1]
if (u != w):
(vu, vw) = (g.edge(v, u), g.edge(v, w))
if (highway[vu] == highway[vw]):
candidates.add(v)
logging.debug('found {} degree 2 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for candidate in candidates:
if (candidate in seen):
continue
seen.add(candidate)
u = g.get_out_neighbors(candidate)[0]
w = g.get_out_neighbors(candidate)[1]
uc = g.edge(u, candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_out_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
joined_linestring = join_linestrings(linestrings)
if (joined_linestring is None):
path = list(reversed(path))
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
joined_linestring = join_linestrings(linestrings)
e = g.add_edge(source=path[0], target=path[(- 1)])
linestring[e] = joined_linestring
e_path[e] = [int(nodes_id[node]) for node in path]
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[uc], highway[uc], level[uc], lanes[uc], width[uc], bicycle[uc], bicycle_safety[uc], foot[uc], foot_safety[uc], max_speed[uc], motorcar[uc])
else:
logging.error('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}', u, w, us, ws)
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 2 simplification not finished: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
logging.debug(' linestring path')
edges_tuples = []
for e in g.edges():
(source, target, path) = (nodes_id[e.source()], nodes_id[e.target()], e_path[e])
if (len(path) == 0):
path = [source, target]
else:
path = [int(i) for i in path]
e_tuples = (g.edge_index[e], source, target, path, osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e], linestring[e])
edges_tuples.append(e_tuples)
df_edges_simplified = pd.DataFrame.from_records(edges_tuples, index='edge_id', columns=['edge_id', 'u', 'v', 'path', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry'])
df_edges_simplified.osm_id = df_edges_simplified.osm_id.str.split('-').str[0]
df_edges_simplified = gpd.GeoDataFrame(df_edges_simplified, geometry='geometry')
df_edges_simplified.crs = df.crs
return df_edges_simplified | def simplify_undirected_as_dataframe(df: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
'\n Simplify an undirected graph stored in a dataframe.\n u –– current node –– v becomes\n u –– v and path [u - current node - v] is saved\n for each node of degree 2, if the inputs have the same highway than the outputs,\n\n Parameters\n ----------\n df : pandas dataframe\n an edge list dataframe with the following columns:\n u, v undirected couple of nodes u –– v\n osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry\n\n Returns\n -------\n dataframe : pandas Dataframe\n simplified Dataframe of the undirected graph\n '
df.reset_index(inplace=True)
g = gt.Graph(directed=False)
osm_id = g.new_edge_property('string')
highway = g.new_edge_property('string')
level = g.new_edge_property('int')
lanes = g.new_edge_property('int')
width = g.new_edge_property('float')
bicycle = g.new_edge_property('bool')
bicycle_safety = g.new_edge_property('int')
foot = g.new_edge_property('bool')
foot_safety = g.new_edge_property('int')
max_speed = g.new_edge_property('int')
motorcar = g.new_edge_property('bool')
linestring = g.new_edge_property('python::object')
edgelist = df[['u', 'v', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry']].values
nodes_id = g.add_edge_list(edgelist, hashed=True, eprops=[osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, linestring])
e_path = g.new_ep('vector<int64_t>')
for e in g.edges():
e_path[e] = []
vs = g.get_vertices()
deg_2 = (g.get_out_degrees(vs) == 2)
logging.debug('selecting degree 2 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if deg_2[i]:
u = g.get_out_neighbors(v)[0]
w = g.get_out_neighbors(v)[1]
if (u != w):
(vu, vw) = (g.edge(v, u), g.edge(v, w))
if (highway[vu] == highway[vw]):
candidates.add(v)
logging.debug('found {} degree 2 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for candidate in candidates:
if (candidate in seen):
continue
seen.add(candidate)
u = g.get_out_neighbors(candidate)[0]
w = g.get_out_neighbors(candidate)[1]
uc = g.edge(u, candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_out_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
joined_linestring = join_linestrings(linestrings)
if (joined_linestring is None):
path = list(reversed(path))
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
joined_linestring = join_linestrings(linestrings)
e = g.add_edge(source=path[0], target=path[(- 1)])
linestring[e] = joined_linestring
e_path[e] = [int(nodes_id[node]) for node in path]
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[uc], highway[uc], level[uc], lanes[uc], width[uc], bicycle[uc], bicycle_safety[uc], foot[uc], foot_safety[uc], max_speed[uc], motorcar[uc])
else:
logging.error('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}', u, w, us, ws)
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 2 simplification not finished: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
logging.debug(' linestring path')
edges_tuples = []
for e in g.edges():
(source, target, path) = (nodes_id[e.source()], nodes_id[e.target()], e_path[e])
if (len(path) == 0):
path = [source, target]
else:
path = [int(i) for i in path]
e_tuples = (g.edge_index[e], source, target, path, osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e], linestring[e])
edges_tuples.append(e_tuples)
df_edges_simplified = pd.DataFrame.from_records(edges_tuples, index='edge_id', columns=['edge_id', 'u', 'v', 'path', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry'])
df_edges_simplified.osm_id = df_edges_simplified.osm_id.str.split('-').str[0]
df_edges_simplified = gpd.GeoDataFrame(df_edges_simplified, geometry='geometry')
df_edges_simplified.crs = df.crs
return df_edges_simplified<|docstring|>Simplify an undirected graph stored in a dataframe.
u –– current node –– v becomes
u –– v and path [u - current node - v] is saved
for each node of degree 2, if the inputs have the same highway than the outputs,
Parameters
----------
df : pandas dataframe
an edge list dataframe with the following columns:
u, v undirected couple of nodes u –– v
osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry
Returns
-------
dataframe : pandas Dataframe
simplified Dataframe of the undirected graph<|endoftext|> |
d8bd43963f135fbdec0d9b418cb8edb5c7002bc7d947a3320dca82e92dfcb5bd | def simplify_directed_as_dataframe(df: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
'\n Simplify a directed graph stored in a dataframe.\n u -> current node -> v becomes\n u -> v and path [u -> current node -> v] is saved\n for each node of degree 4 or 2, if the inputs have the same highway than the outputs,\n\n Parameters\n ----------\n df : pandas dataframe\n an edge list dataframe with the following columns:\n u, v directed couple of nodes u -> v\n osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry\n\n Returns\n -------\n dataframe : pandas Dataframe\n simplified Dataframe of the directed graph\n '
df.reset_index(inplace=True)
g = gt.Graph(directed=True)
osm_id = g.new_edge_property('string')
highway = g.new_edge_property('string')
level = g.new_edge_property('int')
lanes = g.new_edge_property('int')
width = g.new_edge_property('float')
bicycle = g.new_edge_property('bool')
bicycle_safety = g.new_edge_property('int')
foot = g.new_edge_property('bool')
foot_safety = g.new_edge_property('int')
max_speed = g.new_edge_property('int')
motorcar = g.new_edge_property('bool')
linestring = g.new_edge_property('python::object')
edgelist = df[['u', 'v', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry']].values
nodes_id = g.add_edge_list(edgelist, hashed=True, eprops=[osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, linestring])
e_path = g.new_ep('vector<int64_t>')
for e in g.edges():
e_path[e] = []
vs = g.get_vertices()
in_out_deg_2 = ((g.get_in_degrees(vs) == 2) & (g.get_out_degrees(vs) == 2))
logging.debug('selecting degree 4 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if in_out_deg_2[i]:
ns = list(set(g.get_all_neighbors(v)))
if (len(ns) == 2):
(u, w) = (ns[0], ns[1])
(uv, vw, wv, vu) = (g.edge(u, v), g.edge(v, w), g.edge(w, v), g.edge(v, u))
if ((highway[uv] == highway[vw]) and (highway[wv] == highway[vu])):
candidates.add(v)
logging.debug('found {} degree 4 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for (i, candidate) in enumerate(candidates):
if (i == 100000):
logging.debug('100000 degree 4 candidates')
if (candidate in seen):
continue
seen.add(candidate)
(u, w) = g.get_out_neighbors(candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
(cu, cw) = (g.edge(candidate, u), g.edge(candidate, w))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_out_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=u, t=w))
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 2: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 2: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
e = g.add_edge(source=u, target=w)
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[cw], highway[cw], level[cw], lanes[cw], width[cw], bicycle[cw], bicycle_safety[cw], foot[cw], foot_safety[cw], max_speed[cw], motorcar[cw])
e = g.add_edge(source=w, target=u)
path = (((([w] + list(reversed(ws))) + [candidate]) + us) + [u])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[cu], highway[cu], level[cu], lanes[cu], width[cu], bicycle[cu], bicycle_safety[cu], foot[cu], foot_safety[cu], max_speed[cu], motorcar[cu])
else:
logging.debug('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}'.format(u, w, candidate, us, ws))
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 4 simplification uncomplete: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
vs = g.get_vertices()
in_out_deg_1 = ((g.get_in_degrees(vs) == 1) & (g.get_out_degrees(vs) == 1))
logging.debug('selecting degree 2 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if in_out_deg_1[i]:
u = g.get_in_neighbors(v)[0]
w = g.get_out_neighbors(v)[0]
if (u != w):
(uv, vw) = (g.edge(u, v), g.edge(v, w))
if (highway[uv] == highway[vw]):
candidates.add(v)
logging.debug('found {} degree 2 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for candidate in candidates:
if (candidate in seen):
continue
seen.add(candidate)
u = g.get_in_neighbors(candidate)[0]
w = g.get_out_neighbors(candidate)[0]
uc = g.edge(u, candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_in_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
e = g.add_edge(source=u, target=w)
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[uc], highway[uc], level[uc], lanes[uc], width[uc], bicycle[uc], bicycle_safety[uc], foot[uc], foot_safety[uc], max_speed[uc], motorcar[uc])
else:
logging.error('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}', u, w, us, ws)
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 2 simplification not finished: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
logging.debug(' linestring path')
edges_tuples = []
for e in g.edges():
(source, target, path) = (nodes_id[e.source()], nodes_id[e.target()], e_path[e])
if (len(path) == 0):
path = [source, target]
else:
path = [int(i) for i in path]
e_tuples = (g.edge_index[e], source, target, path, osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e], linestring[e])
edges_tuples.append(e_tuples)
df_edges_simplified = pd.DataFrame.from_records(edges_tuples, index='edge_id', columns=['edge_id', 'u', 'v', 'path', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry'])
df_edges_simplified.osm_id = df_edges_simplified.osm_id.str.split('-').str[0]
df_edges_simplified = gpd.GeoDataFrame(df_edges_simplified, geometry='geometry')
df_edges_simplified.crs = df.crs
return df_edges_simplified | Simplify a directed graph stored in a dataframe.
u -> current node -> v becomes
u -> v and path [u -> current node -> v] is saved
for each node of degree 4 or 2, if the inputs have the same highway than the outputs,
Parameters
----------
df : pandas dataframe
an edge list dataframe with the following columns:
u, v directed couple of nodes u -> v
osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry
Returns
-------
dataframe : pandas Dataframe
simplified Dataframe of the directed graph | policosm/geoNetworks/simplify.py | simplify_directed_as_dataframe | ComplexCity/policosm | 6 | python | def simplify_directed_as_dataframe(df: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
'\n Simplify a directed graph stored in a dataframe.\n u -> current node -> v becomes\n u -> v and path [u -> current node -> v] is saved\n for each node of degree 4 or 2, if the inputs have the same highway than the outputs,\n\n Parameters\n ----------\n df : pandas dataframe\n an edge list dataframe with the following columns:\n u, v directed couple of nodes u -> v\n osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry\n\n Returns\n -------\n dataframe : pandas Dataframe\n simplified Dataframe of the directed graph\n '
df.reset_index(inplace=True)
g = gt.Graph(directed=True)
osm_id = g.new_edge_property('string')
highway = g.new_edge_property('string')
level = g.new_edge_property('int')
lanes = g.new_edge_property('int')
width = g.new_edge_property('float')
bicycle = g.new_edge_property('bool')
bicycle_safety = g.new_edge_property('int')
foot = g.new_edge_property('bool')
foot_safety = g.new_edge_property('int')
max_speed = g.new_edge_property('int')
motorcar = g.new_edge_property('bool')
linestring = g.new_edge_property('python::object')
edgelist = df[['u', 'v', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry']].values
nodes_id = g.add_edge_list(edgelist, hashed=True, eprops=[osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, linestring])
e_path = g.new_ep('vector<int64_t>')
for e in g.edges():
e_path[e] = []
vs = g.get_vertices()
in_out_deg_2 = ((g.get_in_degrees(vs) == 2) & (g.get_out_degrees(vs) == 2))
logging.debug('selecting degree 4 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if in_out_deg_2[i]:
ns = list(set(g.get_all_neighbors(v)))
if (len(ns) == 2):
(u, w) = (ns[0], ns[1])
(uv, vw, wv, vu) = (g.edge(u, v), g.edge(v, w), g.edge(w, v), g.edge(v, u))
if ((highway[uv] == highway[vw]) and (highway[wv] == highway[vu])):
candidates.add(v)
logging.debug('found {} degree 4 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for (i, candidate) in enumerate(candidates):
if (i == 100000):
logging.debug('100000 degree 4 candidates')
if (candidate in seen):
continue
seen.add(candidate)
(u, w) = g.get_out_neighbors(candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
(cu, cw) = (g.edge(candidate, u), g.edge(candidate, w))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_out_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=u, t=w))
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 2: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 2: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
e = g.add_edge(source=u, target=w)
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[cw], highway[cw], level[cw], lanes[cw], width[cw], bicycle[cw], bicycle_safety[cw], foot[cw], foot_safety[cw], max_speed[cw], motorcar[cw])
e = g.add_edge(source=w, target=u)
path = (((([w] + list(reversed(ws))) + [candidate]) + us) + [u])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[cu], highway[cu], level[cu], lanes[cu], width[cu], bicycle[cu], bicycle_safety[cu], foot[cu], foot_safety[cu], max_speed[cu], motorcar[cu])
else:
logging.debug('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}'.format(u, w, candidate, us, ws))
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 4 simplification uncomplete: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
vs = g.get_vertices()
in_out_deg_1 = ((g.get_in_degrees(vs) == 1) & (g.get_out_degrees(vs) == 1))
logging.debug('selecting degree 2 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if in_out_deg_1[i]:
u = g.get_in_neighbors(v)[0]
w = g.get_out_neighbors(v)[0]
if (u != w):
(uv, vw) = (g.edge(u, v), g.edge(v, w))
if (highway[uv] == highway[vw]):
candidates.add(v)
logging.debug('found {} degree 2 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for candidate in candidates:
if (candidate in seen):
continue
seen.add(candidate)
u = g.get_in_neighbors(candidate)[0]
w = g.get_out_neighbors(candidate)[0]
uc = g.edge(u, candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_in_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
e = g.add_edge(source=u, target=w)
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[uc], highway[uc], level[uc], lanes[uc], width[uc], bicycle[uc], bicycle_safety[uc], foot[uc], foot_safety[uc], max_speed[uc], motorcar[uc])
else:
logging.error('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}', u, w, us, ws)
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 2 simplification not finished: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
logging.debug(' linestring path')
edges_tuples = []
for e in g.edges():
(source, target, path) = (nodes_id[e.source()], nodes_id[e.target()], e_path[e])
if (len(path) == 0):
path = [source, target]
else:
path = [int(i) for i in path]
e_tuples = (g.edge_index[e], source, target, path, osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e], linestring[e])
edges_tuples.append(e_tuples)
df_edges_simplified = pd.DataFrame.from_records(edges_tuples, index='edge_id', columns=['edge_id', 'u', 'v', 'path', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry'])
df_edges_simplified.osm_id = df_edges_simplified.osm_id.str.split('-').str[0]
df_edges_simplified = gpd.GeoDataFrame(df_edges_simplified, geometry='geometry')
df_edges_simplified.crs = df.crs
return df_edges_simplified | def simplify_directed_as_dataframe(df: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
'\n Simplify a directed graph stored in a dataframe.\n u -> current node -> v becomes\n u -> v and path [u -> current node -> v] is saved\n for each node of degree 4 or 2, if the inputs have the same highway than the outputs,\n\n Parameters\n ----------\n df : pandas dataframe\n an edge list dataframe with the following columns:\n u, v directed couple of nodes u -> v\n osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry\n\n Returns\n -------\n dataframe : pandas Dataframe\n simplified Dataframe of the directed graph\n '
df.reset_index(inplace=True)
g = gt.Graph(directed=True)
osm_id = g.new_edge_property('string')
highway = g.new_edge_property('string')
level = g.new_edge_property('int')
lanes = g.new_edge_property('int')
width = g.new_edge_property('float')
bicycle = g.new_edge_property('bool')
bicycle_safety = g.new_edge_property('int')
foot = g.new_edge_property('bool')
foot_safety = g.new_edge_property('int')
max_speed = g.new_edge_property('int')
motorcar = g.new_edge_property('bool')
linestring = g.new_edge_property('python::object')
edgelist = df[['u', 'v', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry']].values
nodes_id = g.add_edge_list(edgelist, hashed=True, eprops=[osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, linestring])
e_path = g.new_ep('vector<int64_t>')
for e in g.edges():
e_path[e] = []
vs = g.get_vertices()
in_out_deg_2 = ((g.get_in_degrees(vs) == 2) & (g.get_out_degrees(vs) == 2))
logging.debug('selecting degree 4 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if in_out_deg_2[i]:
ns = list(set(g.get_all_neighbors(v)))
if (len(ns) == 2):
(u, w) = (ns[0], ns[1])
(uv, vw, wv, vu) = (g.edge(u, v), g.edge(v, w), g.edge(w, v), g.edge(v, u))
if ((highway[uv] == highway[vw]) and (highway[wv] == highway[vu])):
candidates.add(v)
logging.debug('found {} degree 4 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for (i, candidate) in enumerate(candidates):
if (i == 100000):
logging.debug('100000 degree 4 candidates')
if (candidate in seen):
continue
seen.add(candidate)
(u, w) = g.get_out_neighbors(candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
(cu, cw) = (g.edge(candidate, u), g.edge(candidate, w))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_out_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=u, t=w))
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 2: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 2: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
e = g.add_edge(source=u, target=w)
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[cw], highway[cw], level[cw], lanes[cw], width[cw], bicycle[cw], bicycle_safety[cw], foot[cw], foot_safety[cw], max_speed[cw], motorcar[cw])
e = g.add_edge(source=w, target=u)
path = (((([w] + list(reversed(ws))) + [candidate]) + us) + [u])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[cu], highway[cu], level[cu], lanes[cu], width[cu], bicycle[cu], bicycle_safety[cu], foot[cu], foot_safety[cu], max_speed[cu], motorcar[cu])
else:
logging.debug('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}'.format(u, w, candidate, us, ws))
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 4 simplification uncomplete: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
vs = g.get_vertices()
in_out_deg_1 = ((g.get_in_degrees(vs) == 1) & (g.get_out_degrees(vs) == 1))
logging.debug('selecting degree 2 candidates')
candidates = set()
for (i, v) in enumerate(vs):
if in_out_deg_1[i]:
u = g.get_in_neighbors(v)[0]
w = g.get_out_neighbors(v)[0]
if (u != w):
(uv, vw) = (g.edge(u, v), g.edge(v, w))
if (highway[uv] == highway[vw]):
candidates.add(v)
logging.debug('found {} degree 2 candidates to simplify'.format(len(candidates)))
seen = set()
unregister_candidates = set()
for candidate in candidates:
if (candidate in seen):
continue
seen.add(candidate)
u = g.get_in_neighbors(candidate)[0]
w = g.get_out_neighbors(candidate)[0]
uc = g.edge(u, candidate)
(is_u_fringe, is_w_fringe) = ((u not in candidates), (w not in candidates))
us = []
ws = []
while (not is_u_fringe):
seen.add(u)
us.append(u)
neighbors = set(g.get_in_neighbors(u))
neighbors -= seen
if (len(neighbors) > 0):
u = neighbors.pop()
is_u_fringe = (u not in candidates)
elif (u == w):
us.pop((- 1))
u = us.pop((- 1))
unregister_candidates.add(u)
unregister_candidates.add(w)
is_u_fringe = True
is_w_fringe = True
g.remove_edge(g.edge(s=w, t=u))
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
while (not is_w_fringe):
seen.add(w)
ws.append(w)
neighbors = set(g.get_out_neighbors(w))
neighbors -= seen
if (len(neighbors) > 0):
w = neighbors.pop()
is_w_fringe = (w not in candidates)
else:
logging.debug('degree 1: we got here somehow {} {} {} {}', candidate, u, v, g.get_all_neighbors(candidate))
break
if (is_u_fringe and is_w_fringe):
e = g.add_edge(source=u, target=w)
path = (((([u] + list(reversed(us))) + [candidate]) + ws) + [w])
e_path[e] = [int(nodes_id[node]) for node in path]
linestrings = [linestring[g.edge(a, b)] for (a, b) in pairwise(path)]
linestring[e] = join_linestrings(linestrings)
(osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e]) = (osm_id[uc], highway[uc], level[uc], lanes[uc], width[uc], bicycle[uc], bicycle_safety[uc], foot[uc], foot_safety[uc], max_speed[uc], motorcar[uc])
else:
logging.error('unexpected behavior, source={0}, target={1}, candidate={2}, us={3}, ws={4}', u, w, us, ws)
unseen = (candidates - seen)
if (len(unseen) > 0):
logging.debug('Network scan after degree 2 simplification not finished: candidates {0} have not been examined'.format(unseen))
candidates -= unregister_candidates
g.remove_vertex(list(candidates))
logging.debug(' linestring path')
edges_tuples = []
for e in g.edges():
(source, target, path) = (nodes_id[e.source()], nodes_id[e.target()], e_path[e])
if (len(path) == 0):
path = [source, target]
else:
path = [int(i) for i in path]
e_tuples = (g.edge_index[e], source, target, path, osm_id[e], highway[e], level[e], lanes[e], width[e], bicycle[e], bicycle_safety[e], foot[e], foot_safety[e], max_speed[e], motorcar[e], linestring[e])
edges_tuples.append(e_tuples)
df_edges_simplified = pd.DataFrame.from_records(edges_tuples, index='edge_id', columns=['edge_id', 'u', 'v', 'path', 'osm_id', 'highway', 'level', 'lanes', 'width', 'bicycle', 'bicycle_safety', 'foot', 'foot_safety', 'max_speed', 'motorcar', 'geometry'])
df_edges_simplified.osm_id = df_edges_simplified.osm_id.str.split('-').str[0]
df_edges_simplified = gpd.GeoDataFrame(df_edges_simplified, geometry='geometry')
df_edges_simplified.crs = df.crs
return df_edges_simplified<|docstring|>Simplify a directed graph stored in a dataframe.
u -> current node -> v becomes
u -> v and path [u -> current node -> v] is saved
for each node of degree 4 or 2, if the inputs have the same highway than the outputs,
Parameters
----------
df : pandas dataframe
an edge list dataframe with the following columns:
u, v directed couple of nodes u -> v
osm_id, highway, level, lanes, width, bicycle, bicycle_safety, foot, foot_safety, max_speed, motorcar, geometry
Returns
-------
dataframe : pandas Dataframe
simplified Dataframe of the directed graph<|endoftext|> |
67b99d68aab9fac5961bc678f5f1d35761e5f49bd56a54f86c405bb412a8e1e6 | def test_00_env_pg(self):
'\n [administration] 00: PostgreSQL instance is up & running\n '
conn = connector(host=ENV['pg']['socket_dir'], port=ENV['pg']['port'], user=ENV['pg']['user'], password=ENV['pg']['password'], database='postgres')
try:
conn.connect()
conn.close()
global XSESSION
XSESSION = self._temboard_login()
assert True
except error:
assert False | [administration] 00: PostgreSQL instance is up & running | test/legacy/test_monitoring.py | test_00_env_pg | pgiraud/temboard-agent | 0 | python | def test_00_env_pg(self):
'\n \n '
conn = connector(host=ENV['pg']['socket_dir'], port=ENV['pg']['port'], user=ENV['pg']['user'], password=ENV['pg']['password'], database='postgres')
try:
conn.connect()
conn.close()
global XSESSION
XSESSION = self._temboard_login()
assert True
except error:
assert False | def test_00_env_pg(self):
'\n \n '
conn = connector(host=ENV['pg']['socket_dir'], port=ENV['pg']['port'], user=ENV['pg']['user'], password=ENV['pg']['password'], database='postgres')
try:
conn.connect()
conn.close()
global XSESSION
XSESSION = self._temboard_login()
assert True
except error:
assert False<|docstring|>[administration] 00: PostgreSQL instance is up & running<|endoftext|> |
7db759049ef49c1cded5450e96c9bed232aa844e3398ac0c34756b924bae8f15 | def test_01_monitoring_session(self):
'\n [monitoring] 01: GET /monitoring/probe/sessions : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/sessions' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 01: GET /monitoring/probe/sessions : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_01_monitoring_session | pgiraud/temboard-agent | 0 | python | def test_01_monitoring_session(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/sessions' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_01_monitoring_session(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/sessions' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 01: GET /monitoring/probe/sessions : Check HTTP code returned is 200<|endoftext|> |
f9d7600e93beb122690a92ff8bcd8d2cfac41a810e6cff0ef1eaa8a4c1d5f984 | def test_02_monitoring_xacts(self):
'\n [monitoring] 02: GET /monitoring/probe/xacts : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/xacts' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 02: GET /monitoring/probe/xacts : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_02_monitoring_xacts | pgiraud/temboard-agent | 0 | python | def test_02_monitoring_xacts(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/xacts' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_02_monitoring_xacts(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/xacts' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 02: GET /monitoring/probe/xacts : Check HTTP code returned is 200<|endoftext|> |
c8c2f48491658a5fb57197b7f245ee9a68802ca0ad2cdc0c7737dd6e4734a324 | def test_03_monitoring_locks(self):
'\n [monitoring] 03: GET /monitoring/probe/locks : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/locks' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 03: GET /monitoring/probe/locks : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_03_monitoring_locks | pgiraud/temboard-agent | 0 | python | def test_03_monitoring_locks(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/locks' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_03_monitoring_locks(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/locks' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 03: GET /monitoring/probe/locks : Check HTTP code returned is 200<|endoftext|> |
ae2ef9047e351acd7f56207ff9a6bbf29fed6c304ec0491960dde0026eabbe26 | def test_04_monitoring_blocks(self):
'\n [monitoring] 04: GET /monitoring/probe/blocks : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/blocks' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 04: GET /monitoring/probe/blocks : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_04_monitoring_blocks | pgiraud/temboard-agent | 0 | python | def test_04_monitoring_blocks(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/blocks' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_04_monitoring_blocks(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/blocks' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 04: GET /monitoring/probe/blocks : Check HTTP code returned is 200<|endoftext|> |
8ee3886fa714c7c9bd4d8c57b09e2f26b9da1f4ac9a0a6ffd2cffb2ba2e71ade | def test_05_monitoring_bgwriter(self):
'\n [monitoring] 05: GET /monitoring/probe/bgwriter : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/bgwriter' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 05: GET /monitoring/probe/bgwriter : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_05_monitoring_bgwriter | pgiraud/temboard-agent | 0 | python | def test_05_monitoring_bgwriter(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/bgwriter' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_05_monitoring_bgwriter(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/bgwriter' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 05: GET /monitoring/probe/bgwriter : Check HTTP code returned is 200<|endoftext|> |
6916a916b649e2a58c7d001f3830af4e7b67236ad6661079457ed4543b355b94 | def test_06_monitoring_db_size(self):
'\n [monitoring] 06: GET /monitoring/probe/db_size : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/db_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 06: GET /monitoring/probe/db_size : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_06_monitoring_db_size | pgiraud/temboard-agent | 0 | python | def test_06_monitoring_db_size(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/db_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_06_monitoring_db_size(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/db_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 06: GET /monitoring/probe/db_size : Check HTTP code returned is 200<|endoftext|> |
557bb977fdb826dd02ba5baea89f54469b457683d07a3441aca39bcce3419372 | def test_07_monitoring_tblspc_size(self):
'\n [monitoring] 07: GET /monitoring/probe/tblspc_size : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/tblspc_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 07: GET /monitoring/probe/tblspc_size : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_07_monitoring_tblspc_size | pgiraud/temboard-agent | 0 | python | def test_07_monitoring_tblspc_size(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/tblspc_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_07_monitoring_tblspc_size(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/tblspc_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 07: GET /monitoring/probe/tblspc_size : Check HTTP code returned is 200<|endoftext|> |
d556ee1ae66c1690026012d6bfeceb1a509155ea896919d5319abc1ee1eca75a | def test_08_monitoring_filesystems_size(self):
'\n [monitoring] 08: GET /monitoring/probe/filesystems_size : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/filesystems_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 08: GET /monitoring/probe/filesystems_size : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_08_monitoring_filesystems_size | pgiraud/temboard-agent | 0 | python | def test_08_monitoring_filesystems_size(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/filesystems_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_08_monitoring_filesystems_size(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/filesystems_size' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 08: GET /monitoring/probe/filesystems_size : Check HTTP code returned is 200<|endoftext|> |
7a1cc128798f2eda8a98066674f94b6fb94bbb8694e254b32f9676d1f4ee5dd2 | def test_09_monitoring_cpu(self):
'\n [monitoring] 09: GET /monitoring/probe/cpu : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/cpu' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 09: GET /monitoring/probe/cpu : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_09_monitoring_cpu | pgiraud/temboard-agent | 0 | python | def test_09_monitoring_cpu(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/cpu' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_09_monitoring_cpu(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/cpu' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 09: GET /monitoring/probe/cpu : Check HTTP code returned is 200<|endoftext|> |
93804634f84ea6f811c12219e3c2a6662671d85ba2cb3c392e36722b26bc0e7a | def test_10_monitoring_process(self):
'\n [monitoring] 10: GET /monitoring/probe/process : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/process' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 10: GET /monitoring/probe/process : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_10_monitoring_process | pgiraud/temboard-agent | 0 | python | def test_10_monitoring_process(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/process' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_10_monitoring_process(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/process' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 10: GET /monitoring/probe/process : Check HTTP code returned is 200<|endoftext|> |
56aff02281619c311e909b42a9499d90f49d4d975f5fc9e9a8f34ed9be950c87 | def test_11_monitoring_memory(self):
'\n [monitoring] 11: GET /monitoring/probe/memory : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/memory' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 11: GET /monitoring/probe/memory : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_11_monitoring_memory | pgiraud/temboard-agent | 0 | python | def test_11_monitoring_memory(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/memory' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_11_monitoring_memory(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/memory' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 11: GET /monitoring/probe/memory : Check HTTP code returned is 200<|endoftext|> |
d7c400de749f682362bf2b256de32db61bf820e191301d977052ce6d0ed0734a | def test_12_monitoring_loadavg(self):
'\n [monitoring] 12: GET /monitoring/probe/loadavg : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/loadavg' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 12: GET /monitoring/probe/loadavg : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_12_monitoring_loadavg | pgiraud/temboard-agent | 0 | python | def test_12_monitoring_loadavg(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/loadavg' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_12_monitoring_loadavg(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/loadavg' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 12: GET /monitoring/probe/loadavg : Check HTTP code returned is 200<|endoftext|> |
8e9ad4a42be36775dec537ca2f4e1e53520f7d324db78583fa52b6a130b664ce | def test_13_monitoring_wal_files(self):
'\n [monitoring] 13: GET /monitoring/probe/wal_files : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/wal_files' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 13: GET /monitoring/probe/wal_files : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_13_monitoring_wal_files | pgiraud/temboard-agent | 0 | python | def test_13_monitoring_wal_files(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/wal_files' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_13_monitoring_wal_files(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/wal_files' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 13: GET /monitoring/probe/wal_files : Check HTTP code returned is 200<|endoftext|> |
e022a2c68e2021cdcf604c735a0e5aacf982707bbaefcbe3b5c3425734ca796e | def test_14_monitoring_replication(self):
'\n [monitoring] 14: GET /monitoring/probe/replication : Check HTTP code returned is 200\n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/replication' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | [monitoring] 14: GET /monitoring/probe/replication : Check HTTP code returned is 200 | test/legacy/test_monitoring.py | test_14_monitoring_replication | pgiraud/temboard-agent | 0 | python | def test_14_monitoring_replication(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/replication' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200) | def test_14_monitoring_replication(self):
'\n \n '
status = 0
try:
(status, res) = temboard_request(ENV['agent']['ssl_cert_file'], method='GET', url=('https://%s:%s/monitoring/probe/replication' % (ENV['agent']['host'], ENV['agent']['port'])), headers={'Content-type': 'application/json', 'X-Session': XSESSION})
except HTTPError as e:
status = e.code
assert (status == 200)<|docstring|>[monitoring] 14: GET /monitoring/probe/replication : Check HTTP code returned is 200<|endoftext|> |
6f28605a3c4ab7e2b72fbd0828018ebd78f8a363586f3eafd69bf11c0afa75c2 | def unfits(fn, pandas=False):
'Returns numpy record array from fits catalog file fn\n\n\tArgs:\n\t\tfn (str): filename of fits file to load\n\t\tpandas (bool): If True, return pandas DataFrame instead of an array\n\n\tReturns:\n\t\t(np.array):\n\t'
if pandas:
astropy.table.Table.read(fn, format='fits').to_pandas()
else:
with fits.open(fn) as hdul:
data = hdul[1].data
return np.array(data, dtype=data.dtype) | Returns numpy record array from fits catalog file fn
Args:
fn (str): filename of fits file to load
pandas (bool): If True, return pandas DataFrame instead of an array
Returns:
(np.array): | paltas/Sources/cosmos.py | unfits | swagnercarena/paltas | 5 | python | def unfits(fn, pandas=False):
'Returns numpy record array from fits catalog file fn\n\n\tArgs:\n\t\tfn (str): filename of fits file to load\n\t\tpandas (bool): If True, return pandas DataFrame instead of an array\n\n\tReturns:\n\t\t(np.array):\n\t'
if pandas:
astropy.table.Table.read(fn, format='fits').to_pandas()
else:
with fits.open(fn) as hdul:
data = hdul[1].data
return np.array(data, dtype=data.dtype) | def unfits(fn, pandas=False):
'Returns numpy record array from fits catalog file fn\n\n\tArgs:\n\t\tfn (str): filename of fits file to load\n\t\tpandas (bool): If True, return pandas DataFrame instead of an array\n\n\tReturns:\n\t\t(np.array):\n\t'
if pandas:
astropy.table.Table.read(fn, format='fits').to_pandas()
else:
with fits.open(fn) as hdul:
data = hdul[1].data
return np.array(data, dtype=data.dtype)<|docstring|>Returns numpy record array from fits catalog file fn
Args:
fn (str): filename of fits file to load
pandas (bool): If True, return pandas DataFrame instead of an array
Returns:
(np.array):<|endoftext|> |
975e8df3926832ea640b5784cc9509c0173f375083130e6df5efcfbc9d45b335 | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = np.ones(len(self), dtype=np.bool_)
faintest_apparent_mag = self.source_parameters['faintest_apparent_mag']
minimum_size_in_pixels = self.source_parameters['minimum_size_in_pixels']
max_z = self.source_parameters['max_z']
min_flux_radius = self.source_parameters['min_flux_radius']
if (faintest_apparent_mag is not None):
is_ok &= (self.catalog['mag_auto'] < faintest_apparent_mag)
if (minimum_size_in_pixels is not None):
min_size = np.minimum(self.catalog['size_x'], self.catalog['size_y'])
is_ok &= (min_size >= minimum_size_in_pixels)
if (max_z is not None):
is_ok &= (self.catalog['z'] < max_z)
if (min_flux_radius is not None):
is_ok &= (self.catalog['flux_radius'] > min_flux_radius)
return is_ok | Return a boolean mask of the sources that pass the source
parameter cuts.
Returns:
(np.array): Array of bools of catalog indices to use for
sampling. | paltas/Sources/cosmos.py | _passes_cuts | swagnercarena/paltas | 5 | python | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = np.ones(len(self), dtype=np.bool_)
faintest_apparent_mag = self.source_parameters['faintest_apparent_mag']
minimum_size_in_pixels = self.source_parameters['minimum_size_in_pixels']
max_z = self.source_parameters['max_z']
min_flux_radius = self.source_parameters['min_flux_radius']
if (faintest_apparent_mag is not None):
is_ok &= (self.catalog['mag_auto'] < faintest_apparent_mag)
if (minimum_size_in_pixels is not None):
min_size = np.minimum(self.catalog['size_x'], self.catalog['size_y'])
is_ok &= (min_size >= minimum_size_in_pixels)
if (max_z is not None):
is_ok &= (self.catalog['z'] < max_z)
if (min_flux_radius is not None):
is_ok &= (self.catalog['flux_radius'] > min_flux_radius)
return is_ok | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = np.ones(len(self), dtype=np.bool_)
faintest_apparent_mag = self.source_parameters['faintest_apparent_mag']
minimum_size_in_pixels = self.source_parameters['minimum_size_in_pixels']
max_z = self.source_parameters['max_z']
min_flux_radius = self.source_parameters['min_flux_radius']
if (faintest_apparent_mag is not None):
is_ok &= (self.catalog['mag_auto'] < faintest_apparent_mag)
if (minimum_size_in_pixels is not None):
min_size = np.minimum(self.catalog['size_x'], self.catalog['size_y'])
is_ok &= (min_size >= minimum_size_in_pixels)
if (max_z is not None):
is_ok &= (self.catalog['z'] < max_z)
if (min_flux_radius is not None):
is_ok &= (self.catalog['flux_radius'] > min_flux_radius)
return is_ok<|docstring|>Return a boolean mask of the sources that pass the source
parameter cuts.
Returns:
(np.array): Array of bools of catalog indices to use for
sampling.<|endoftext|> |
97cb1265c89d3bf67530875908ed9b39cc58b941509a9ddaf363ccbb4d2c4119 | def sample_indices(self, n_galaxies):
'Return n_galaxies array of catalog indices to sample\n\n\t\tArgs:\n\t\t\tn_galaxies (int): Number of indices to return\n\n\t\tReturns:\n\t\t\t(np.array): Array of ints of catalog indices to sample.\n\n\t\tNotes:\n\t\t\tThe minimum apparent magnitude, minimum size in pixels, and\n\t\t\tminimum redshift are all set by the source parameters dict.\n\t\t'
is_ok = self._passes_cuts()
return np.random.choice(np.where(is_ok)[0], size=n_galaxies, replace=True) | Return n_galaxies array of catalog indices to sample
Args:
n_galaxies (int): Number of indices to return
Returns:
(np.array): Array of ints of catalog indices to sample.
Notes:
The minimum apparent magnitude, minimum size in pixels, and
minimum redshift are all set by the source parameters dict. | paltas/Sources/cosmos.py | sample_indices | swagnercarena/paltas | 5 | python | def sample_indices(self, n_galaxies):
'Return n_galaxies array of catalog indices to sample\n\n\t\tArgs:\n\t\t\tn_galaxies (int): Number of indices to return\n\n\t\tReturns:\n\t\t\t(np.array): Array of ints of catalog indices to sample.\n\n\t\tNotes:\n\t\t\tThe minimum apparent magnitude, minimum size in pixels, and\n\t\t\tminimum redshift are all set by the source parameters dict.\n\t\t'
is_ok = self._passes_cuts()
return np.random.choice(np.where(is_ok)[0], size=n_galaxies, replace=True) | def sample_indices(self, n_galaxies):
'Return n_galaxies array of catalog indices to sample\n\n\t\tArgs:\n\t\t\tn_galaxies (int): Number of indices to return\n\n\t\tReturns:\n\t\t\t(np.array): Array of ints of catalog indices to sample.\n\n\t\tNotes:\n\t\t\tThe minimum apparent magnitude, minimum size in pixels, and\n\t\t\tminimum redshift are all set by the source parameters dict.\n\t\t'
is_ok = self._passes_cuts()
return np.random.choice(np.where(is_ok)[0], size=n_galaxies, replace=True)<|docstring|>Return n_galaxies array of catalog indices to sample
Args:
n_galaxies (int): Number of indices to return
Returns:
(np.array): Array of ints of catalog indices to sample.
Notes:
The minimum apparent magnitude, minimum size in pixels, and
minimum redshift are all set by the source parameters dict.<|endoftext|> |
cd9f83d80636bece0d6a68210649bf8e2d5ddf3fb7d32b2334a09360dadd95ea | @staticmethod
def _file_number(fn):
'Return integer X in blah_nX.fits filename fn.\n\t\tX can be more than one digit, not necessarily zero padded.\n\t\t'
return int(str(fn).split('_n')[(- 1)].split('.')[0]) | Return integer X in blah_nX.fits filename fn.
X can be more than one digit, not necessarily zero padded. | paltas/Sources/cosmos.py | _file_number | swagnercarena/paltas | 5 | python | @staticmethod
def _file_number(fn):
'Return integer X in blah_nX.fits filename fn.\n\t\tX can be more than one digit, not necessarily zero padded.\n\t\t'
return int(str(fn).split('_n')[(- 1)].split('.')[0]) | @staticmethod
def _file_number(fn):
'Return integer X in blah_nX.fits filename fn.\n\t\tX can be more than one digit, not necessarily zero padded.\n\t\t'
return int(str(fn).split('_n')[(- 1)].split('.')[0])<|docstring|>Return integer X in blah_nX.fits filename fn.
X can be more than one digit, not necessarily zero padded.<|endoftext|> |
9d3ec6e492ffb5adb11c023acd0979651922be8eefd2c2d813fad31b1f8cfc6c | def iter_image_and_metadata_bulk(self, message=''):
'Yields the image array and metadata for all of the images\n\t\tin the catalog.\n\n\t\tArgs:\n\t\t\tmessage (str): If the iterator uses tqdm, this message\n\t\t\t\twill be displayed.\n\n\t\tReturns:\n\t\t\t(generator): A generator that can be iterated over to give\n\t\t\tlenstronomy kwargs.\n\n\t\tNotes:\n\t\t\tThis will read the fits files.\n\t\t'
catalog_i = 0
_pattern = f'real_galaxy_images_23.5_n*.fits'
files = list(sorted(self.folder.glob(_pattern), key=self._file_number))
for fn in tqdm(files, desc=message):
with fits.open(fn) as hdul:
for img in hdul:
(yield (img.data, self.catalog[catalog_i]))
catalog_i += 1 | Yields the image array and metadata for all of the images
in the catalog.
Args:
message (str): If the iterator uses tqdm, this message
will be displayed.
Returns:
(generator): A generator that can be iterated over to give
lenstronomy kwargs.
Notes:
This will read the fits files. | paltas/Sources/cosmos.py | iter_image_and_metadata_bulk | swagnercarena/paltas | 5 | python | def iter_image_and_metadata_bulk(self, message=):
'Yields the image array and metadata for all of the images\n\t\tin the catalog.\n\n\t\tArgs:\n\t\t\tmessage (str): If the iterator uses tqdm, this message\n\t\t\t\twill be displayed.\n\n\t\tReturns:\n\t\t\t(generator): A generator that can be iterated over to give\n\t\t\tlenstronomy kwargs.\n\n\t\tNotes:\n\t\t\tThis will read the fits files.\n\t\t'
catalog_i = 0
_pattern = f'real_galaxy_images_23.5_n*.fits'
files = list(sorted(self.folder.glob(_pattern), key=self._file_number))
for fn in tqdm(files, desc=message):
with fits.open(fn) as hdul:
for img in hdul:
(yield (img.data, self.catalog[catalog_i]))
catalog_i += 1 | def iter_image_and_metadata_bulk(self, message=):
'Yields the image array and metadata for all of the images\n\t\tin the catalog.\n\n\t\tArgs:\n\t\t\tmessage (str): If the iterator uses tqdm, this message\n\t\t\t\twill be displayed.\n\n\t\tReturns:\n\t\t\t(generator): A generator that can be iterated over to give\n\t\t\tlenstronomy kwargs.\n\n\t\tNotes:\n\t\t\tThis will read the fits files.\n\t\t'
catalog_i = 0
_pattern = f'real_galaxy_images_23.5_n*.fits'
files = list(sorted(self.folder.glob(_pattern), key=self._file_number))
for fn in tqdm(files, desc=message):
with fits.open(fn) as hdul:
for img in hdul:
(yield (img.data, self.catalog[catalog_i]))
catalog_i += 1<|docstring|>Yields the image array and metadata for all of the images
in the catalog.
Args:
message (str): If the iterator uses tqdm, this message
will be displayed.
Returns:
(generator): A generator that can be iterated over to give
lenstronomy kwargs.
Notes:
This will read the fits files.<|endoftext|> |
785c6d6ac637cc697cf71f9478cbf4c20eca6a48b9327da1ee11fc2e66a4c634 | def image_and_metadata(self, catalog_i):
'Returns the image array and metadata for one galaxy\n\n\t\tArgs:\n\t\t\tcatalog_i (int): The catalog index\n\n\t\tReturns:\n\t\t\t([np.array, np.void]) A numpy array containing the image\n\t\t\tmetadata and a numpy void type that acts as a dictionary with\n\t\t\tthe metadata.\n\n\t\tNotes:\n\t\t\tThis will read the numpy files made during initialization. This is\n\t\t\tmuch faster on average than going for the fits files.\n\t\t'
img = np.load(str((self.npy_files_path / ('img_%d.npy' % catalog_i))))
smoothing_sigma = self.source_parameters['smoothing_sigma']
if (smoothing_sigma > 0):
img = scipy.ndimage.gaussian_filter(img, sigma=(smoothing_sigma / HUBBLE_ACS_PIXEL_WIDTH))
return (img, self.catalog[catalog_i]) | Returns the image array and metadata for one galaxy
Args:
catalog_i (int): The catalog index
Returns:
([np.array, np.void]) A numpy array containing the image
metadata and a numpy void type that acts as a dictionary with
the metadata.
Notes:
This will read the numpy files made during initialization. This is
much faster on average than going for the fits files. | paltas/Sources/cosmos.py | image_and_metadata | swagnercarena/paltas | 5 | python | def image_and_metadata(self, catalog_i):
'Returns the image array and metadata for one galaxy\n\n\t\tArgs:\n\t\t\tcatalog_i (int): The catalog index\n\n\t\tReturns:\n\t\t\t([np.array, np.void]) A numpy array containing the image\n\t\t\tmetadata and a numpy void type that acts as a dictionary with\n\t\t\tthe metadata.\n\n\t\tNotes:\n\t\t\tThis will read the numpy files made during initialization. This is\n\t\t\tmuch faster on average than going for the fits files.\n\t\t'
img = np.load(str((self.npy_files_path / ('img_%d.npy' % catalog_i))))
smoothing_sigma = self.source_parameters['smoothing_sigma']
if (smoothing_sigma > 0):
img = scipy.ndimage.gaussian_filter(img, sigma=(smoothing_sigma / HUBBLE_ACS_PIXEL_WIDTH))
return (img, self.catalog[catalog_i]) | def image_and_metadata(self, catalog_i):
'Returns the image array and metadata for one galaxy\n\n\t\tArgs:\n\t\t\tcatalog_i (int): The catalog index\n\n\t\tReturns:\n\t\t\t([np.array, np.void]) A numpy array containing the image\n\t\t\tmetadata and a numpy void type that acts as a dictionary with\n\t\t\tthe metadata.\n\n\t\tNotes:\n\t\t\tThis will read the numpy files made during initialization. This is\n\t\t\tmuch faster on average than going for the fits files.\n\t\t'
img = np.load(str((self.npy_files_path / ('img_%d.npy' % catalog_i))))
smoothing_sigma = self.source_parameters['smoothing_sigma']
if (smoothing_sigma > 0):
img = scipy.ndimage.gaussian_filter(img, sigma=(smoothing_sigma / HUBBLE_ACS_PIXEL_WIDTH))
return (img, self.catalog[catalog_i])<|docstring|>Returns the image array and metadata for one galaxy
Args:
catalog_i (int): The catalog index
Returns:
([np.array, np.void]) A numpy array containing the image
metadata and a numpy void type that acts as a dictionary with
the metadata.
Notes:
This will read the numpy files made during initialization. This is
much faster on average than going for the fits files.<|endoftext|> |
57e62c97d17de9c9009c1fe4cec4b514290d7500a5902ce8b7d2de368db4dfa1 | def draw_source(self, catalog_i=None, phi=None):
"Creates lenstronomy interpolation lightmodel kwargs from\n\t\ta catalog image.\n\n\t\tArgs:\n\t\t\tcatalog_i (int): Index of image in catalog\n\t\t\tz_new (float): Redshift to place image at\n\t\t\tphi (float): Rotation to apply to the image.\n\t\t\t\tIf not provided, use random or original rotation\n\t\t\t\tdepending on source_parameters['random_rotation']\n\n\t\tReturns:\n\t\t\t(list,list,list): A list containing the model ['INTERPOL'],\n\t\t\tthe kwargs for an instance of the class\n\t\t\tlenstronomy.LightModel.Profiles.interpolation.Interpol,\n\t\t\tand the redshift of the model.\n\n\t\tNotes:\n\t\t\tIf not catalog_i is provided, one that meets the cuts will be\n\t\t\tselected at random.\n\t\t"
(catalog_i, phi) = self.fill_catalog_i_phi_defaults(catalog_i, phi)
metadata = self.catalog[catalog_i]
z_new = self.source_parameters['z_source']
z_scaling = self.z_scale_factor(metadata['z'], z_new)
sercic_info = {p: self.sercic_info[p][catalog_i] for p in self.sercic_info}
(e1, e2) = phi_q2_ellipticity.py_func(((sercic_info['phi'] + phi) % (2 * np.pi)), sercic_info['q'])
return (['SERSIC_ELLIPSE'], [dict(amp=(sercic_info['intensity'] / (metadata['pixel_width'] ** 2)), e1=e1, e2=e2, R_sersic=(sercic_info['r_half'] * z_scaling), n_sersic=sercic_info['n'])], [z_new]) | Creates lenstronomy interpolation lightmodel kwargs from
a catalog image.
Args:
catalog_i (int): Index of image in catalog
z_new (float): Redshift to place image at
phi (float): Rotation to apply to the image.
If not provided, use random or original rotation
depending on source_parameters['random_rotation']
Returns:
(list,list,list): A list containing the model ['INTERPOL'],
the kwargs for an instance of the class
lenstronomy.LightModel.Profiles.interpolation.Interpol,
and the redshift of the model.
Notes:
If not catalog_i is provided, one that meets the cuts will be
selected at random. | paltas/Sources/cosmos.py | draw_source | swagnercarena/paltas | 5 | python | def draw_source(self, catalog_i=None, phi=None):
"Creates lenstronomy interpolation lightmodel kwargs from\n\t\ta catalog image.\n\n\t\tArgs:\n\t\t\tcatalog_i (int): Index of image in catalog\n\t\t\tz_new (float): Redshift to place image at\n\t\t\tphi (float): Rotation to apply to the image.\n\t\t\t\tIf not provided, use random or original rotation\n\t\t\t\tdepending on source_parameters['random_rotation']\n\n\t\tReturns:\n\t\t\t(list,list,list): A list containing the model ['INTERPOL'],\n\t\t\tthe kwargs for an instance of the class\n\t\t\tlenstronomy.LightModel.Profiles.interpolation.Interpol,\n\t\t\tand the redshift of the model.\n\n\t\tNotes:\n\t\t\tIf not catalog_i is provided, one that meets the cuts will be\n\t\t\tselected at random.\n\t\t"
(catalog_i, phi) = self.fill_catalog_i_phi_defaults(catalog_i, phi)
metadata = self.catalog[catalog_i]
z_new = self.source_parameters['z_source']
z_scaling = self.z_scale_factor(metadata['z'], z_new)
sercic_info = {p: self.sercic_info[p][catalog_i] for p in self.sercic_info}
(e1, e2) = phi_q2_ellipticity.py_func(((sercic_info['phi'] + phi) % (2 * np.pi)), sercic_info['q'])
return (['SERSIC_ELLIPSE'], [dict(amp=(sercic_info['intensity'] / (metadata['pixel_width'] ** 2)), e1=e1, e2=e2, R_sersic=(sercic_info['r_half'] * z_scaling), n_sersic=sercic_info['n'])], [z_new]) | def draw_source(self, catalog_i=None, phi=None):
"Creates lenstronomy interpolation lightmodel kwargs from\n\t\ta catalog image.\n\n\t\tArgs:\n\t\t\tcatalog_i (int): Index of image in catalog\n\t\t\tz_new (float): Redshift to place image at\n\t\t\tphi (float): Rotation to apply to the image.\n\t\t\t\tIf not provided, use random or original rotation\n\t\t\t\tdepending on source_parameters['random_rotation']\n\n\t\tReturns:\n\t\t\t(list,list,list): A list containing the model ['INTERPOL'],\n\t\t\tthe kwargs for an instance of the class\n\t\t\tlenstronomy.LightModel.Profiles.interpolation.Interpol,\n\t\t\tand the redshift of the model.\n\n\t\tNotes:\n\t\t\tIf not catalog_i is provided, one that meets the cuts will be\n\t\t\tselected at random.\n\t\t"
(catalog_i, phi) = self.fill_catalog_i_phi_defaults(catalog_i, phi)
metadata = self.catalog[catalog_i]
z_new = self.source_parameters['z_source']
z_scaling = self.z_scale_factor(metadata['z'], z_new)
sercic_info = {p: self.sercic_info[p][catalog_i] for p in self.sercic_info}
(e1, e2) = phi_q2_ellipticity.py_func(((sercic_info['phi'] + phi) % (2 * np.pi)), sercic_info['q'])
return (['SERSIC_ELLIPSE'], [dict(amp=(sercic_info['intensity'] / (metadata['pixel_width'] ** 2)), e1=e1, e2=e2, R_sersic=(sercic_info['r_half'] * z_scaling), n_sersic=sercic_info['n'])], [z_new])<|docstring|>Creates lenstronomy interpolation lightmodel kwargs from
a catalog image.
Args:
catalog_i (int): Index of image in catalog
z_new (float): Redshift to place image at
phi (float): Rotation to apply to the image.
If not provided, use random or original rotation
depending on source_parameters['random_rotation']
Returns:
(list,list,list): A list containing the model ['INTERPOL'],
the kwargs for an instance of the class
lenstronomy.LightModel.Profiles.interpolation.Interpol,
and the redshift of the model.
Notes:
If not catalog_i is provided, one that meets the cuts will be
selected at random.<|endoftext|> |
41b101ebbb206fcc2896bb60de7ef5b7c8ae047ab4790918db7ec2c21d5d2beb | def image_and_metadata(self, catalog_i):
'Returns the image array and metadata for one galaxy\n\n\t\tArgs:\n\t\t\tcatalog_i (int): The catalog index\n\n\t\tReturns:\n\t\t\t([np.array, np.void]) A numpy array containing the image\n\t\t\tmetadata and a numpy void type that acts as a dictionary with\n\t\t\tthe metadata.\n\n\t\tNotes:\n\t\t\tThis will read the numpy files made during initialization. This is\n\t\t\tmuch faster on average than going for the fits files.\n\t\t'
raise NotImplementedError | Returns the image array and metadata for one galaxy
Args:
catalog_i (int): The catalog index
Returns:
([np.array, np.void]) A numpy array containing the image
metadata and a numpy void type that acts as a dictionary with
the metadata.
Notes:
This will read the numpy files made during initialization. This is
much faster on average than going for the fits files. | paltas/Sources/cosmos.py | image_and_metadata | swagnercarena/paltas | 5 | python | def image_and_metadata(self, catalog_i):
'Returns the image array and metadata for one galaxy\n\n\t\tArgs:\n\t\t\tcatalog_i (int): The catalog index\n\n\t\tReturns:\n\t\t\t([np.array, np.void]) A numpy array containing the image\n\t\t\tmetadata and a numpy void type that acts as a dictionary with\n\t\t\tthe metadata.\n\n\t\tNotes:\n\t\t\tThis will read the numpy files made during initialization. This is\n\t\t\tmuch faster on average than going for the fits files.\n\t\t'
raise NotImplementedError | def image_and_metadata(self, catalog_i):
'Returns the image array and metadata for one galaxy\n\n\t\tArgs:\n\t\t\tcatalog_i (int): The catalog index\n\n\t\tReturns:\n\t\t\t([np.array, np.void]) A numpy array containing the image\n\t\t\tmetadata and a numpy void type that acts as a dictionary with\n\t\t\tthe metadata.\n\n\t\tNotes:\n\t\t\tThis will read the numpy files made during initialization. This is\n\t\t\tmuch faster on average than going for the fits files.\n\t\t'
raise NotImplementedError<|docstring|>Returns the image array and metadata for one galaxy
Args:
catalog_i (int): The catalog index
Returns:
([np.array, np.void]) A numpy array containing the image
metadata and a numpy void type that acts as a dictionary with
the metadata.
Notes:
This will read the numpy files made during initialization. This is
much faster on average than going for the fits files.<|endoftext|> |
05d2ba13afbfb8cf8201641b2984318da9a4d1ae6d05bee1eab130dae98456ee | def iter_image_and_metadata_bulk(self, message=''):
'Yields the image array and metadata for all of the images\n\t\tin the catalog.\n\n\t\tArgs:\n\t\t\tmessage (str): If the iterator uses tqdm, this message\n\t\t\t\twill be displayed.\n\n\t\tReturns:\n\t\t\t(generator): A generator that can be iterated over to give\n\t\t\tlenstronomy kwargs.\n\n\t\tNotes:\n\t\t\tThis will read the fits files.\n\t\t'
raise NotImplementedError | Yields the image array and metadata for all of the images
in the catalog.
Args:
message (str): If the iterator uses tqdm, this message
will be displayed.
Returns:
(generator): A generator that can be iterated over to give
lenstronomy kwargs.
Notes:
This will read the fits files. | paltas/Sources/cosmos.py | iter_image_and_metadata_bulk | swagnercarena/paltas | 5 | python | def iter_image_and_metadata_bulk(self, message=):
'Yields the image array and metadata for all of the images\n\t\tin the catalog.\n\n\t\tArgs:\n\t\t\tmessage (str): If the iterator uses tqdm, this message\n\t\t\t\twill be displayed.\n\n\t\tReturns:\n\t\t\t(generator): A generator that can be iterated over to give\n\t\t\tlenstronomy kwargs.\n\n\t\tNotes:\n\t\t\tThis will read the fits files.\n\t\t'
raise NotImplementedError | def iter_image_and_metadata_bulk(self, message=):
'Yields the image array and metadata for all of the images\n\t\tin the catalog.\n\n\t\tArgs:\n\t\t\tmessage (str): If the iterator uses tqdm, this message\n\t\t\t\twill be displayed.\n\n\t\tReturns:\n\t\t\t(generator): A generator that can be iterated over to give\n\t\t\tlenstronomy kwargs.\n\n\t\tNotes:\n\t\t\tThis will read the fits files.\n\t\t'
raise NotImplementedError<|docstring|>Yields the image array and metadata for all of the images
in the catalog.
Args:
message (str): If the iterator uses tqdm, this message
will be displayed.
Returns:
(generator): A generator that can be iterated over to give
lenstronomy kwargs.
Notes:
This will read the fits files.<|endoftext|> |
2c2ccb72d672af1f9d7c5b0a1d49626e7bde8442012d0065148d48bf0da22da4 | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = super()._passes_cuts()
is_ok &= np.invert(np.in1d(np.arange(len(self)), self.source_parameters['source_exclusion_list']))
return is_ok | Return a boolean mask of the sources that pass the source
parameter cuts.
Returns:
(np.array): Array of bools of catalog indices to use for
sampling. | paltas/Sources/cosmos.py | _passes_cuts | swagnercarena/paltas | 5 | python | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = super()._passes_cuts()
is_ok &= np.invert(np.in1d(np.arange(len(self)), self.source_parameters['source_exclusion_list']))
return is_ok | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = super()._passes_cuts()
is_ok &= np.invert(np.in1d(np.arange(len(self)), self.source_parameters['source_exclusion_list']))
return is_ok<|docstring|>Return a boolean mask of the sources that pass the source
parameter cuts.
Returns:
(np.array): Array of bools of catalog indices to use for
sampling.<|endoftext|> |
a00487d68634ac7de03896d3defdcaaae59be483de50150d970d903133394aeb | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = super()._passes_cuts()
is_ok &= np.in1d(np.arange(len(self)), self.source_parameters['source_inclusion_list'])
return is_ok | Return a boolean mask of the sources that pass the source
parameter cuts.
Returns:
(np.array): Array of bools of catalog indices to use for
sampling. | paltas/Sources/cosmos.py | _passes_cuts | swagnercarena/paltas | 5 | python | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = super()._passes_cuts()
is_ok &= np.in1d(np.arange(len(self)), self.source_parameters['source_inclusion_list'])
return is_ok | def _passes_cuts(self):
' Return a boolean mask of the sources that pass the source\n\t\tparameter cuts.\n\n\t\tReturns:\n\t\t\t(np.array): Array of bools of catalog indices to use for\n\t\t\t\tsampling.\n\t\t'
is_ok = super()._passes_cuts()
is_ok &= np.in1d(np.arange(len(self)), self.source_parameters['source_inclusion_list'])
return is_ok<|docstring|>Return a boolean mask of the sources that pass the source
parameter cuts.
Returns:
(np.array): Array of bools of catalog indices to use for
sampling.<|endoftext|> |
56280eba6e3d7d7024c9fb9a59e2ec945a2a6d16d283cfbe2652aaf9bcc68151 | def generateTheCalendarCSV(data, year, month):
"\n In this method, I'm going to add write data into the calendar file.\n parameters:\n data : receive from the browser.\n year : receive from query string.\n month : receive from query string\n "
path = ((((os.path.dirname(__file__) + '/Working-Shift-Scheduling/files/calendar') + year) + MONTH[month]) + '.csv')
with open(path, 'w') as f:
writer = csv.writer(f)
keys = data.keys()
'\n If the data include the last day of last month, the program need to eliminate it.\n '
if (int(data['Date'][1]) > int(data['Date'][2])):
for key in keys:
del data[key][1]
writer.writerow(data[key])
else:
for key in keys:
writer.writerow(data[key]) | In this method, I'm going to add write data into the calendar file.
parameters:
data : receive from the browser.
year : receive from query string.
month : receive from query string | WorkingShift/Shift/utils.py | generateTheCalendarCSV | yuchun1214/Working-Shift-Arrangement-System | 1 | python | def generateTheCalendarCSV(data, year, month):
"\n In this method, I'm going to add write data into the calendar file.\n parameters:\n data : receive from the browser.\n year : receive from query string.\n month : receive from query string\n "
path = ((((os.path.dirname(__file__) + '/Working-Shift-Scheduling/files/calendar') + year) + MONTH[month]) + '.csv')
with open(path, 'w') as f:
writer = csv.writer(f)
keys = data.keys()
'\n If the data include the last day of last month, the program need to eliminate it.\n '
if (int(data['Date'][1]) > int(data['Date'][2])):
for key in keys:
del data[key][1]
writer.writerow(data[key])
else:
for key in keys:
writer.writerow(data[key]) | def generateTheCalendarCSV(data, year, month):
"\n In this method, I'm going to add write data into the calendar file.\n parameters:\n data : receive from the browser.\n year : receive from query string.\n month : receive from query string\n "
path = ((((os.path.dirname(__file__) + '/Working-Shift-Scheduling/files/calendar') + year) + MONTH[month]) + '.csv')
with open(path, 'w') as f:
writer = csv.writer(f)
keys = data.keys()
'\n If the data include the last day of last month, the program need to eliminate it.\n '
if (int(data['Date'][1]) > int(data['Date'][2])):
for key in keys:
del data[key][1]
writer.writerow(data[key])
else:
for key in keys:
writer.writerow(data[key])<|docstring|>In this method, I'm going to add write data into the calendar file.
parameters:
data : receive from the browser.
year : receive from query string.
month : receive from query string<|endoftext|> |
1d17c117f7292fdaabf5e88d3bd93986dfebae1d963288bb885743d07a5c9f1c | def generate_vectors_paired_X_y(corpus, vector_name, pair_orientation_attribute_name, pair_id_to_objs):
'\n Generate the X, y matrix for paired prediction and annotate the objects with the pair orientation.\n\n :param corpus:\n :param vector_name:\n :param pair_orientation_attribute_name:\n :param pair_id_to_objs:\n :return:\n '
pos_orientation_pair_ids = []
neg_orientation_pair_ids = []
for (pair_id, (pos_obj, neg_obj)) in pair_id_to_objs.items():
if (pos_obj.meta[pair_orientation_attribute_name] == 'pos'):
pos_orientation_pair_ids.append(pair_id)
else:
neg_orientation_pair_ids.append(pair_id)
(pos_orientation_pos_objs, pos_orientation_neg_objs) = zip(*[pair_id_to_objs[pair_id] for pair_id in pos_orientation_pair_ids])
(neg_orientation_pos_objs, neg_orientation_neg_objs) = zip(*[pair_id_to_objs[pair_id] for pair_id in neg_orientation_pair_ids])
pos_pos_ids = [obj.id for obj in pos_orientation_pos_objs]
pos_neg_ids = [obj.id for obj in pos_orientation_neg_objs]
neg_pos_ids = [obj.id for obj in neg_orientation_pos_objs]
neg_neg_ids = [obj.id for obj in neg_orientation_neg_objs]
pos_pos_vectors = corpus.get_vectors(vector_name, pos_pos_ids)
pos_neg_vectors = corpus.get_vectors(vector_name, pos_neg_ids)
neg_pos_vectors = corpus.get_vectors(vector_name, neg_pos_ids)
neg_neg_vectors = corpus.get_vectors(vector_name, neg_neg_ids)
y = np.array((([1] * len(pos_orientation_pair_ids)) + ([0] * len(neg_orientation_pair_ids))))
if issparse(pos_pos_vectors):
X = vstack([(pos_pos_vectors - pos_neg_vectors), (neg_neg_vectors - neg_pos_vectors)])
else:
X = np.vstack([(pos_pos_vectors - pos_neg_vectors), (neg_neg_vectors - neg_pos_vectors)])
indices = np.arange(X.shape[0])
shuffle(indices)
return (X[indices], y[indices]) | Generate the X, y matrix for paired prediction and annotate the objects with the pair orientation.
:param corpus:
:param vector_name:
:param pair_orientation_attribute_name:
:param pair_id_to_objs:
:return: | convokit/paired_prediction/util.py | generate_vectors_paired_X_y | christianoswald/Cornell-Conversational-Analysis-Toolkit | 371 | python | def generate_vectors_paired_X_y(corpus, vector_name, pair_orientation_attribute_name, pair_id_to_objs):
'\n Generate the X, y matrix for paired prediction and annotate the objects with the pair orientation.\n\n :param corpus:\n :param vector_name:\n :param pair_orientation_attribute_name:\n :param pair_id_to_objs:\n :return:\n '
pos_orientation_pair_ids = []
neg_orientation_pair_ids = []
for (pair_id, (pos_obj, neg_obj)) in pair_id_to_objs.items():
if (pos_obj.meta[pair_orientation_attribute_name] == 'pos'):
pos_orientation_pair_ids.append(pair_id)
else:
neg_orientation_pair_ids.append(pair_id)
(pos_orientation_pos_objs, pos_orientation_neg_objs) = zip(*[pair_id_to_objs[pair_id] for pair_id in pos_orientation_pair_ids])
(neg_orientation_pos_objs, neg_orientation_neg_objs) = zip(*[pair_id_to_objs[pair_id] for pair_id in neg_orientation_pair_ids])
pos_pos_ids = [obj.id for obj in pos_orientation_pos_objs]
pos_neg_ids = [obj.id for obj in pos_orientation_neg_objs]
neg_pos_ids = [obj.id for obj in neg_orientation_pos_objs]
neg_neg_ids = [obj.id for obj in neg_orientation_neg_objs]
pos_pos_vectors = corpus.get_vectors(vector_name, pos_pos_ids)
pos_neg_vectors = corpus.get_vectors(vector_name, pos_neg_ids)
neg_pos_vectors = corpus.get_vectors(vector_name, neg_pos_ids)
neg_neg_vectors = corpus.get_vectors(vector_name, neg_neg_ids)
y = np.array((([1] * len(pos_orientation_pair_ids)) + ([0] * len(neg_orientation_pair_ids))))
if issparse(pos_pos_vectors):
X = vstack([(pos_pos_vectors - pos_neg_vectors), (neg_neg_vectors - neg_pos_vectors)])
else:
X = np.vstack([(pos_pos_vectors - pos_neg_vectors), (neg_neg_vectors - neg_pos_vectors)])
indices = np.arange(X.shape[0])
shuffle(indices)
return (X[indices], y[indices]) | def generate_vectors_paired_X_y(corpus, vector_name, pair_orientation_attribute_name, pair_id_to_objs):
'\n Generate the X, y matrix for paired prediction and annotate the objects with the pair orientation.\n\n :param corpus:\n :param vector_name:\n :param pair_orientation_attribute_name:\n :param pair_id_to_objs:\n :return:\n '
pos_orientation_pair_ids = []
neg_orientation_pair_ids = []
for (pair_id, (pos_obj, neg_obj)) in pair_id_to_objs.items():
if (pos_obj.meta[pair_orientation_attribute_name] == 'pos'):
pos_orientation_pair_ids.append(pair_id)
else:
neg_orientation_pair_ids.append(pair_id)
(pos_orientation_pos_objs, pos_orientation_neg_objs) = zip(*[pair_id_to_objs[pair_id] for pair_id in pos_orientation_pair_ids])
(neg_orientation_pos_objs, neg_orientation_neg_objs) = zip(*[pair_id_to_objs[pair_id] for pair_id in neg_orientation_pair_ids])
pos_pos_ids = [obj.id for obj in pos_orientation_pos_objs]
pos_neg_ids = [obj.id for obj in pos_orientation_neg_objs]
neg_pos_ids = [obj.id for obj in neg_orientation_pos_objs]
neg_neg_ids = [obj.id for obj in neg_orientation_neg_objs]
pos_pos_vectors = corpus.get_vectors(vector_name, pos_pos_ids)
pos_neg_vectors = corpus.get_vectors(vector_name, pos_neg_ids)
neg_pos_vectors = corpus.get_vectors(vector_name, neg_pos_ids)
neg_neg_vectors = corpus.get_vectors(vector_name, neg_neg_ids)
y = np.array((([1] * len(pos_orientation_pair_ids)) + ([0] * len(neg_orientation_pair_ids))))
if issparse(pos_pos_vectors):
X = vstack([(pos_pos_vectors - pos_neg_vectors), (neg_neg_vectors - neg_pos_vectors)])
else:
X = np.vstack([(pos_pos_vectors - pos_neg_vectors), (neg_neg_vectors - neg_pos_vectors)])
indices = np.arange(X.shape[0])
shuffle(indices)
return (X[indices], y[indices])<|docstring|>Generate the X, y matrix for paired prediction and annotate the objects with the pair orientation.
:param corpus:
:param vector_name:
:param pair_orientation_attribute_name:
:param pair_id_to_objs:
:return:<|endoftext|> |
cdac45ad1899a1525c2d4838a23b3f567aadbdcb910c8a8224fe8eb619b55b19 | def generate_paired_X_y(pred_feats, pair_orientation_attribute_name, pair_id_to_objs):
'\n Generate the X, y matrix for paired prediction\n :param pair_id_to_objs: dictionary indexed by the paired feature instance value, with the value\n being a tuple (pos_obj, neg_obj)\n :return: X, y matrix representing the predictive features and labels respectively\n '
pos_obj_dict = dict()
neg_obj_dict = dict()
for (pair_id, (pos_obj, neg_obj)) in pair_id_to_objs.items():
pos_obj_dict[pair_id] = extract_feats_from_obj(pos_obj, pred_feats)
neg_obj_dict[pair_id] = extract_feats_from_obj(neg_obj, pred_feats)
pos_obj_df = DataFrame.from_dict(pos_obj_dict, orient='index')
neg_obj_df = DataFrame.from_dict(neg_obj_dict, orient='index')
(X, y) = ([], [])
pair_ids = list(pair_id_to_objs)
shuffle(pair_ids)
for pair_id in pair_ids:
pos_feats = np.array(pos_obj_df.loc[pair_id]).astype('float64')
neg_feats = np.array(neg_obj_df.loc[pair_id]).astype('float64')
orientation = pair_id_to_objs[pair_id][0].meta[pair_orientation_attribute_name]
assert (orientation in ['pos', 'neg'])
if (orientation == 'pos'):
y.append(1)
diff = (pos_feats - neg_feats)
else:
y.append(0)
diff = (neg_feats - pos_feats)
X.append(diff)
return (csr_matrix(np.array(X)), np.array(y)) | Generate the X, y matrix for paired prediction
:param pair_id_to_objs: dictionary indexed by the paired feature instance value, with the value
being a tuple (pos_obj, neg_obj)
:return: X, y matrix representing the predictive features and labels respectively | convokit/paired_prediction/util.py | generate_paired_X_y | christianoswald/Cornell-Conversational-Analysis-Toolkit | 371 | python | def generate_paired_X_y(pred_feats, pair_orientation_attribute_name, pair_id_to_objs):
'\n Generate the X, y matrix for paired prediction\n :param pair_id_to_objs: dictionary indexed by the paired feature instance value, with the value\n being a tuple (pos_obj, neg_obj)\n :return: X, y matrix representing the predictive features and labels respectively\n '
pos_obj_dict = dict()
neg_obj_dict = dict()
for (pair_id, (pos_obj, neg_obj)) in pair_id_to_objs.items():
pos_obj_dict[pair_id] = extract_feats_from_obj(pos_obj, pred_feats)
neg_obj_dict[pair_id] = extract_feats_from_obj(neg_obj, pred_feats)
pos_obj_df = DataFrame.from_dict(pos_obj_dict, orient='index')
neg_obj_df = DataFrame.from_dict(neg_obj_dict, orient='index')
(X, y) = ([], [])
pair_ids = list(pair_id_to_objs)
shuffle(pair_ids)
for pair_id in pair_ids:
pos_feats = np.array(pos_obj_df.loc[pair_id]).astype('float64')
neg_feats = np.array(neg_obj_df.loc[pair_id]).astype('float64')
orientation = pair_id_to_objs[pair_id][0].meta[pair_orientation_attribute_name]
assert (orientation in ['pos', 'neg'])
if (orientation == 'pos'):
y.append(1)
diff = (pos_feats - neg_feats)
else:
y.append(0)
diff = (neg_feats - pos_feats)
X.append(diff)
return (csr_matrix(np.array(X)), np.array(y)) | def generate_paired_X_y(pred_feats, pair_orientation_attribute_name, pair_id_to_objs):
'\n Generate the X, y matrix for paired prediction\n :param pair_id_to_objs: dictionary indexed by the paired feature instance value, with the value\n being a tuple (pos_obj, neg_obj)\n :return: X, y matrix representing the predictive features and labels respectively\n '
pos_obj_dict = dict()
neg_obj_dict = dict()
for (pair_id, (pos_obj, neg_obj)) in pair_id_to_objs.items():
pos_obj_dict[pair_id] = extract_feats_from_obj(pos_obj, pred_feats)
neg_obj_dict[pair_id] = extract_feats_from_obj(neg_obj, pred_feats)
pos_obj_df = DataFrame.from_dict(pos_obj_dict, orient='index')
neg_obj_df = DataFrame.from_dict(neg_obj_dict, orient='index')
(X, y) = ([], [])
pair_ids = list(pair_id_to_objs)
shuffle(pair_ids)
for pair_id in pair_ids:
pos_feats = np.array(pos_obj_df.loc[pair_id]).astype('float64')
neg_feats = np.array(neg_obj_df.loc[pair_id]).astype('float64')
orientation = pair_id_to_objs[pair_id][0].meta[pair_orientation_attribute_name]
assert (orientation in ['pos', 'neg'])
if (orientation == 'pos'):
y.append(1)
diff = (pos_feats - neg_feats)
else:
y.append(0)
diff = (neg_feats - pos_feats)
X.append(diff)
return (csr_matrix(np.array(X)), np.array(y))<|docstring|>Generate the X, y matrix for paired prediction
:param pair_id_to_objs: dictionary indexed by the paired feature instance value, with the value
being a tuple (pos_obj, neg_obj)
:return: X, y matrix representing the predictive features and labels respectively<|endoftext|> |
1ed61fe742430d10d0c47f63e79d71454cfd79f87beb6167a6e2e5e74b5f1036 | def MinDx(mesh):
' Finds the minimum cell edge length for each cell in a DG0 function\n\n :param mesh: :class:`Mesh` to find min cell edge length of\n :type mesh: :class:`Mesh`\n\n '
if (mesh.geometric_dimension() == 2):
min_cell_length = Function(FunctionSpace(mesh, 'DG', 0))
min_cell_length.interpolate(MinCellEdgeLength(mesh))
if (mesh.geometric_dimension() == 1):
min_cell_length = Function(FunctionSpace(mesh, 'DG', 0))
min_cell_length.interpolate(CellVolume(mesh))
return min_cell_length | Finds the minimum cell edge length for each cell in a DG0 function
:param mesh: :class:`Mesh` to find min cell edge length of
:type mesh: :class:`Mesh` | flooddrake/min_dx.py | MinDx | firedrakeproject/flooddrake | 6 | python | def MinDx(mesh):
' Finds the minimum cell edge length for each cell in a DG0 function\n\n :param mesh: :class:`Mesh` to find min cell edge length of\n :type mesh: :class:`Mesh`\n\n '
if (mesh.geometric_dimension() == 2):
min_cell_length = Function(FunctionSpace(mesh, 'DG', 0))
min_cell_length.interpolate(MinCellEdgeLength(mesh))
if (mesh.geometric_dimension() == 1):
min_cell_length = Function(FunctionSpace(mesh, 'DG', 0))
min_cell_length.interpolate(CellVolume(mesh))
return min_cell_length | def MinDx(mesh):
' Finds the minimum cell edge length for each cell in a DG0 function\n\n :param mesh: :class:`Mesh` to find min cell edge length of\n :type mesh: :class:`Mesh`\n\n '
if (mesh.geometric_dimension() == 2):
min_cell_length = Function(FunctionSpace(mesh, 'DG', 0))
min_cell_length.interpolate(MinCellEdgeLength(mesh))
if (mesh.geometric_dimension() == 1):
min_cell_length = Function(FunctionSpace(mesh, 'DG', 0))
min_cell_length.interpolate(CellVolume(mesh))
return min_cell_length<|docstring|>Finds the minimum cell edge length for each cell in a DG0 function
:param mesh: :class:`Mesh` to find min cell edge length of
:type mesh: :class:`Mesh`<|endoftext|> |
2f268628b2c79f8ebfd8149254dd1060ba517d792907db4202c5f1804f61efda | def passed(self, text=None):
'Attests that a test case has passed.'
if text:
self.ui.notice(text)
self.success_num += 1 | Attests that a test case has passed. | src/pbbt/ctl.py | passed | prometheusresearch/pbbt | 2 | python | def passed(self, text=None):
if text:
self.ui.notice(text)
self.success_num += 1 | def passed(self, text=None):
if text:
self.ui.notice(text)
self.success_num += 1<|docstring|>Attests that a test case has passed.<|endoftext|> |
d6fc6d1e64c50f6a93a00844bf92e3c0f00a91941850cd95032f87e72ce759dc | def failed(self, text=None):
'Attests that a test case has failed.'
if text:
self.ui.warning(text)
self.failure_num += 1
if (self.max_errors and (self.failure_num >= self.max_errors)):
self.halted = True | Attests that a test case has failed. | src/pbbt/ctl.py | failed | prometheusresearch/pbbt | 2 | python | def failed(self, text=None):
if text:
self.ui.warning(text)
self.failure_num += 1
if (self.max_errors and (self.failure_num >= self.max_errors)):
self.halted = True | def failed(self, text=None):
if text:
self.ui.warning(text)
self.failure_num += 1
if (self.max_errors and (self.failure_num >= self.max_errors)):
self.halted = True<|docstring|>Attests that a test case has failed.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.