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
|
|---|---|---|---|---|---|---|---|---|---|
a1e1dde04a446e0f6635117daf576737b7abd39533b726029c68e8b84eb64c22
|
def add(self, skill: Type[Skill], add_to_order: bool=True, set_cooldown: bool=True):
'\n Learn a new skill.\n '
self.skill_names.append(skill.__name__)
self.skills[skill.__name__] = skill
if add_to_order:
self.skill_order.append(skill.__name__)
if set_cooldown:
self.cooldowns[skill.__name__] = 0
|
Learn a new skill.
|
scripts/engine/core/component.py
|
add
|
Snayff/notquiteparadise
| 12
|
python
|
def add(self, skill: Type[Skill], add_to_order: bool=True, set_cooldown: bool=True):
'\n \n '
self.skill_names.append(skill.__name__)
self.skills[skill.__name__] = skill
if add_to_order:
self.skill_order.append(skill.__name__)
if set_cooldown:
self.cooldowns[skill.__name__] = 0
|
def add(self, skill: Type[Skill], add_to_order: bool=True, set_cooldown: bool=True):
'\n \n '
self.skill_names.append(skill.__name__)
self.skills[skill.__name__] = skill
if add_to_order:
self.skill_order.append(skill.__name__)
if set_cooldown:
self.cooldowns[skill.__name__] = 0<|docstring|>Learn a new skill.<|endoftext|>
|
c857e72f577a42a6f5ddfef62b2c852ea055cc7dbb64867da54eeedc82caf18a
|
def can_add_blessing(self, skill: Type[Skill], blessing: SkillModifier) -> bool:
'\n Check if a blessing can be added to a skill.\n '
if (skill.__name__ not in self.skill_blessings):
self.skill_blessings[skill.__name__] = []
used_effects: Set[str] = set()
blessing_names: Set[str] = set()
for b in self.skill_blessings[skill.__name__]:
used_effects = used_effects.union(b.involved_effects)
blessing_names = blessing_names.union({b.__class__.__name__})
if used_effects.intersection(blessing.involved_effects):
return False
elif (blessing.__class__.__name__ in blessing_names):
return False
elif set(blessing.conflicts).intersection(blessing_names):
return False
elif (not set(blessing.skill_types).intersection(set(skill.types))):
return False
else:
return True
|
Check if a blessing can be added to a skill.
|
scripts/engine/core/component.py
|
can_add_blessing
|
Snayff/notquiteparadise
| 12
|
python
|
def can_add_blessing(self, skill: Type[Skill], blessing: SkillModifier) -> bool:
'\n \n '
if (skill.__name__ not in self.skill_blessings):
self.skill_blessings[skill.__name__] = []
used_effects: Set[str] = set()
blessing_names: Set[str] = set()
for b in self.skill_blessings[skill.__name__]:
used_effects = used_effects.union(b.involved_effects)
blessing_names = blessing_names.union({b.__class__.__name__})
if used_effects.intersection(blessing.involved_effects):
return False
elif (blessing.__class__.__name__ in blessing_names):
return False
elif set(blessing.conflicts).intersection(blessing_names):
return False
elif (not set(blessing.skill_types).intersection(set(skill.types))):
return False
else:
return True
|
def can_add_blessing(self, skill: Type[Skill], blessing: SkillModifier) -> bool:
'\n \n '
if (skill.__name__ not in self.skill_blessings):
self.skill_blessings[skill.__name__] = []
used_effects: Set[str] = set()
blessing_names: Set[str] = set()
for b in self.skill_blessings[skill.__name__]:
used_effects = used_effects.union(b.involved_effects)
blessing_names = blessing_names.union({b.__class__.__name__})
if used_effects.intersection(blessing.involved_effects):
return False
elif (blessing.__class__.__name__ in blessing_names):
return False
elif set(blessing.conflicts).intersection(blessing_names):
return False
elif (not set(blessing.skill_types).intersection(set(skill.types))):
return False
else:
return True<|docstring|>Check if a blessing can be added to a skill.<|endoftext|>
|
7b9e9a4491c873c6e5e7c0e2534d246efaaa3648e327099c7dae010a262fd8be
|
def add_blessing(self, skill: Type[Skill], blessing: SkillModifier) -> bool:
'\n Add a blessing to a skill.\n '
blessing.roll_level()
if self.can_add_blessing(skill, blessing):
self.skill_blessings[skill.__name__].append(blessing)
return True
else:
return False
|
Add a blessing to a skill.
|
scripts/engine/core/component.py
|
add_blessing
|
Snayff/notquiteparadise
| 12
|
python
|
def add_blessing(self, skill: Type[Skill], blessing: SkillModifier) -> bool:
'\n \n '
blessing.roll_level()
if self.can_add_blessing(skill, blessing):
self.skill_blessings[skill.__name__].append(blessing)
return True
else:
return False
|
def add_blessing(self, skill: Type[Skill], blessing: SkillModifier) -> bool:
'\n \n '
blessing.roll_level()
if self.can_add_blessing(skill, blessing):
self.skill_blessings[skill.__name__].append(blessing)
return True
else:
return False<|docstring|>Add a blessing to a skill.<|endoftext|>
|
ee5b248444c33fbd4f51a5a90a2a8f28dc7ce9481eb83fd2dabee80d0ada8971
|
def remove_blessing(self, skill: Type[Skill], remove_blessing: Type[SkillModifier]) -> bool:
'\n Attempt to remove a blessing.\n '
if remove_blessing.removable:
if (skill.__name__ in self.skill_blessings):
for blessing in self.skill_blessings[skill.__name__]:
if (blessing.__class__.__name__ == remove_blessing.__name__):
self.skill_blessings[skill.__name__].remove(blessing)
return True
return False
|
Attempt to remove a blessing.
|
scripts/engine/core/component.py
|
remove_blessing
|
Snayff/notquiteparadise
| 12
|
python
|
def remove_blessing(self, skill: Type[Skill], remove_blessing: Type[SkillModifier]) -> bool:
'\n \n '
if remove_blessing.removable:
if (skill.__name__ in self.skill_blessings):
for blessing in self.skill_blessings[skill.__name__]:
if (blessing.__class__.__name__ == remove_blessing.__name__):
self.skill_blessings[skill.__name__].remove(blessing)
return True
return False
|
def remove_blessing(self, skill: Type[Skill], remove_blessing: Type[SkillModifier]) -> bool:
'\n \n '
if remove_blessing.removable:
if (skill.__name__ in self.skill_blessings):
for blessing in self.skill_blessings[skill.__name__]:
if (blessing.__class__.__name__ == remove_blessing.__name__):
self.skill_blessings[skill.__name__].remove(blessing)
return True
return False<|docstring|>Attempt to remove a blessing.<|endoftext|>
|
23d48c537cc4ae78234a22e8076ad061eea71ecc93171728be3a5bda55941800
|
def on_delete(self):
"\n Delete the associated light from the Gamemap's Lightbox\n "
from scripts.engine.core import world
light_box = world.get_game_map().light_box
light_box.delete_light(self.light_id)
|
Delete the associated light from the Gamemap's Lightbox
|
scripts/engine/core/component.py
|
on_delete
|
Snayff/notquiteparadise
| 12
|
python
|
def on_delete(self):
"\n \n "
from scripts.engine.core import world
light_box = world.get_game_map().light_box
light_box.delete_light(self.light_id)
|
def on_delete(self):
"\n \n "
from scripts.engine.core import world
light_box = world.get_game_map().light_box
light_box.delete_light(self.light_id)<|docstring|>Delete the associated light from the Gamemap's Lightbox<|endoftext|>
|
bedc316838eefda80f45e395111eedc064f4a2dc6eae1a2294a91606fddafbc0
|
def __init__(self, vigour: int, clout: int, skullduggery: int, bustle: int, exactitude: int):
'\n Set primary stats. Secondary stats pulled from library.\n '
self._vigour: int = vigour
self._clout: int = clout
self._skullduggery: int = skullduggery
self._bustle: int = bustle
self._exactitude: int = exactitude
self._vigour_mod: Dict[(str, int)] = {}
self._clout_mod: Dict[(str, int)] = {}
self._skullduggery_mod: Dict[(str, int)] = {}
self._bustle_mod: Dict[(str, int)] = {}
self._exactitude_mod: Dict[(str, int)] = {}
self._max_health: int = 0
self._max_stamina: int = 0
self._accuracy: int = 0
self._resist_burn: int = 0
self._resist_cold: int = 0
self._resist_chemical: int = 0
self._resist_astral: int = 0
self._resist_mundane: int = 0
self._rush: int = 0
self._max_health_mod: Dict[(str, int)] = {}
self._max_stamina_mod: Dict[(str, int)] = {}
self._accuracy_mod: Dict[(str, int)] = {}
self._resist_burn_mod: Dict[(str, int)] = {}
self._resist_cold_mod: Dict[(str, int)] = {}
self._resist_chemical_mod: Dict[(str, int)] = {}
self._resist_astral_mod: Dict[(str, int)] = {}
self._resist_mundane_mod: Dict[(str, int)] = {}
self._rush_mod: Dict[(str, int)] = {}
|
Set primary stats. Secondary stats pulled from library.
|
scripts/engine/core/component.py
|
__init__
|
Snayff/notquiteparadise
| 12
|
python
|
def __init__(self, vigour: int, clout: int, skullduggery: int, bustle: int, exactitude: int):
'\n \n '
self._vigour: int = vigour
self._clout: int = clout
self._skullduggery: int = skullduggery
self._bustle: int = bustle
self._exactitude: int = exactitude
self._vigour_mod: Dict[(str, int)] = {}
self._clout_mod: Dict[(str, int)] = {}
self._skullduggery_mod: Dict[(str, int)] = {}
self._bustle_mod: Dict[(str, int)] = {}
self._exactitude_mod: Dict[(str, int)] = {}
self._max_health: int = 0
self._max_stamina: int = 0
self._accuracy: int = 0
self._resist_burn: int = 0
self._resist_cold: int = 0
self._resist_chemical: int = 0
self._resist_astral: int = 0
self._resist_mundane: int = 0
self._rush: int = 0
self._max_health_mod: Dict[(str, int)] = {}
self._max_stamina_mod: Dict[(str, int)] = {}
self._accuracy_mod: Dict[(str, int)] = {}
self._resist_burn_mod: Dict[(str, int)] = {}
self._resist_cold_mod: Dict[(str, int)] = {}
self._resist_chemical_mod: Dict[(str, int)] = {}
self._resist_astral_mod: Dict[(str, int)] = {}
self._resist_mundane_mod: Dict[(str, int)] = {}
self._rush_mod: Dict[(str, int)] = {}
|
def __init__(self, vigour: int, clout: int, skullduggery: int, bustle: int, exactitude: int):
'\n \n '
self._vigour: int = vigour
self._clout: int = clout
self._skullduggery: int = skullduggery
self._bustle: int = bustle
self._exactitude: int = exactitude
self._vigour_mod: Dict[(str, int)] = {}
self._clout_mod: Dict[(str, int)] = {}
self._skullduggery_mod: Dict[(str, int)] = {}
self._bustle_mod: Dict[(str, int)] = {}
self._exactitude_mod: Dict[(str, int)] = {}
self._max_health: int = 0
self._max_stamina: int = 0
self._accuracy: int = 0
self._resist_burn: int = 0
self._resist_cold: int = 0
self._resist_chemical: int = 0
self._resist_astral: int = 0
self._resist_mundane: int = 0
self._rush: int = 0
self._max_health_mod: Dict[(str, int)] = {}
self._max_stamina_mod: Dict[(str, int)] = {}
self._accuracy_mod: Dict[(str, int)] = {}
self._resist_burn_mod: Dict[(str, int)] = {}
self._resist_cold_mod: Dict[(str, int)] = {}
self._resist_chemical_mod: Dict[(str, int)] = {}
self._resist_astral_mod: Dict[(str, int)] = {}
self._resist_mundane_mod: Dict[(str, int)] = {}
self._rush_mod: Dict[(str, int)] = {}<|docstring|>Set primary stats. Secondary stats pulled from library.<|endoftext|>
|
1ec3de14f4ab73d203d7c63cc10b04dcd5adc54b34156bd2751f59589ae51207
|
def amend_base_value(self, stat: Union[(PrimaryStatType, SecondaryStatType)], amount: int):
'\n Amend the base value of a stat\n '
current_value = getattr(self, ('_' + stat))
setattr(self, ('_' + stat), (current_value + amount))
|
Amend the base value of a stat
|
scripts/engine/core/component.py
|
amend_base_value
|
Snayff/notquiteparadise
| 12
|
python
|
def amend_base_value(self, stat: Union[(PrimaryStatType, SecondaryStatType)], amount: int):
'\n \n '
current_value = getattr(self, ('_' + stat))
setattr(self, ('_' + stat), (current_value + amount))
|
def amend_base_value(self, stat: Union[(PrimaryStatType, SecondaryStatType)], amount: int):
'\n \n '
current_value = getattr(self, ('_' + stat))
setattr(self, ('_' + stat), (current_value + amount))<|docstring|>Amend the base value of a stat<|endoftext|>
|
a392c2a622721033cdc28a647f77586a76a90c3d4531444a90bf37deb953db2f
|
def add_mod(self, stat: Union[(PrimaryStatType, SecondaryStatType)], cause: str, amount: int) -> bool:
'\n Amend the modifier of a stat. Returns True if successfully amended, else False.\n '
mod_to_amend = getattr(self, (('_' + stat) + '_mod'))
if (cause in mod_to_amend):
logging.info(f'Stat not modified as {cause} has already been applied.')
return False
else:
mod_to_amend[cause] = amount
return True
|
Amend the modifier of a stat. Returns True if successfully amended, else False.
|
scripts/engine/core/component.py
|
add_mod
|
Snayff/notquiteparadise
| 12
|
python
|
def add_mod(self, stat: Union[(PrimaryStatType, SecondaryStatType)], cause: str, amount: int) -> bool:
'\n \n '
mod_to_amend = getattr(self, (('_' + stat) + '_mod'))
if (cause in mod_to_amend):
logging.info(f'Stat not modified as {cause} has already been applied.')
return False
else:
mod_to_amend[cause] = amount
return True
|
def add_mod(self, stat: Union[(PrimaryStatType, SecondaryStatType)], cause: str, amount: int) -> bool:
'\n \n '
mod_to_amend = getattr(self, (('_' + stat) + '_mod'))
if (cause in mod_to_amend):
logging.info(f'Stat not modified as {cause} has already been applied.')
return False
else:
mod_to_amend[cause] = amount
return True<|docstring|>Amend the modifier of a stat. Returns True if successfully amended, else False.<|endoftext|>
|
65e2c86609a8595ece699a7f4290518d68e5c785cb749c3ec7374961e8dc37ef
|
def remove_mod(self, cause: str) -> bool:
'\n Remove a modifier from a stat. Returns True if successfully removed, else False.\n '
from scripts.engine.core import utility
for stat in utility.get_class_members(self.__class__):
if (cause in stat):
assert isinstance(stat, dict)
del stat[cause]
return True
logging.info(f'Modifier not removed as {cause} does not exist in modifier list.')
return False
|
Remove a modifier from a stat. Returns True if successfully removed, else False.
|
scripts/engine/core/component.py
|
remove_mod
|
Snayff/notquiteparadise
| 12
|
python
|
def remove_mod(self, cause: str) -> bool:
'\n \n '
from scripts.engine.core import utility
for stat in utility.get_class_members(self.__class__):
if (cause in stat):
assert isinstance(stat, dict)
del stat[cause]
return True
logging.info(f'Modifier not removed as {cause} does not exist in modifier list.')
return False
|
def remove_mod(self, cause: str) -> bool:
'\n \n '
from scripts.engine.core import utility
for stat in utility.get_class_members(self.__class__):
if (cause in stat):
assert isinstance(stat, dict)
del stat[cause]
return True
logging.info(f'Modifier not removed as {cause} does not exist in modifier list.')
return False<|docstring|>Remove a modifier from a stat. Returns True if successfully removed, else False.<|endoftext|>
|
85859e3077fcd9738d96a22191e400723b3f601184ad4595b4738e7cab6e4001
|
def _get_secondary_stat(self, stat: SecondaryStatType) -> int:
'\n Get the value of the secondary stat\n '
stat_data = library.SECONDARY_STAT_MODS[stat]
value = getattr(self, ('_' + stat.lower()))
value += (self.vigour * stat_data.vigour_mod)
value += (self.clout * stat_data.clout_mod)
value += (self.skullduggery * stat_data.skullduggery_mod)
value += (self.bustle * stat_data.bustle_mod)
value += (self.exactitude * stat_data.exactitude_mod)
value += self._get_mod_value(stat)
return value
|
Get the value of the secondary stat
|
scripts/engine/core/component.py
|
_get_secondary_stat
|
Snayff/notquiteparadise
| 12
|
python
|
def _get_secondary_stat(self, stat: SecondaryStatType) -> int:
'\n \n '
stat_data = library.SECONDARY_STAT_MODS[stat]
value = getattr(self, ('_' + stat.lower()))
value += (self.vigour * stat_data.vigour_mod)
value += (self.clout * stat_data.clout_mod)
value += (self.skullduggery * stat_data.skullduggery_mod)
value += (self.bustle * stat_data.bustle_mod)
value += (self.exactitude * stat_data.exactitude_mod)
value += self._get_mod_value(stat)
return value
|
def _get_secondary_stat(self, stat: SecondaryStatType) -> int:
'\n \n '
stat_data = library.SECONDARY_STAT_MODS[stat]
value = getattr(self, ('_' + stat.lower()))
value += (self.vigour * stat_data.vigour_mod)
value += (self.clout * stat_data.clout_mod)
value += (self.skullduggery * stat_data.skullduggery_mod)
value += (self.bustle * stat_data.bustle_mod)
value += (self.exactitude * stat_data.exactitude_mod)
value += self._get_mod_value(stat)
return value<|docstring|>Get the value of the secondary stat<|endoftext|>
|
f3e1640bd1e7c79e14a7bec53cdc3263e436a7ae5d950a440546a03017289439
|
@property
def vigour(self) -> int:
'\n Influences healthiness. Never below 1.\n '
return max(1, (self._vigour + self._get_mod_value(PrimaryStat.VIGOUR)))
|
Influences healthiness. Never below 1.
|
scripts/engine/core/component.py
|
vigour
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def vigour(self) -> int:
'\n \n '
return max(1, (self._vigour + self._get_mod_value(PrimaryStat.VIGOUR)))
|
@property
def vigour(self) -> int:
'\n \n '
return max(1, (self._vigour + self._get_mod_value(PrimaryStat.VIGOUR)))<|docstring|>Influences healthiness. Never below 1.<|endoftext|>
|
7e9e8be536bc8e877e5c87b01ab8fe685a27aad8b0438d6400be02f24be9ca8a
|
@property
def clout(self) -> int:
'\n Influences forceful things. Never below 1.\n '
return max(1, (self._clout + self._get_mod_value(PrimaryStat.CLOUT)))
|
Influences forceful things. Never below 1.
|
scripts/engine/core/component.py
|
clout
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def clout(self) -> int:
'\n \n '
return max(1, (self._clout + self._get_mod_value(PrimaryStat.CLOUT)))
|
@property
def clout(self) -> int:
'\n \n '
return max(1, (self._clout + self._get_mod_value(PrimaryStat.CLOUT)))<|docstring|>Influences forceful things. Never below 1.<|endoftext|>
|
6edc384c26214eccec9e5ced8e7d1b0d8182e4f05576ee03d0adf21abfef7b88
|
@property
def skullduggery(self) -> int:
'\n Influences sneaky things. Never below 1.\n '
return max(1, (self._skullduggery + self._get_mod_value(PrimaryStat.SKULLDUGGERY)))
|
Influences sneaky things. Never below 1.
|
scripts/engine/core/component.py
|
skullduggery
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def skullduggery(self) -> int:
'\n \n '
return max(1, (self._skullduggery + self._get_mod_value(PrimaryStat.SKULLDUGGERY)))
|
@property
def skullduggery(self) -> int:
'\n \n '
return max(1, (self._skullduggery + self._get_mod_value(PrimaryStat.SKULLDUGGERY)))<|docstring|>Influences sneaky things. Never below 1.<|endoftext|>
|
3cdbd9df3781a3e803de33a0a016ec7b2b715af35142393e944223c695f5ab17
|
@property
def bustle(self) -> int:
'\n Influences speedy things. Never below 1.\n '
return max(1, (self._bustle + self._get_mod_value(PrimaryStat.BUSTLE)))
|
Influences speedy things. Never below 1.
|
scripts/engine/core/component.py
|
bustle
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def bustle(self) -> int:
'\n \n '
return max(1, (self._bustle + self._get_mod_value(PrimaryStat.BUSTLE)))
|
@property
def bustle(self) -> int:
'\n \n '
return max(1, (self._bustle + self._get_mod_value(PrimaryStat.BUSTLE)))<|docstring|>Influences speedy things. Never below 1.<|endoftext|>
|
0e271bdc91fb05b2fa2223d83929c52d58950bed4724d7dfad546b8ee74e4c79
|
@property
def exactitude(self) -> int:
'\n Influences preciseness. Never below 1.\n '
return max(1, (self._exactitude + self._get_mod_value(PrimaryStat.EXACTITUDE)))
|
Influences preciseness. Never below 1.
|
scripts/engine/core/component.py
|
exactitude
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def exactitude(self) -> int:
'\n \n '
return max(1, (self._exactitude + self._get_mod_value(PrimaryStat.EXACTITUDE)))
|
@property
def exactitude(self) -> int:
'\n \n '
return max(1, (self._exactitude + self._get_mod_value(PrimaryStat.EXACTITUDE)))<|docstring|>Influences preciseness. Never below 1.<|endoftext|>
|
ce3264c970166b7e5742da06b3b6430c49072a0a8264fd25b6e02f93985fd336
|
@property
def max_health(self) -> int:
'\n Total damage an entity can take before death.\n '
return max(1, self._get_secondary_stat(SecondaryStat.MAX_HEALTH))
|
Total damage an entity can take before death.
|
scripts/engine/core/component.py
|
max_health
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def max_health(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.MAX_HEALTH))
|
@property
def max_health(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.MAX_HEALTH))<|docstring|>Total damage an entity can take before death.<|endoftext|>
|
0e2ef66e461ea74ee6d91c01c98e027cfb99fca73c3a9104a14c74cdba4d0045
|
@property
def max_stamina(self) -> int:
'\n An entities energy to take actions.\n\n '
return max(1, self._get_secondary_stat(SecondaryStat.MAX_STAMINA))
|
An entities energy to take actions.
|
scripts/engine/core/component.py
|
max_stamina
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def max_stamina(self) -> int:
'\n \n\n '
return max(1, self._get_secondary_stat(SecondaryStat.MAX_STAMINA))
|
@property
def max_stamina(self) -> int:
'\n \n\n '
return max(1, self._get_secondary_stat(SecondaryStat.MAX_STAMINA))<|docstring|>An entities energy to take actions.<|endoftext|>
|
bb9ba894f43474c07692817193051ab8fcf395d80fd47c878dc9010fb0c60dab
|
@property
def accuracy(self) -> int:
'\n An entities likelihood to hit.\n '
return max(1, self._get_secondary_stat(SecondaryStat.ACCURACY))
|
An entities likelihood to hit.
|
scripts/engine/core/component.py
|
accuracy
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def accuracy(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.ACCURACY))
|
@property
def accuracy(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.ACCURACY))<|docstring|>An entities likelihood to hit.<|endoftext|>
|
98451088f1502d7897620d9101667d5e2fa437c316b332ad47d593d6c4502a3e
|
@property
def resist_burn(self) -> int:
'\n An entities resistance to burn damage.\n\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_BURN))
|
An entities resistance to burn damage.
|
scripts/engine/core/component.py
|
resist_burn
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def resist_burn(self) -> int:
'\n \n\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_BURN))
|
@property
def resist_burn(self) -> int:
'\n \n\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_BURN))<|docstring|>An entities resistance to burn damage.<|endoftext|>
|
2eb2e735d4bacc0c147a8bce0be46a6be450e71ce1a7c5aadd858e2279cd10f2
|
@property
def resist_cold(self) -> int:
'\n An entities resistance to cold damage.\n\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_COLD))
|
An entities resistance to cold damage.
|
scripts/engine/core/component.py
|
resist_cold
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def resist_cold(self) -> int:
'\n \n\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_COLD))
|
@property
def resist_cold(self) -> int:
'\n \n\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_COLD))<|docstring|>An entities resistance to cold damage.<|endoftext|>
|
0f6774d2b878570b7da72004d864d65bf9b660b9e9850c632edd750fd73907eb
|
@property
def resist_chemical(self) -> int:
'\n An entities resistance to chemical damage.\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_CHEMICAL))
|
An entities resistance to chemical damage.
|
scripts/engine/core/component.py
|
resist_chemical
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def resist_chemical(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_CHEMICAL))
|
@property
def resist_chemical(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_CHEMICAL))<|docstring|>An entities resistance to chemical damage.<|endoftext|>
|
c6fac52221f43f52e14aec0ca83fd56b0cf099bd76b9e1e98eb2e78388b5cf9d
|
@property
def resist_astral(self) -> int:
'\n An entities resistance to astral damage.\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_ASTRAL))
|
An entities resistance to astral damage.
|
scripts/engine/core/component.py
|
resist_astral
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def resist_astral(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_ASTRAL))
|
@property
def resist_astral(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_ASTRAL))<|docstring|>An entities resistance to astral damage.<|endoftext|>
|
315e83b781ccb8395b32b184b7fb096187f594c6d05c6d818ccfeafd2c1c4dbc
|
@property
def resist_mundane(self) -> int:
'\n An entities resistance to mundane damage.\n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_MUNDANE))
|
An entities resistance to mundane damage.
|
scripts/engine/core/component.py
|
resist_mundane
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def resist_mundane(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_MUNDANE))
|
@property
def resist_mundane(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RESIST_MUNDANE))<|docstring|>An entities resistance to mundane damage.<|endoftext|>
|
588a3dfc4f58ccbbeabd3b6f9d1a0fd57fc81f8ba55c3dc170e7dc4440d9480d
|
@property
def rush(self) -> int:
'\n How quickly an entity does things. Reduce time cost of actions.\n '
return max(1, self._get_secondary_stat(SecondaryStat.RUSH))
|
How quickly an entity does things. Reduce time cost of actions.
|
scripts/engine/core/component.py
|
rush
|
Snayff/notquiteparadise
| 12
|
python
|
@property
def rush(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RUSH))
|
@property
def rush(self) -> int:
'\n \n '
return max(1, self._get_secondary_stat(SecondaryStat.RUSH))<|docstring|>How quickly an entity does things. Reduce time cost of actions.<|endoftext|>
|
bd350ee6dfc8f739e99745b152f332653f1e2ed089d7a9bfc2e6490c9e9c80d9
|
def moead(ref_dirs, n_neighbors=15, decomposition='auto', prob_neighbor_mating=0.7, **kwargs):
"\n\n Parameters\n ----------\n ref_dirs : {ref_dirs}\n\n decomposition : {{ 'auto', 'tchebi', 'pbi' }}\n The decomposition approach that should be used. If set to `auto` for two objectives `tchebi` and for more than\n two `pbi` will be used.\n\n n_neighbors : int\n Number of neighboring reference lines to be used for selection.\n\n prob_neighbor_mating : float\n Probability of selecting the parents in the neighborhood.\n\n\n Returns\n -------\n moead : :class:`~pymoo.model.algorithm.MOEAD`\n Returns an MOEAD algorithm object.\n\n\n "
return MOEAD(ref_dirs, n_neighbors=n_neighbors, decomposition=decomposition, prob_neighbor_mating=prob_neighbor_mating, **kwargs)
|
Parameters
----------
ref_dirs : {ref_dirs}
decomposition : {{ 'auto', 'tchebi', 'pbi' }}
The decomposition approach that should be used. If set to `auto` for two objectives `tchebi` and for more than
two `pbi` will be used.
n_neighbors : int
Number of neighboring reference lines to be used for selection.
prob_neighbor_mating : float
Probability of selecting the parents in the neighborhood.
Returns
-------
moead : :class:`~pymoo.model.algorithm.MOEAD`
Returns an MOEAD algorithm object.
|
pymoo/algorithms/moead.py
|
moead
|
temaurer/pymoo
| 0
|
python
|
def moead(ref_dirs, n_neighbors=15, decomposition='auto', prob_neighbor_mating=0.7, **kwargs):
"\n\n Parameters\n ----------\n ref_dirs : {ref_dirs}\n\n decomposition : {{ 'auto', 'tchebi', 'pbi' }}\n The decomposition approach that should be used. If set to `auto` for two objectives `tchebi` and for more than\n two `pbi` will be used.\n\n n_neighbors : int\n Number of neighboring reference lines to be used for selection.\n\n prob_neighbor_mating : float\n Probability of selecting the parents in the neighborhood.\n\n\n Returns\n -------\n moead : :class:`~pymoo.model.algorithm.MOEAD`\n Returns an MOEAD algorithm object.\n\n\n "
return MOEAD(ref_dirs, n_neighbors=n_neighbors, decomposition=decomposition, prob_neighbor_mating=prob_neighbor_mating, **kwargs)
|
def moead(ref_dirs, n_neighbors=15, decomposition='auto', prob_neighbor_mating=0.7, **kwargs):
"\n\n Parameters\n ----------\n ref_dirs : {ref_dirs}\n\n decomposition : {{ 'auto', 'tchebi', 'pbi' }}\n The decomposition approach that should be used. If set to `auto` for two objectives `tchebi` and for more than\n two `pbi` will be used.\n\n n_neighbors : int\n Number of neighboring reference lines to be used for selection.\n\n prob_neighbor_mating : float\n Probability of selecting the parents in the neighborhood.\n\n\n Returns\n -------\n moead : :class:`~pymoo.model.algorithm.MOEAD`\n Returns an MOEAD algorithm object.\n\n\n "
return MOEAD(ref_dirs, n_neighbors=n_neighbors, decomposition=decomposition, prob_neighbor_mating=prob_neighbor_mating, **kwargs)<|docstring|>Parameters
----------
ref_dirs : {ref_dirs}
decomposition : {{ 'auto', 'tchebi', 'pbi' }}
The decomposition approach that should be used. If set to `auto` for two objectives `tchebi` and for more than
two `pbi` will be used.
n_neighbors : int
Number of neighboring reference lines to be used for selection.
prob_neighbor_mating : float
Probability of selecting the parents in the neighborhood.
Returns
-------
moead : :class:`~pymoo.model.algorithm.MOEAD`
Returns an MOEAD algorithm object.<|endoftext|>
|
5ad822d2cb3e00adcefe57a780155591a49b1fff9d3e429292f0ffafad38e6cf
|
def AddPosts():
"\n p = Post(body='my first post!', author=u)\n db.session.add(p)\n db.session.commit()\n "
|
p = Post(body='my first post!', author=u)
db.session.add(p)
db.session.commit()
|
version/v4/microblog/app/models.py
|
AddPosts
|
Twenkid/flask-mega-tutorial
| 0
|
python
|
def AddPosts():
"\n p = Post(body='my first post!', author=u)\n db.session.add(p)\n db.session.commit()\n "
|
def AddPosts():
"\n p = Post(body='my first post!', author=u)\n db.session.add(p)\n db.session.commit()\n "<|docstring|>p = Post(body='my first post!', author=u)
db.session.add(p)
db.session.commit()<|endoftext|>
|
8be5008c69c2cad16f59d535ce0f6903211fb06645f9286e9458c25944d1e910
|
def inputs(argv):
'\n Takes inputs from command line. \n Inputs:\n -f <freq> = centre frequency in MHz\n -s <source> = source name in RA-DEC convention from miriad\n -1 <start_chan> = starting channel number\n -2 <end_chan> = final channel number\n -d <step_size> = channel step_size for images\n -b <field_size> = size of field in pixels \n -n <core_num> = number of cores to run task on\n '
freq = ''
mfs = False
clean = False
try:
(opts, args) = getopt.getopt(argv, 'hcf:s:1:2:d:b:n:', ['freq=', 'source=', 'start_chan=', 'end_chan=', 'step_size=', 'field_size=', 'core_num='])
print(opts, args)
except getopt.GetoptError:
print('input error, check format')
sys.exit(2)
for (opt, arg) in opts:
if (opt == '-h'):
print('\n Takes inputs from command line. \n Inputs:\n -f <freq> = centre frequency in MHz\n -s <source> = source name in RA-DEC convention from miriad\n -1 <start_chan> = starting channel number\n -2 <end_chan> = final channel number\n -d <step_size> = channel step_size for images\n -b <field_size> = size of field in pixels \n -n <core_num> = number of cores to run task on\n ')
sys.exit()
elif (opt in ('-f', '--freq')):
freq = arg
elif (opt in ('-1', '--start_chan')):
schan = int(arg)
elif (opt in ('-2', '--end_chan')):
echan = int(arg)
elif (opt in ('-s', '--source')):
source = arg
elif (opt in ('-d', '--step_size')):
step = int(arg)
elif (opt in ('-b', '--field_size')):
field = int(arg)
elif (opt in ('-n', '--core_num')):
core = int(arg)
return (freq, source, schan, echan, step, field, core)
|
Takes inputs from command line.
Inputs:
-f <freq> = centre frequency in MHz
-s <source> = source name in RA-DEC convention from miriad
-1 <start_chan> = starting channel number
-2 <end_chan> = final channel number
-d <step_size> = channel step_size for images
-b <field_size> = size of field in pixels
-n <core_num> = number of cores to run task on
|
MM_inverter.py
|
inputs
|
AlecThomson/Miriad_Multicore
| 0
|
python
|
def inputs(argv):
'\n Takes inputs from command line. \n Inputs:\n -f <freq> = centre frequency in MHz\n -s <source> = source name in RA-DEC convention from miriad\n -1 <start_chan> = starting channel number\n -2 <end_chan> = final channel number\n -d <step_size> = channel step_size for images\n -b <field_size> = size of field in pixels \n -n <core_num> = number of cores to run task on\n '
freq =
mfs = False
clean = False
try:
(opts, args) = getopt.getopt(argv, 'hcf:s:1:2:d:b:n:', ['freq=', 'source=', 'start_chan=', 'end_chan=', 'step_size=', 'field_size=', 'core_num='])
print(opts, args)
except getopt.GetoptError:
print('input error, check format')
sys.exit(2)
for (opt, arg) in opts:
if (opt == '-h'):
print('\n Takes inputs from command line. \n Inputs:\n -f <freq> = centre frequency in MHz\n -s <source> = source name in RA-DEC convention from miriad\n -1 <start_chan> = starting channel number\n -2 <end_chan> = final channel number\n -d <step_size> = channel step_size for images\n -b <field_size> = size of field in pixels \n -n <core_num> = number of cores to run task on\n ')
sys.exit()
elif (opt in ('-f', '--freq')):
freq = arg
elif (opt in ('-1', '--start_chan')):
schan = int(arg)
elif (opt in ('-2', '--end_chan')):
echan = int(arg)
elif (opt in ('-s', '--source')):
source = arg
elif (opt in ('-d', '--step_size')):
step = int(arg)
elif (opt in ('-b', '--field_size')):
field = int(arg)
elif (opt in ('-n', '--core_num')):
core = int(arg)
return (freq, source, schan, echan, step, field, core)
|
def inputs(argv):
'\n Takes inputs from command line. \n Inputs:\n -f <freq> = centre frequency in MHz\n -s <source> = source name in RA-DEC convention from miriad\n -1 <start_chan> = starting channel number\n -2 <end_chan> = final channel number\n -d <step_size> = channel step_size for images\n -b <field_size> = size of field in pixels \n -n <core_num> = number of cores to run task on\n '
freq =
mfs = False
clean = False
try:
(opts, args) = getopt.getopt(argv, 'hcf:s:1:2:d:b:n:', ['freq=', 'source=', 'start_chan=', 'end_chan=', 'step_size=', 'field_size=', 'core_num='])
print(opts, args)
except getopt.GetoptError:
print('input error, check format')
sys.exit(2)
for (opt, arg) in opts:
if (opt == '-h'):
print('\n Takes inputs from command line. \n Inputs:\n -f <freq> = centre frequency in MHz\n -s <source> = source name in RA-DEC convention from miriad\n -1 <start_chan> = starting channel number\n -2 <end_chan> = final channel number\n -d <step_size> = channel step_size for images\n -b <field_size> = size of field in pixels \n -n <core_num> = number of cores to run task on\n ')
sys.exit()
elif (opt in ('-f', '--freq')):
freq = arg
elif (opt in ('-1', '--start_chan')):
schan = int(arg)
elif (opt in ('-2', '--end_chan')):
echan = int(arg)
elif (opt in ('-s', '--source')):
source = arg
elif (opt in ('-d', '--step_size')):
step = int(arg)
elif (opt in ('-b', '--field_size')):
field = int(arg)
elif (opt in ('-n', '--core_num')):
core = int(arg)
return (freq, source, schan, echan, step, field, core)<|docstring|>Takes inputs from command line.
Inputs:
-f <freq> = centre frequency in MHz
-s <source> = source name in RA-DEC convention from miriad
-1 <start_chan> = starting channel number
-2 <end_chan> = final channel number
-d <step_size> = channel step_size for images
-b <field_size> = size of field in pixels
-n <core_num> = number of cores to run task on<|endoftext|>
|
ba9ea2f224ca0fd54f10aa311228b75d08267677ef72a1a001884469c961f2b5
|
def grid_images(t):
'\n Takes inputs and runs miriad invert from command line producing dirty maps and beams\n \n User Inputs:\n t = core index\n \n Other Inputs:\n outputs from inputs function above\n \n Outputs:\n for each channel band produces dirty maps (.map) for each Stokes parameter and beam images\n '
uvaver_locations = glob.glob(f'../../*/*/{source}*.uvaver')
var_strs = ','.join(uvaver_locations)
stokespars = ['i', 'q', 'u', 'v']
print(f'Loading in {var_strs}')
start = (schan + (int(((echan - schan) / core)) * t))
end = (schan + (int(((echan - schan) / core)) * (t + 1)))
for chan in range(start, end, step):
(im, qm, um, vm) = [f'{source}.{freq}.{chan:04d}.{a}.map' for a in stokespars]
beam = f'{source}.{freq}.{chan:04d}.beam'
maps = ','.join([im, qm, um, vm])
if ((not os.path.isdir(im)) and (not os.path.isdir(beam))):
chan_str = f'chan,{step},{chan}'
stokes_str = ','.join(stokespars)
cmd = f'invert vis={var_strs} map={maps} beam={beam} line={chan_str} imsize={field},{field} cell=1,1 robust=+0.6 stokes={stokes_str} options=double,mfs'
print(cmd)
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
for line in p.stdout:
print(line)
p.wait()
|
Takes inputs and runs miriad invert from command line producing dirty maps and beams
User Inputs:
t = core index
Other Inputs:
outputs from inputs function above
Outputs:
for each channel band produces dirty maps (.map) for each Stokes parameter and beam images
|
MM_inverter.py
|
grid_images
|
AlecThomson/Miriad_Multicore
| 0
|
python
|
def grid_images(t):
'\n Takes inputs and runs miriad invert from command line producing dirty maps and beams\n \n User Inputs:\n t = core index\n \n Other Inputs:\n outputs from inputs function above\n \n Outputs:\n for each channel band produces dirty maps (.map) for each Stokes parameter and beam images\n '
uvaver_locations = glob.glob(f'../../*/*/{source}*.uvaver')
var_strs = ','.join(uvaver_locations)
stokespars = ['i', 'q', 'u', 'v']
print(f'Loading in {var_strs}')
start = (schan + (int(((echan - schan) / core)) * t))
end = (schan + (int(((echan - schan) / core)) * (t + 1)))
for chan in range(start, end, step):
(im, qm, um, vm) = [f'{source}.{freq}.{chan:04d}.{a}.map' for a in stokespars]
beam = f'{source}.{freq}.{chan:04d}.beam'
maps = ','.join([im, qm, um, vm])
if ((not os.path.isdir(im)) and (not os.path.isdir(beam))):
chan_str = f'chan,{step},{chan}'
stokes_str = ','.join(stokespars)
cmd = f'invert vis={var_strs} map={maps} beam={beam} line={chan_str} imsize={field},{field} cell=1,1 robust=+0.6 stokes={stokes_str} options=double,mfs'
print(cmd)
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
for line in p.stdout:
print(line)
p.wait()
|
def grid_images(t):
'\n Takes inputs and runs miriad invert from command line producing dirty maps and beams\n \n User Inputs:\n t = core index\n \n Other Inputs:\n outputs from inputs function above\n \n Outputs:\n for each channel band produces dirty maps (.map) for each Stokes parameter and beam images\n '
uvaver_locations = glob.glob(f'../../*/*/{source}*.uvaver')
var_strs = ','.join(uvaver_locations)
stokespars = ['i', 'q', 'u', 'v']
print(f'Loading in {var_strs}')
start = (schan + (int(((echan - schan) / core)) * t))
end = (schan + (int(((echan - schan) / core)) * (t + 1)))
for chan in range(start, end, step):
(im, qm, um, vm) = [f'{source}.{freq}.{chan:04d}.{a}.map' for a in stokespars]
beam = f'{source}.{freq}.{chan:04d}.beam'
maps = ','.join([im, qm, um, vm])
if ((not os.path.isdir(im)) and (not os.path.isdir(beam))):
chan_str = f'chan,{step},{chan}'
stokes_str = ','.join(stokespars)
cmd = f'invert vis={var_strs} map={maps} beam={beam} line={chan_str} imsize={field},{field} cell=1,1 robust=+0.6 stokes={stokes_str} options=double,mfs'
print(cmd)
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
for line in p.stdout:
print(line)
p.wait()<|docstring|>Takes inputs and runs miriad invert from command line producing dirty maps and beams
User Inputs:
t = core index
Other Inputs:
outputs from inputs function above
Outputs:
for each channel band produces dirty maps (.map) for each Stokes parameter and beam images<|endoftext|>
|
6119ebc6b1e31aa13e3b5686cf0e8546f1d302ee9dcddbe2b06ab537a4a88680
|
def __str__(self):
' Convert this card to JSON format for saving.'
return json.dumps({'name': str(self.name), 'category': self.menu.value.get(), 'costs': {k: str(v) for (k, v) in self.costs.items()}, 'rules': str(self.description)}, indent=4)
|
Convert this card to JSON format for saving.
|
CardPrototype.pyw
|
__str__
|
WeRelic/MinervaCardTools
| 0
|
python
|
def __str__(self):
' '
return json.dumps({'name': str(self.name), 'category': self.menu.value.get(), 'costs': {k: str(v) for (k, v) in self.costs.items()}, 'rules': str(self.description)}, indent=4)
|
def __str__(self):
' '
return json.dumps({'name': str(self.name), 'category': self.menu.value.get(), 'costs': {k: str(v) for (k, v) in self.costs.items()}, 'rules': str(self.description)}, indent=4)<|docstring|>Convert this card to JSON format for saving.<|endoftext|>
|
277d7316f6789e6c51f898b7ac1dcf46b689f8ff07fbf2fae0c5ae2782cdd81b
|
def generate_pips(self):
" \n This function generates a single image containing all the pips required to represent the casting cost for a card. \n Do not call this function directly, it's intended as a helper function for 'CardEntry.generate_image'\n "
resources = ['energy', 'ore', 'scrap', 'alloy', 'research']
cost = (lambda k: self.costs[k].value.get())
generic = (None if (cost('any') == 0) else generic_pips[(cost('any') - 1)].copy())
total_pips = ((1, 0)[(cost('any') == 0)] + sum([cost(k) for k in resources]))
(pip_w, pip_h) = ((total_pips * 221), 221)
pip_image = Image.new('RGBA', (pip_w, pip_h), (0, 0, 0, 0))
pip_list = []
if generic:
pip_list.append(generic)
for k in resources:
for n in range(cost(k)):
pip_list.append(pip_images[k].copy())
for pip in enumerate(pip_list):
pip_image.paste(pip[1], ((pip[0] * 221), 0), pip[1])
pip_image.save(local_path('src\\temp_pips.png'))
return pip_image
|
This function generates a single image containing all the pips required to represent the casting cost for a card.
Do not call this function directly, it's intended as a helper function for 'CardEntry.generate_image'
|
CardPrototype.pyw
|
generate_pips
|
WeRelic/MinervaCardTools
| 0
|
python
|
def generate_pips(self):
" \n This function generates a single image containing all the pips required to represent the casting cost for a card. \n Do not call this function directly, it's intended as a helper function for 'CardEntry.generate_image'\n "
resources = ['energy', 'ore', 'scrap', 'alloy', 'research']
cost = (lambda k: self.costs[k].value.get())
generic = (None if (cost('any') == 0) else generic_pips[(cost('any') - 1)].copy())
total_pips = ((1, 0)[(cost('any') == 0)] + sum([cost(k) for k in resources]))
(pip_w, pip_h) = ((total_pips * 221), 221)
pip_image = Image.new('RGBA', (pip_w, pip_h), (0, 0, 0, 0))
pip_list = []
if generic:
pip_list.append(generic)
for k in resources:
for n in range(cost(k)):
pip_list.append(pip_images[k].copy())
for pip in enumerate(pip_list):
pip_image.paste(pip[1], ((pip[0] * 221), 0), pip[1])
pip_image.save(local_path('src\\temp_pips.png'))
return pip_image
|
def generate_pips(self):
" \n This function generates a single image containing all the pips required to represent the casting cost for a card. \n Do not call this function directly, it's intended as a helper function for 'CardEntry.generate_image'\n "
resources = ['energy', 'ore', 'scrap', 'alloy', 'research']
cost = (lambda k: self.costs[k].value.get())
generic = (None if (cost('any') == 0) else generic_pips[(cost('any') - 1)].copy())
total_pips = ((1, 0)[(cost('any') == 0)] + sum([cost(k) for k in resources]))
(pip_w, pip_h) = ((total_pips * 221), 221)
pip_image = Image.new('RGBA', (pip_w, pip_h), (0, 0, 0, 0))
pip_list = []
if generic:
pip_list.append(generic)
for k in resources:
for n in range(cost(k)):
pip_list.append(pip_images[k].copy())
for pip in enumerate(pip_list):
pip_image.paste(pip[1], ((pip[0] * 221), 0), pip[1])
pip_image.save(local_path('src\\temp_pips.png'))
return pip_image<|docstring|>This function generates a single image containing all the pips required to represent the casting cost for a card.
Do not call this function directly, it's intended as a helper function for 'CardEntry.generate_image'<|endoftext|>
|
2040fdde11eefb2c2bfd43adec6438a8ccd3d222696c898181eaeef071a8a996
|
def generate_rules_text(self):
" \n This function generates an image containing the rules text for this card. \n Do not call this function directly. It's merely a helper for 'CardEntry.generate_image'\n "
rules_font = ImageFont.truetype(local_path('src\\OptimusPrinceps.ttf'), 200)
img = Image.new('RGBA', (3025, 4075), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
wrap = textwrap.TextWrapper(width=26, replace_whitespace=False)
text = wrap.fill(str(self.rules))
draw.multiline_text((0, 0), text, font=rules_font, fill=(0, 0, 0))
return img
|
This function generates an image containing the rules text for this card.
Do not call this function directly. It's merely a helper for 'CardEntry.generate_image'
|
CardPrototype.pyw
|
generate_rules_text
|
WeRelic/MinervaCardTools
| 0
|
python
|
def generate_rules_text(self):
" \n This function generates an image containing the rules text for this card. \n Do not call this function directly. It's merely a helper for 'CardEntry.generate_image'\n "
rules_font = ImageFont.truetype(local_path('src\\OptimusPrinceps.ttf'), 200)
img = Image.new('RGBA', (3025, 4075), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
wrap = textwrap.TextWrapper(width=26, replace_whitespace=False)
text = wrap.fill(str(self.rules))
draw.multiline_text((0, 0), text, font=rules_font, fill=(0, 0, 0))
return img
|
def generate_rules_text(self):
" \n This function generates an image containing the rules text for this card. \n Do not call this function directly. It's merely a helper for 'CardEntry.generate_image'\n "
rules_font = ImageFont.truetype(local_path('src\\OptimusPrinceps.ttf'), 200)
img = Image.new('RGBA', (3025, 4075), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
wrap = textwrap.TextWrapper(width=26, replace_whitespace=False)
text = wrap.fill(str(self.rules))
draw.multiline_text((0, 0), text, font=rules_font, fill=(0, 0, 0))
return img<|docstring|>This function generates an image containing the rules text for this card.
Do not call this function directly. It's merely a helper for 'CardEntry.generate_image'<|endoftext|>
|
afb40d400bf1da25ca5279c58396c80136459c27a7fa947623c427076f0192fd
|
def generate_image(self, preview=False):
' This function generates the entire face image for this card. '
global card_index
print('Generating Card Image... ')
new_image = new_card_image()
(cw, ch) = (int((new_image.size[0] / 2)), int((new_image.size[1] / 2)))
name = ImageDraw.Draw(new_image)
text_size = font.getsize(self.name.value.get())
name.text(((cw - (text_size[0] / 2)), 100), self.name.value.get(), fill='black', font=font)
pips = self.generate_pips()
new_image.paste(pips, ((cw - int((pips.size[0] / 2))), (120 + text_size[1])), pips)
rules = self.generate_rules_text()
(rw, rh) = (int((rules.size[0] / 2)), int((rules.size[1] / 2)))
new_image.paste(rules, ((cw - rw), ((200 + text_size[1]) + pips.size[1])), rules)
filename = (self.name.value.get().replace(' ', '_') + '.png')
category = self.menu.value.get()
if preview:
new_image.show()
else:
new_image.save(local_path(f'img\{category}\{filename}'))
|
This function generates the entire face image for this card.
|
CardPrototype.pyw
|
generate_image
|
WeRelic/MinervaCardTools
| 0
|
python
|
def generate_image(self, preview=False):
' '
global card_index
print('Generating Card Image... ')
new_image = new_card_image()
(cw, ch) = (int((new_image.size[0] / 2)), int((new_image.size[1] / 2)))
name = ImageDraw.Draw(new_image)
text_size = font.getsize(self.name.value.get())
name.text(((cw - (text_size[0] / 2)), 100), self.name.value.get(), fill='black', font=font)
pips = self.generate_pips()
new_image.paste(pips, ((cw - int((pips.size[0] / 2))), (120 + text_size[1])), pips)
rules = self.generate_rules_text()
(rw, rh) = (int((rules.size[0] / 2)), int((rules.size[1] / 2)))
new_image.paste(rules, ((cw - rw), ((200 + text_size[1]) + pips.size[1])), rules)
filename = (self.name.value.get().replace(' ', '_') + '.png')
category = self.menu.value.get()
if preview:
new_image.show()
else:
new_image.save(local_path(f'img\{category}\{filename}'))
|
def generate_image(self, preview=False):
' '
global card_index
print('Generating Card Image... ')
new_image = new_card_image()
(cw, ch) = (int((new_image.size[0] / 2)), int((new_image.size[1] / 2)))
name = ImageDraw.Draw(new_image)
text_size = font.getsize(self.name.value.get())
name.text(((cw - (text_size[0] / 2)), 100), self.name.value.get(), fill='black', font=font)
pips = self.generate_pips()
new_image.paste(pips, ((cw - int((pips.size[0] / 2))), (120 + text_size[1])), pips)
rules = self.generate_rules_text()
(rw, rh) = (int((rules.size[0] / 2)), int((rules.size[1] / 2)))
new_image.paste(rules, ((cw - rw), ((200 + text_size[1]) + pips.size[1])), rules)
filename = (self.name.value.get().replace(' ', '_') + '.png')
category = self.menu.value.get()
if preview:
new_image.show()
else:
new_image.save(local_path(f'img\{category}\{filename}'))<|docstring|>This function generates the entire face image for this card.<|endoftext|>
|
d6f94d9d5466f865178d82fcfb6e36d7d42b608fb950061910a70ca5895217dd
|
def export_file(self, fp: str, path: str='') -> None:
'Save a part of the data into a single file'
keys = self.path_to_keys(path)
root = self._go_at(keys)
JsonFile.save(fp, root)
|
Save a part of the data into a single file
|
tools37/JsonLoader.py
|
export_file
|
GabrielAmare/Tools37
| 0
|
python
|
def export_file(self, fp: str, path: str=) -> None:
keys = self.path_to_keys(path)
root = self._go_at(keys)
JsonFile.save(fp, root)
|
def export_file(self, fp: str, path: str=) -> None:
keys = self.path_to_keys(path)
root = self._go_at(keys)
JsonFile.save(fp, root)<|docstring|>Save a part of the data into a single file<|endoftext|>
|
d7ad2886f85c26408d88cf02d978d295e62c63429c491d13ddd017f8aef3f8b4
|
def import_file(self, fp: str, path: str='') -> None:
'Load a single file into the data'
data = JsonFile.load(fp)
keys = self.path_to_keys(path)
root = self._go_at(keys, force_path=True)
def include(origin: dict, add: dict):
for (key, val) in add.items():
if isinstance(val, dict):
origin.setdefault(key, {})
include(origin[key], val)
else:
origin[key] = val
include(root, data)
|
Load a single file into the data
|
tools37/JsonLoader.py
|
import_file
|
GabrielAmare/Tools37
| 0
|
python
|
def import_file(self, fp: str, path: str=) -> None:
data = JsonFile.load(fp)
keys = self.path_to_keys(path)
root = self._go_at(keys, force_path=True)
def include(origin: dict, add: dict):
for (key, val) in add.items():
if isinstance(val, dict):
origin.setdefault(key, {})
include(origin[key], val)
else:
origin[key] = val
include(root, data)
|
def import_file(self, fp: str, path: str=) -> None:
data = JsonFile.load(fp)
keys = self.path_to_keys(path)
root = self._go_at(keys, force_path=True)
def include(origin: dict, add: dict):
for (key, val) in add.items():
if isinstance(val, dict):
origin.setdefault(key, {})
include(origin[key], val)
else:
origin[key] = val
include(root, data)<|docstring|>Load a single file into the data<|endoftext|>
|
56d16358a37a7353008b57ade64abfc2c9f90b26d1edd6038597fafb677f4e19
|
def square(t, duty=0.5):
'\n Return a periodic square-wave waveform.\n\n The square wave has a period ``2*pi``, has value +1 from 0 to\n ``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in\n the interval [0,1].\n\n Note that this is not band-limited. It produces an infinite number\n of harmonics, which are aliased back and forth across the frequency\n spectrum.\n\n Parameters\n ----------\n t : array_like\n The input time array.\n duty : array_like, optional\n Duty cycle. Default is 0.5 (50% duty cycle).\n If an array, causes wave shape to change over time, and must be the\n same length as t.\n\n Returns\n -------\n y : ndarray\n Output array containing the square waveform.\n\n Examples\n --------\n A 5 Hz waveform sampled at 500 Hz for 1 second:\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> t = np.linspace(0, 1, 500, endpoint=False)\n >>> plt.plot(t, signal.square(2 * np.pi * 5 * t))\n >>> plt.ylim(-2, 2)\n\n A pulse-width modulated sine wave:\n\n >>> plt.figure()\n >>> sig = np.sin(2 * np.pi * t)\n >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)\n >>> plt.subplot(2, 1, 1)\n >>> plt.plot(t, sig)\n >>> plt.subplot(2, 1, 2)\n >>> plt.plot(t, pwm)\n >>> plt.ylim(-1.5, 1.5)\n\n '
(t, w) = (asarray(t), asarray(duty))
w = asarray((w + (t - t)))
t = asarray((t + (w - w)))
if (t.dtype.char in ['fFdD']):
ytype = t.dtype.char
else:
ytype = 'd'
y = zeros(t.shape, ytype)
mask1 = ((w > 1) | (w < 0))
place(y, mask1, nan)
tmod = mod(t, (2 * pi))
mask2 = ((1 - mask1) & (tmod < ((w * 2) * pi)))
place(y, mask2, 1)
mask3 = ((1 - mask1) & (1 - mask2))
place(y, mask3, (- 1))
return y
|
Return a periodic square-wave waveform.
The square wave has a period ``2*pi``, has value +1 from 0 to
``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in
the interval [0,1].
Note that this is not band-limited. It produces an infinite number
of harmonics, which are aliased back and forth across the frequency
spectrum.
Parameters
----------
t : array_like
The input time array.
duty : array_like, optional
Duty cycle. Default is 0.5 (50% duty cycle).
If an array, causes wave shape to change over time, and must be the
same length as t.
Returns
-------
y : ndarray
Output array containing the square waveform.
Examples
--------
A 5 Hz waveform sampled at 500 Hz for 1 second:
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(0, 1, 500, endpoint=False)
>>> plt.plot(t, signal.square(2 * np.pi * 5 * t))
>>> plt.ylim(-2, 2)
A pulse-width modulated sine wave:
>>> plt.figure()
>>> sig = np.sin(2 * np.pi * t)
>>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
>>> plt.subplot(2, 1, 1)
>>> plt.plot(t, sig)
>>> plt.subplot(2, 1, 2)
>>> plt.plot(t, pwm)
>>> plt.ylim(-1.5, 1.5)
|
cusignal/waveforms.py
|
square
|
andrewpalumbo/cusignal
| 1
|
python
|
def square(t, duty=0.5):
'\n Return a periodic square-wave waveform.\n\n The square wave has a period ``2*pi``, has value +1 from 0 to\n ``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in\n the interval [0,1].\n\n Note that this is not band-limited. It produces an infinite number\n of harmonics, which are aliased back and forth across the frequency\n spectrum.\n\n Parameters\n ----------\n t : array_like\n The input time array.\n duty : array_like, optional\n Duty cycle. Default is 0.5 (50% duty cycle).\n If an array, causes wave shape to change over time, and must be the\n same length as t.\n\n Returns\n -------\n y : ndarray\n Output array containing the square waveform.\n\n Examples\n --------\n A 5 Hz waveform sampled at 500 Hz for 1 second:\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> t = np.linspace(0, 1, 500, endpoint=False)\n >>> plt.plot(t, signal.square(2 * np.pi * 5 * t))\n >>> plt.ylim(-2, 2)\n\n A pulse-width modulated sine wave:\n\n >>> plt.figure()\n >>> sig = np.sin(2 * np.pi * t)\n >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)\n >>> plt.subplot(2, 1, 1)\n >>> plt.plot(t, sig)\n >>> plt.subplot(2, 1, 2)\n >>> plt.plot(t, pwm)\n >>> plt.ylim(-1.5, 1.5)\n\n '
(t, w) = (asarray(t), asarray(duty))
w = asarray((w + (t - t)))
t = asarray((t + (w - w)))
if (t.dtype.char in ['fFdD']):
ytype = t.dtype.char
else:
ytype = 'd'
y = zeros(t.shape, ytype)
mask1 = ((w > 1) | (w < 0))
place(y, mask1, nan)
tmod = mod(t, (2 * pi))
mask2 = ((1 - mask1) & (tmod < ((w * 2) * pi)))
place(y, mask2, 1)
mask3 = ((1 - mask1) & (1 - mask2))
place(y, mask3, (- 1))
return y
|
def square(t, duty=0.5):
'\n Return a periodic square-wave waveform.\n\n The square wave has a period ``2*pi``, has value +1 from 0 to\n ``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in\n the interval [0,1].\n\n Note that this is not band-limited. It produces an infinite number\n of harmonics, which are aliased back and forth across the frequency\n spectrum.\n\n Parameters\n ----------\n t : array_like\n The input time array.\n duty : array_like, optional\n Duty cycle. Default is 0.5 (50% duty cycle).\n If an array, causes wave shape to change over time, and must be the\n same length as t.\n\n Returns\n -------\n y : ndarray\n Output array containing the square waveform.\n\n Examples\n --------\n A 5 Hz waveform sampled at 500 Hz for 1 second:\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> t = np.linspace(0, 1, 500, endpoint=False)\n >>> plt.plot(t, signal.square(2 * np.pi * 5 * t))\n >>> plt.ylim(-2, 2)\n\n A pulse-width modulated sine wave:\n\n >>> plt.figure()\n >>> sig = np.sin(2 * np.pi * t)\n >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)\n >>> plt.subplot(2, 1, 1)\n >>> plt.plot(t, sig)\n >>> plt.subplot(2, 1, 2)\n >>> plt.plot(t, pwm)\n >>> plt.ylim(-1.5, 1.5)\n\n '
(t, w) = (asarray(t), asarray(duty))
w = asarray((w + (t - t)))
t = asarray((t + (w - w)))
if (t.dtype.char in ['fFdD']):
ytype = t.dtype.char
else:
ytype = 'd'
y = zeros(t.shape, ytype)
mask1 = ((w > 1) | (w < 0))
place(y, mask1, nan)
tmod = mod(t, (2 * pi))
mask2 = ((1 - mask1) & (tmod < ((w * 2) * pi)))
place(y, mask2, 1)
mask3 = ((1 - mask1) & (1 - mask2))
place(y, mask3, (- 1))
return y<|docstring|>Return a periodic square-wave waveform.
The square wave has a period ``2*pi``, has value +1 from 0 to
``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in
the interval [0,1].
Note that this is not band-limited. It produces an infinite number
of harmonics, which are aliased back and forth across the frequency
spectrum.
Parameters
----------
t : array_like
The input time array.
duty : array_like, optional
Duty cycle. Default is 0.5 (50% duty cycle).
If an array, causes wave shape to change over time, and must be the
same length as t.
Returns
-------
y : ndarray
Output array containing the square waveform.
Examples
--------
A 5 Hz waveform sampled at 500 Hz for 1 second:
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(0, 1, 500, endpoint=False)
>>> plt.plot(t, signal.square(2 * np.pi * 5 * t))
>>> plt.ylim(-2, 2)
A pulse-width modulated sine wave:
>>> plt.figure()
>>> sig = np.sin(2 * np.pi * t)
>>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
>>> plt.subplot(2, 1, 1)
>>> plt.plot(t, sig)
>>> plt.subplot(2, 1, 2)
>>> plt.plot(t, pwm)
>>> plt.ylim(-1.5, 1.5)<|endoftext|>
|
ab2837a4820a3917ebeaab72cdfe8a083b4162e2933376e4c0100228d20b2e3a
|
def gausspulse(t, fc=1000, bw=0.5, bwr=(- 6), tpr=(- 60), retquad=False, retenv=False):
"\n Return a Gaussian modulated sinusoid:\n\n ``exp(-a t^2) exp(1j*2*pi*fc*t).``\n\n If `retquad` is True, then return the real and imaginary parts\n (in-phase and quadrature).\n If `retenv` is True, then return the envelope (unmodulated signal).\n Otherwise, return the real part of the modulated sinusoid.\n\n Parameters\n ----------\n t : ndarray or the string 'cutoff'\n Input array.\n fc : int, optional\n Center frequency (e.g. Hz). Default is 1000.\n bw : float, optional\n Fractional bandwidth in frequency domain of pulse (e.g. Hz).\n Default is 0.5.\n bwr : float, optional\n Reference level at which fractional bandwidth is calculated (dB).\n Default is -6.\n tpr : float, optional\n If `t` is 'cutoff', then the function returns the cutoff\n time for when the pulse amplitude falls below `tpr` (in dB).\n Default is -60.\n retquad : bool, optional\n If True, return the quadrature (imaginary) as well as the real part\n of the signal. Default is False.\n retenv : bool, optional\n If True, return the envelope of the signal. Default is False.\n\n Returns\n -------\n yI : ndarray\n Real part of signal. Always returned.\n yQ : ndarray\n Imaginary part of signal. Only returned if `retquad` is True.\n yenv : ndarray\n Envelope of signal. Only returned if `retenv` is True.\n\n See Also\n --------\n scipy.signal.morlet\n\n Examples\n --------\n Plot real component, imaginary component, and envelope for a 5 Hz pulse,\n sampled at 100 Hz for 2 seconds:\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)\n >>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)\n >>> plt.plot(t, i, t, q, t, e, '--')\n\n "
if (fc < 0):
raise ValueError(('Center frequency (fc=%.2f) must be >=0.' % fc))
if (bw <= 0):
raise ValueError(('Fractional bandwidth (bw=%.2f) must be > 0.' % bw))
if (bwr >= 0):
raise ValueError(('Reference level for bandwidth (bwr=%.2f) must be < 0 dB' % bwr))
ref = pow(10.0, (bwr / 20.0))
a = ((- (((pi * fc) * bw) ** 2)) / (4.0 * log(ref)))
if isinstance(t, string_types):
if (t == 'cutoff'):
if (tpr >= 0):
raise ValueError('Reference level for time cutoff must be < 0 dB')
tref = pow(10.0, (tpr / 20.0))
return sqrt(((- log(tref)) / a))
else:
raise ValueError("If `t` is a string, it must be 'cutoff'")
yenv = exp((((- a) * t) * t))
yI = (yenv * cos((((2 * pi) * fc) * t)))
yQ = (yenv * sin((((2 * pi) * fc) * t)))
if ((not retquad) and (not retenv)):
return yI
if ((not retquad) and retenv):
return (yI, yenv)
if (retquad and (not retenv)):
return (yI, yQ)
if (retquad and retenv):
return (yI, yQ, yenv)
|
Return a Gaussian modulated sinusoid:
``exp(-a t^2) exp(1j*2*pi*fc*t).``
If `retquad` is True, then return the real and imaginary parts
(in-phase and quadrature).
If `retenv` is True, then return the envelope (unmodulated signal).
Otherwise, return the real part of the modulated sinusoid.
Parameters
----------
t : ndarray or the string 'cutoff'
Input array.
fc : int, optional
Center frequency (e.g. Hz). Default is 1000.
bw : float, optional
Fractional bandwidth in frequency domain of pulse (e.g. Hz).
Default is 0.5.
bwr : float, optional
Reference level at which fractional bandwidth is calculated (dB).
Default is -6.
tpr : float, optional
If `t` is 'cutoff', then the function returns the cutoff
time for when the pulse amplitude falls below `tpr` (in dB).
Default is -60.
retquad : bool, optional
If True, return the quadrature (imaginary) as well as the real part
of the signal. Default is False.
retenv : bool, optional
If True, return the envelope of the signal. Default is False.
Returns
-------
yI : ndarray
Real part of signal. Always returned.
yQ : ndarray
Imaginary part of signal. Only returned if `retquad` is True.
yenv : ndarray
Envelope of signal. Only returned if `retenv` is True.
See Also
--------
scipy.signal.morlet
Examples
--------
Plot real component, imaginary component, and envelope for a 5 Hz pulse,
sampled at 100 Hz for 2 seconds:
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)
>>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)
>>> plt.plot(t, i, t, q, t, e, '--')
|
cusignal/waveforms.py
|
gausspulse
|
andrewpalumbo/cusignal
| 1
|
python
|
def gausspulse(t, fc=1000, bw=0.5, bwr=(- 6), tpr=(- 60), retquad=False, retenv=False):
"\n Return a Gaussian modulated sinusoid:\n\n ``exp(-a t^2) exp(1j*2*pi*fc*t).``\n\n If `retquad` is True, then return the real and imaginary parts\n (in-phase and quadrature).\n If `retenv` is True, then return the envelope (unmodulated signal).\n Otherwise, return the real part of the modulated sinusoid.\n\n Parameters\n ----------\n t : ndarray or the string 'cutoff'\n Input array.\n fc : int, optional\n Center frequency (e.g. Hz). Default is 1000.\n bw : float, optional\n Fractional bandwidth in frequency domain of pulse (e.g. Hz).\n Default is 0.5.\n bwr : float, optional\n Reference level at which fractional bandwidth is calculated (dB).\n Default is -6.\n tpr : float, optional\n If `t` is 'cutoff', then the function returns the cutoff\n time for when the pulse amplitude falls below `tpr` (in dB).\n Default is -60.\n retquad : bool, optional\n If True, return the quadrature (imaginary) as well as the real part\n of the signal. Default is False.\n retenv : bool, optional\n If True, return the envelope of the signal. Default is False.\n\n Returns\n -------\n yI : ndarray\n Real part of signal. Always returned.\n yQ : ndarray\n Imaginary part of signal. Only returned if `retquad` is True.\n yenv : ndarray\n Envelope of signal. Only returned if `retenv` is True.\n\n See Also\n --------\n scipy.signal.morlet\n\n Examples\n --------\n Plot real component, imaginary component, and envelope for a 5 Hz pulse,\n sampled at 100 Hz for 2 seconds:\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)\n >>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)\n >>> plt.plot(t, i, t, q, t, e, '--')\n\n "
if (fc < 0):
raise ValueError(('Center frequency (fc=%.2f) must be >=0.' % fc))
if (bw <= 0):
raise ValueError(('Fractional bandwidth (bw=%.2f) must be > 0.' % bw))
if (bwr >= 0):
raise ValueError(('Reference level for bandwidth (bwr=%.2f) must be < 0 dB' % bwr))
ref = pow(10.0, (bwr / 20.0))
a = ((- (((pi * fc) * bw) ** 2)) / (4.0 * log(ref)))
if isinstance(t, string_types):
if (t == 'cutoff'):
if (tpr >= 0):
raise ValueError('Reference level for time cutoff must be < 0 dB')
tref = pow(10.0, (tpr / 20.0))
return sqrt(((- log(tref)) / a))
else:
raise ValueError("If `t` is a string, it must be 'cutoff'")
yenv = exp((((- a) * t) * t))
yI = (yenv * cos((((2 * pi) * fc) * t)))
yQ = (yenv * sin((((2 * pi) * fc) * t)))
if ((not retquad) and (not retenv)):
return yI
if ((not retquad) and retenv):
return (yI, yenv)
if (retquad and (not retenv)):
return (yI, yQ)
if (retquad and retenv):
return (yI, yQ, yenv)
|
def gausspulse(t, fc=1000, bw=0.5, bwr=(- 6), tpr=(- 60), retquad=False, retenv=False):
"\n Return a Gaussian modulated sinusoid:\n\n ``exp(-a t^2) exp(1j*2*pi*fc*t).``\n\n If `retquad` is True, then return the real and imaginary parts\n (in-phase and quadrature).\n If `retenv` is True, then return the envelope (unmodulated signal).\n Otherwise, return the real part of the modulated sinusoid.\n\n Parameters\n ----------\n t : ndarray or the string 'cutoff'\n Input array.\n fc : int, optional\n Center frequency (e.g. Hz). Default is 1000.\n bw : float, optional\n Fractional bandwidth in frequency domain of pulse (e.g. Hz).\n Default is 0.5.\n bwr : float, optional\n Reference level at which fractional bandwidth is calculated (dB).\n Default is -6.\n tpr : float, optional\n If `t` is 'cutoff', then the function returns the cutoff\n time for when the pulse amplitude falls below `tpr` (in dB).\n Default is -60.\n retquad : bool, optional\n If True, return the quadrature (imaginary) as well as the real part\n of the signal. Default is False.\n retenv : bool, optional\n If True, return the envelope of the signal. Default is False.\n\n Returns\n -------\n yI : ndarray\n Real part of signal. Always returned.\n yQ : ndarray\n Imaginary part of signal. Only returned if `retquad` is True.\n yenv : ndarray\n Envelope of signal. Only returned if `retenv` is True.\n\n See Also\n --------\n scipy.signal.morlet\n\n Examples\n --------\n Plot real component, imaginary component, and envelope for a 5 Hz pulse,\n sampled at 100 Hz for 2 seconds:\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)\n >>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)\n >>> plt.plot(t, i, t, q, t, e, '--')\n\n "
if (fc < 0):
raise ValueError(('Center frequency (fc=%.2f) must be >=0.' % fc))
if (bw <= 0):
raise ValueError(('Fractional bandwidth (bw=%.2f) must be > 0.' % bw))
if (bwr >= 0):
raise ValueError(('Reference level for bandwidth (bwr=%.2f) must be < 0 dB' % bwr))
ref = pow(10.0, (bwr / 20.0))
a = ((- (((pi * fc) * bw) ** 2)) / (4.0 * log(ref)))
if isinstance(t, string_types):
if (t == 'cutoff'):
if (tpr >= 0):
raise ValueError('Reference level for time cutoff must be < 0 dB')
tref = pow(10.0, (tpr / 20.0))
return sqrt(((- log(tref)) / a))
else:
raise ValueError("If `t` is a string, it must be 'cutoff'")
yenv = exp((((- a) * t) * t))
yI = (yenv * cos((((2 * pi) * fc) * t)))
yQ = (yenv * sin((((2 * pi) * fc) * t)))
if ((not retquad) and (not retenv)):
return yI
if ((not retquad) and retenv):
return (yI, yenv)
if (retquad and (not retenv)):
return (yI, yQ)
if (retquad and retenv):
return (yI, yQ, yenv)<|docstring|>Return a Gaussian modulated sinusoid:
``exp(-a t^2) exp(1j*2*pi*fc*t).``
If `retquad` is True, then return the real and imaginary parts
(in-phase and quadrature).
If `retenv` is True, then return the envelope (unmodulated signal).
Otherwise, return the real part of the modulated sinusoid.
Parameters
----------
t : ndarray or the string 'cutoff'
Input array.
fc : int, optional
Center frequency (e.g. Hz). Default is 1000.
bw : float, optional
Fractional bandwidth in frequency domain of pulse (e.g. Hz).
Default is 0.5.
bwr : float, optional
Reference level at which fractional bandwidth is calculated (dB).
Default is -6.
tpr : float, optional
If `t` is 'cutoff', then the function returns the cutoff
time for when the pulse amplitude falls below `tpr` (in dB).
Default is -60.
retquad : bool, optional
If True, return the quadrature (imaginary) as well as the real part
of the signal. Default is False.
retenv : bool, optional
If True, return the envelope of the signal. Default is False.
Returns
-------
yI : ndarray
Real part of signal. Always returned.
yQ : ndarray
Imaginary part of signal. Only returned if `retquad` is True.
yenv : ndarray
Envelope of signal. Only returned if `retenv` is True.
See Also
--------
scipy.signal.morlet
Examples
--------
Plot real component, imaginary component, and envelope for a 5 Hz pulse,
sampled at 100 Hz for 2 seconds:
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)
>>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)
>>> plt.plot(t, i, t, q, t, e, '--')<|endoftext|>
|
c3b67e53ba7473654da02d2bf2659153fb0178dd7c0c72483d4b9c254890f779
|
def chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True):
'Frequency-swept cosine generator.\n\n In the following, \'Hz\' should be interpreted as \'cycles per unit\';\n there is no requirement here that the unit is one second. The\n important distinction is that the units of rotation are cycles, not\n radians. Likewise, `t` could be a measurement of space instead of time.\n\n Parameters\n ----------\n t : array_like\n Times at which to evaluate the waveform.\n f0 : float\n Frequency (e.g. Hz) at time t=0.\n t1 : float\n Time at which `f1` is specified.\n f1 : float\n Frequency (e.g. Hz) of the waveform at time `t1`.\n method : {\'linear\', \'quadratic\', \'logarithmic\', \'hyperbolic\'}, optional\n Kind of frequency sweep. If not given, `linear` is assumed. See\n Notes below for more details.\n phi : float, optional\n Phase offset, in degrees. Default is 0.\n vertex_zero : bool, optional\n This parameter is only used when `method` is \'quadratic\'.\n It determines whether the vertex of the parabola that is the graph\n of the frequency is at t=0 or t=t1.\n\n Returns\n -------\n y : ndarray\n A numpy array containing the signal evaluated at `t` with the\n requested time-varying frequency. More precisely, the function\n returns ``cos(phase + (pi/180)*phi)`` where `phase` is the integral\n (from 0 to `t`) of ``2*pi*f(t)``. ``f(t)`` is defined below.\n\n See Also\n --------\n sweep_poly\n\n Notes\n -----\n There are four options for the `method`. The following formulas give\n the instantaneous frequency (in Hz) of the signal generated by\n `chirp()`. For convenience, the shorter names shown below may also be\n used.\n\n linear, lin, li:\n\n ``f(t) = f0 + (f1 - f0) * t / t1``\n\n quadratic, quad, q:\n\n The graph of the frequency f(t) is a parabola through (0, f0) and\n (t1, f1). By default, the vertex of the parabola is at (0, f0).\n If `vertex_zero` is False, then the vertex is at (t1, f1). The\n formula is:\n\n if vertex_zero is True:\n\n ``f(t) = f0 + (f1 - f0) * t**2 / t1**2``\n\n else:\n\n ``f(t) = f1 - (f1 - f0) * (t1 - t)**2 / t1**2``\n\n To use a more general quadratic function, or an arbitrary\n polynomial, use the function `scipy.signal.sweep_poly`.\n\n logarithmic, log, lo:\n\n ``f(t) = f0 * (f1/f0)**(t/t1)``\n\n f0 and f1 must be nonzero and have the same sign.\n\n This signal is also known as a geometric or exponential chirp.\n\n hyperbolic, hyp:\n\n ``f(t) = f0*f1*t1 / ((f0 - f1)*t + f1*t1)``\n\n f0 and f1 must be nonzero.\n\n Examples\n --------\n The following will be used in the examples:\n\n >>> from scipy.signal import chirp, spectrogram\n >>> import matplotlib.pyplot as plt\n\n For the first example, we\'ll plot the waveform for a linear chirp\n from 6 Hz to 1 Hz over 10 seconds:\n\n >>> t = np.linspace(0, 10, 5001)\n >>> w = chirp(t, f0=6, f1=1, t1=10, method=\'linear\')\n >>> plt.plot(t, w)\n >>> plt.title("Linear Chirp, f(0)=6, f(10)=1")\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.show()\n\n For the remaining examples, we\'ll use higher frequency ranges,\n and demonstrate the result using `scipy.signal.spectrogram`.\n We\'ll use a 10 second interval sampled at 8000 Hz.\n\n >>> fs = 8000\n >>> T = 10\n >>> t = np.linspace(0, T, T*fs, endpoint=False)\n\n Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds\n (vertex of the parabolic curve of the frequency is at t=0):\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'quadratic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Quadratic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds\n (vertex of the parabolic curve of the frequency is at t=10):\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'quadratic\',\n ... vertex_zero=False)\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Quadratic Chirp, f(0)=1500, f(10)=250\\n\' +\n ... \'(vertex_zero=False)\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Logarithmic chirp from 1500 Hz to 250 Hz over 10 seconds:\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'logarithmic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Logarithmic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Hyperbolic chirp from 1500 Hz to 250 Hz over 10 seconds:\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'hyperbolic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Hyperbolic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n '
phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero)
phi *= (pi / 180)
return cos((phase + phi))
|
Frequency-swept cosine generator.
In the following, 'Hz' should be interpreted as 'cycles per unit';
there is no requirement here that the unit is one second. The
important distinction is that the units of rotation are cycles, not
radians. Likewise, `t` could be a measurement of space instead of time.
Parameters
----------
t : array_like
Times at which to evaluate the waveform.
f0 : float
Frequency (e.g. Hz) at time t=0.
t1 : float
Time at which `f1` is specified.
f1 : float
Frequency (e.g. Hz) of the waveform at time `t1`.
method : {'linear', 'quadratic', 'logarithmic', 'hyperbolic'}, optional
Kind of frequency sweep. If not given, `linear` is assumed. See
Notes below for more details.
phi : float, optional
Phase offset, in degrees. Default is 0.
vertex_zero : bool, optional
This parameter is only used when `method` is 'quadratic'.
It determines whether the vertex of the parabola that is the graph
of the frequency is at t=0 or t=t1.
Returns
-------
y : ndarray
A numpy array containing the signal evaluated at `t` with the
requested time-varying frequency. More precisely, the function
returns ``cos(phase + (pi/180)*phi)`` where `phase` is the integral
(from 0 to `t`) of ``2*pi*f(t)``. ``f(t)`` is defined below.
See Also
--------
sweep_poly
Notes
-----
There are four options for the `method`. The following formulas give
the instantaneous frequency (in Hz) of the signal generated by
`chirp()`. For convenience, the shorter names shown below may also be
used.
linear, lin, li:
``f(t) = f0 + (f1 - f0) * t / t1``
quadratic, quad, q:
The graph of the frequency f(t) is a parabola through (0, f0) and
(t1, f1). By default, the vertex of the parabola is at (0, f0).
If `vertex_zero` is False, then the vertex is at (t1, f1). The
formula is:
if vertex_zero is True:
``f(t) = f0 + (f1 - f0) * t**2 / t1**2``
else:
``f(t) = f1 - (f1 - f0) * (t1 - t)**2 / t1**2``
To use a more general quadratic function, or an arbitrary
polynomial, use the function `scipy.signal.sweep_poly`.
logarithmic, log, lo:
``f(t) = f0 * (f1/f0)**(t/t1)``
f0 and f1 must be nonzero and have the same sign.
This signal is also known as a geometric or exponential chirp.
hyperbolic, hyp:
``f(t) = f0*f1*t1 / ((f0 - f1)*t + f1*t1)``
f0 and f1 must be nonzero.
Examples
--------
The following will be used in the examples:
>>> from scipy.signal import chirp, spectrogram
>>> import matplotlib.pyplot as plt
For the first example, we'll plot the waveform for a linear chirp
from 6 Hz to 1 Hz over 10 seconds:
>>> t = np.linspace(0, 10, 5001)
>>> w = chirp(t, f0=6, f1=1, t1=10, method='linear')
>>> plt.plot(t, w)
>>> plt.title("Linear Chirp, f(0)=6, f(10)=1")
>>> plt.xlabel('t (sec)')
>>> plt.show()
For the remaining examples, we'll use higher frequency ranges,
and demonstrate the result using `scipy.signal.spectrogram`.
We'll use a 10 second interval sampled at 8000 Hz.
>>> fs = 8000
>>> T = 10
>>> t = np.linspace(0, T, T*fs, endpoint=False)
Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds
(vertex of the parabolic curve of the frequency is at t=0):
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='quadratic')
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Quadratic Chirp, f(0)=1500, f(10)=250')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()
Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds
(vertex of the parabolic curve of the frequency is at t=10):
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='quadratic',
... vertex_zero=False)
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Quadratic Chirp, f(0)=1500, f(10)=250\n' +
... '(vertex_zero=False)')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()
Logarithmic chirp from 1500 Hz to 250 Hz over 10 seconds:
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='logarithmic')
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Logarithmic Chirp, f(0)=1500, f(10)=250')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()
Hyperbolic chirp from 1500 Hz to 250 Hz over 10 seconds:
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='hyperbolic')
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Hyperbolic Chirp, f(0)=1500, f(10)=250')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()
|
cusignal/waveforms.py
|
chirp
|
andrewpalumbo/cusignal
| 1
|
python
|
def chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True):
'Frequency-swept cosine generator.\n\n In the following, \'Hz\' should be interpreted as \'cycles per unit\';\n there is no requirement here that the unit is one second. The\n important distinction is that the units of rotation are cycles, not\n radians. Likewise, `t` could be a measurement of space instead of time.\n\n Parameters\n ----------\n t : array_like\n Times at which to evaluate the waveform.\n f0 : float\n Frequency (e.g. Hz) at time t=0.\n t1 : float\n Time at which `f1` is specified.\n f1 : float\n Frequency (e.g. Hz) of the waveform at time `t1`.\n method : {\'linear\', \'quadratic\', \'logarithmic\', \'hyperbolic\'}, optional\n Kind of frequency sweep. If not given, `linear` is assumed. See\n Notes below for more details.\n phi : float, optional\n Phase offset, in degrees. Default is 0.\n vertex_zero : bool, optional\n This parameter is only used when `method` is \'quadratic\'.\n It determines whether the vertex of the parabola that is the graph\n of the frequency is at t=0 or t=t1.\n\n Returns\n -------\n y : ndarray\n A numpy array containing the signal evaluated at `t` with the\n requested time-varying frequency. More precisely, the function\n returns ``cos(phase + (pi/180)*phi)`` where `phase` is the integral\n (from 0 to `t`) of ``2*pi*f(t)``. ``f(t)`` is defined below.\n\n See Also\n --------\n sweep_poly\n\n Notes\n -----\n There are four options for the `method`. The following formulas give\n the instantaneous frequency (in Hz) of the signal generated by\n `chirp()`. For convenience, the shorter names shown below may also be\n used.\n\n linear, lin, li:\n\n ``f(t) = f0 + (f1 - f0) * t / t1``\n\n quadratic, quad, q:\n\n The graph of the frequency f(t) is a parabola through (0, f0) and\n (t1, f1). By default, the vertex of the parabola is at (0, f0).\n If `vertex_zero` is False, then the vertex is at (t1, f1). The\n formula is:\n\n if vertex_zero is True:\n\n ``f(t) = f0 + (f1 - f0) * t**2 / t1**2``\n\n else:\n\n ``f(t) = f1 - (f1 - f0) * (t1 - t)**2 / t1**2``\n\n To use a more general quadratic function, or an arbitrary\n polynomial, use the function `scipy.signal.sweep_poly`.\n\n logarithmic, log, lo:\n\n ``f(t) = f0 * (f1/f0)**(t/t1)``\n\n f0 and f1 must be nonzero and have the same sign.\n\n This signal is also known as a geometric or exponential chirp.\n\n hyperbolic, hyp:\n\n ``f(t) = f0*f1*t1 / ((f0 - f1)*t + f1*t1)``\n\n f0 and f1 must be nonzero.\n\n Examples\n --------\n The following will be used in the examples:\n\n >>> from scipy.signal import chirp, spectrogram\n >>> import matplotlib.pyplot as plt\n\n For the first example, we\'ll plot the waveform for a linear chirp\n from 6 Hz to 1 Hz over 10 seconds:\n\n >>> t = np.linspace(0, 10, 5001)\n >>> w = chirp(t, f0=6, f1=1, t1=10, method=\'linear\')\n >>> plt.plot(t, w)\n >>> plt.title("Linear Chirp, f(0)=6, f(10)=1")\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.show()\n\n For the remaining examples, we\'ll use higher frequency ranges,\n and demonstrate the result using `scipy.signal.spectrogram`.\n We\'ll use a 10 second interval sampled at 8000 Hz.\n\n >>> fs = 8000\n >>> T = 10\n >>> t = np.linspace(0, T, T*fs, endpoint=False)\n\n Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds\n (vertex of the parabolic curve of the frequency is at t=0):\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'quadratic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Quadratic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds\n (vertex of the parabolic curve of the frequency is at t=10):\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'quadratic\',\n ... vertex_zero=False)\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Quadratic Chirp, f(0)=1500, f(10)=250\\n\' +\n ... \'(vertex_zero=False)\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Logarithmic chirp from 1500 Hz to 250 Hz over 10 seconds:\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'logarithmic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Logarithmic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Hyperbolic chirp from 1500 Hz to 250 Hz over 10 seconds:\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'hyperbolic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Hyperbolic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n '
phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero)
phi *= (pi / 180)
return cos((phase + phi))
|
def chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True):
'Frequency-swept cosine generator.\n\n In the following, \'Hz\' should be interpreted as \'cycles per unit\';\n there is no requirement here that the unit is one second. The\n important distinction is that the units of rotation are cycles, not\n radians. Likewise, `t` could be a measurement of space instead of time.\n\n Parameters\n ----------\n t : array_like\n Times at which to evaluate the waveform.\n f0 : float\n Frequency (e.g. Hz) at time t=0.\n t1 : float\n Time at which `f1` is specified.\n f1 : float\n Frequency (e.g. Hz) of the waveform at time `t1`.\n method : {\'linear\', \'quadratic\', \'logarithmic\', \'hyperbolic\'}, optional\n Kind of frequency sweep. If not given, `linear` is assumed. See\n Notes below for more details.\n phi : float, optional\n Phase offset, in degrees. Default is 0.\n vertex_zero : bool, optional\n This parameter is only used when `method` is \'quadratic\'.\n It determines whether the vertex of the parabola that is the graph\n of the frequency is at t=0 or t=t1.\n\n Returns\n -------\n y : ndarray\n A numpy array containing the signal evaluated at `t` with the\n requested time-varying frequency. More precisely, the function\n returns ``cos(phase + (pi/180)*phi)`` where `phase` is the integral\n (from 0 to `t`) of ``2*pi*f(t)``. ``f(t)`` is defined below.\n\n See Also\n --------\n sweep_poly\n\n Notes\n -----\n There are four options for the `method`. The following formulas give\n the instantaneous frequency (in Hz) of the signal generated by\n `chirp()`. For convenience, the shorter names shown below may also be\n used.\n\n linear, lin, li:\n\n ``f(t) = f0 + (f1 - f0) * t / t1``\n\n quadratic, quad, q:\n\n The graph of the frequency f(t) is a parabola through (0, f0) and\n (t1, f1). By default, the vertex of the parabola is at (0, f0).\n If `vertex_zero` is False, then the vertex is at (t1, f1). The\n formula is:\n\n if vertex_zero is True:\n\n ``f(t) = f0 + (f1 - f0) * t**2 / t1**2``\n\n else:\n\n ``f(t) = f1 - (f1 - f0) * (t1 - t)**2 / t1**2``\n\n To use a more general quadratic function, or an arbitrary\n polynomial, use the function `scipy.signal.sweep_poly`.\n\n logarithmic, log, lo:\n\n ``f(t) = f0 * (f1/f0)**(t/t1)``\n\n f0 and f1 must be nonzero and have the same sign.\n\n This signal is also known as a geometric or exponential chirp.\n\n hyperbolic, hyp:\n\n ``f(t) = f0*f1*t1 / ((f0 - f1)*t + f1*t1)``\n\n f0 and f1 must be nonzero.\n\n Examples\n --------\n The following will be used in the examples:\n\n >>> from scipy.signal import chirp, spectrogram\n >>> import matplotlib.pyplot as plt\n\n For the first example, we\'ll plot the waveform for a linear chirp\n from 6 Hz to 1 Hz over 10 seconds:\n\n >>> t = np.linspace(0, 10, 5001)\n >>> w = chirp(t, f0=6, f1=1, t1=10, method=\'linear\')\n >>> plt.plot(t, w)\n >>> plt.title("Linear Chirp, f(0)=6, f(10)=1")\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.show()\n\n For the remaining examples, we\'ll use higher frequency ranges,\n and demonstrate the result using `scipy.signal.spectrogram`.\n We\'ll use a 10 second interval sampled at 8000 Hz.\n\n >>> fs = 8000\n >>> T = 10\n >>> t = np.linspace(0, T, T*fs, endpoint=False)\n\n Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds\n (vertex of the parabolic curve of the frequency is at t=0):\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'quadratic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Quadratic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds\n (vertex of the parabolic curve of the frequency is at t=10):\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'quadratic\',\n ... vertex_zero=False)\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Quadratic Chirp, f(0)=1500, f(10)=250\\n\' +\n ... \'(vertex_zero=False)\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Logarithmic chirp from 1500 Hz to 250 Hz over 10 seconds:\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'logarithmic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Logarithmic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n Hyperbolic chirp from 1500 Hz to 250 Hz over 10 seconds:\n\n >>> w = chirp(t, f0=1500, f1=250, t1=10, method=\'hyperbolic\')\n >>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,\n ... nfft=2048)\n >>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap=\'gray_r\')\n >>> plt.title(\'Hyperbolic Chirp, f(0)=1500, f(10)=250\')\n >>> plt.xlabel(\'t (sec)\')\n >>> plt.ylabel(\'Frequency (Hz)\')\n >>> plt.grid()\n >>> plt.show()\n\n '
phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero)
phi *= (pi / 180)
return cos((phase + phi))<|docstring|>Frequency-swept cosine generator.
In the following, 'Hz' should be interpreted as 'cycles per unit';
there is no requirement here that the unit is one second. The
important distinction is that the units of rotation are cycles, not
radians. Likewise, `t` could be a measurement of space instead of time.
Parameters
----------
t : array_like
Times at which to evaluate the waveform.
f0 : float
Frequency (e.g. Hz) at time t=0.
t1 : float
Time at which `f1` is specified.
f1 : float
Frequency (e.g. Hz) of the waveform at time `t1`.
method : {'linear', 'quadratic', 'logarithmic', 'hyperbolic'}, optional
Kind of frequency sweep. If not given, `linear` is assumed. See
Notes below for more details.
phi : float, optional
Phase offset, in degrees. Default is 0.
vertex_zero : bool, optional
This parameter is only used when `method` is 'quadratic'.
It determines whether the vertex of the parabola that is the graph
of the frequency is at t=0 or t=t1.
Returns
-------
y : ndarray
A numpy array containing the signal evaluated at `t` with the
requested time-varying frequency. More precisely, the function
returns ``cos(phase + (pi/180)*phi)`` where `phase` is the integral
(from 0 to `t`) of ``2*pi*f(t)``. ``f(t)`` is defined below.
See Also
--------
sweep_poly
Notes
-----
There are four options for the `method`. The following formulas give
the instantaneous frequency (in Hz) of the signal generated by
`chirp()`. For convenience, the shorter names shown below may also be
used.
linear, lin, li:
``f(t) = f0 + (f1 - f0) * t / t1``
quadratic, quad, q:
The graph of the frequency f(t) is a parabola through (0, f0) and
(t1, f1). By default, the vertex of the parabola is at (0, f0).
If `vertex_zero` is False, then the vertex is at (t1, f1). The
formula is:
if vertex_zero is True:
``f(t) = f0 + (f1 - f0) * t**2 / t1**2``
else:
``f(t) = f1 - (f1 - f0) * (t1 - t)**2 / t1**2``
To use a more general quadratic function, or an arbitrary
polynomial, use the function `scipy.signal.sweep_poly`.
logarithmic, log, lo:
``f(t) = f0 * (f1/f0)**(t/t1)``
f0 and f1 must be nonzero and have the same sign.
This signal is also known as a geometric or exponential chirp.
hyperbolic, hyp:
``f(t) = f0*f1*t1 / ((f0 - f1)*t + f1*t1)``
f0 and f1 must be nonzero.
Examples
--------
The following will be used in the examples:
>>> from scipy.signal import chirp, spectrogram
>>> import matplotlib.pyplot as plt
For the first example, we'll plot the waveform for a linear chirp
from 6 Hz to 1 Hz over 10 seconds:
>>> t = np.linspace(0, 10, 5001)
>>> w = chirp(t, f0=6, f1=1, t1=10, method='linear')
>>> plt.plot(t, w)
>>> plt.title("Linear Chirp, f(0)=6, f(10)=1")
>>> plt.xlabel('t (sec)')
>>> plt.show()
For the remaining examples, we'll use higher frequency ranges,
and demonstrate the result using `scipy.signal.spectrogram`.
We'll use a 10 second interval sampled at 8000 Hz.
>>> fs = 8000
>>> T = 10
>>> t = np.linspace(0, T, T*fs, endpoint=False)
Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds
(vertex of the parabolic curve of the frequency is at t=0):
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='quadratic')
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Quadratic Chirp, f(0)=1500, f(10)=250')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()
Quadratic chirp from 1500 Hz to 250 Hz over 10 seconds
(vertex of the parabolic curve of the frequency is at t=10):
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='quadratic',
... vertex_zero=False)
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Quadratic Chirp, f(0)=1500, f(10)=250\n' +
... '(vertex_zero=False)')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()
Logarithmic chirp from 1500 Hz to 250 Hz over 10 seconds:
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='logarithmic')
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Logarithmic Chirp, f(0)=1500, f(10)=250')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()
Hyperbolic chirp from 1500 Hz to 250 Hz over 10 seconds:
>>> w = chirp(t, f0=1500, f1=250, t1=10, method='hyperbolic')
>>> ff, tt, Sxx = spectrogram(w, fs=fs, noverlap=256, nperseg=512,
... nfft=2048)
>>> plt.pcolormesh(tt, ff[:513], Sxx[:513], cmap='gray_r')
>>> plt.title('Hyperbolic Chirp, f(0)=1500, f(10)=250')
>>> plt.xlabel('t (sec)')
>>> plt.ylabel('Frequency (Hz)')
>>> plt.grid()
>>> plt.show()<|endoftext|>
|
4304aaaf4422afdabce71e71cad4dbe3be4837a6436ecc03926326887cae4fd1
|
def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True):
'\n Calculate the phase used by `chirp` to generate its output.\n\n See `chirp` for a description of the arguments.\n\n '
t = asarray(t)
f0 = float(f0)
t1 = float(t1)
f1 = float(f1)
if (method in ['linear', 'lin', 'li']):
beta = ((f1 - f0) / t1)
phase = ((2 * pi) * ((f0 * t) + (((0.5 * beta) * t) * t)))
elif (method in ['quadratic', 'quad', 'q']):
beta = ((f1 - f0) / (t1 ** 2))
if vertex_zero:
phase = ((2 * pi) * ((f0 * t) + ((beta * (t ** 3)) / 3)))
else:
phase = ((2 * pi) * ((f1 * t) + ((beta * (((t1 - t) ** 3) - (t1 ** 3))) / 3)))
elif (method in ['logarithmic', 'log', 'lo']):
if ((f0 * f1) <= 0.0):
raise ValueError('For a logarithmic chirp, f0 and f1 must be nonzero and have the same sign.')
if (f0 == f1):
phase = (((2 * pi) * f0) * t)
else:
beta = (t1 / log((f1 / f0)))
phase = ((((2 * pi) * beta) * f0) * (pow((f1 / f0), (t / t1)) - 1.0))
elif (method in ['hyperbolic', 'hyp']):
if ((f0 == 0) or (f1 == 0)):
raise ValueError('For a hyperbolic chirp, f0 and f1 must be nonzero.')
if (f0 == f1):
phase = (((2 * pi) * f0) * t)
else:
sing = (((- f1) * t1) / (f0 - f1))
phase = (((2 * pi) * ((- sing) * f0)) * log(cp.abs((1 - (t / sing)))))
else:
raise ValueError(("method must be 'linear', 'quadratic', 'logarithmic', or 'hyperbolic', but a value of %r was given." % method))
return phase
|
Calculate the phase used by `chirp` to generate its output.
See `chirp` for a description of the arguments.
|
cusignal/waveforms.py
|
_chirp_phase
|
andrewpalumbo/cusignal
| 1
|
python
|
def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True):
'\n Calculate the phase used by `chirp` to generate its output.\n\n See `chirp` for a description of the arguments.\n\n '
t = asarray(t)
f0 = float(f0)
t1 = float(t1)
f1 = float(f1)
if (method in ['linear', 'lin', 'li']):
beta = ((f1 - f0) / t1)
phase = ((2 * pi) * ((f0 * t) + (((0.5 * beta) * t) * t)))
elif (method in ['quadratic', 'quad', 'q']):
beta = ((f1 - f0) / (t1 ** 2))
if vertex_zero:
phase = ((2 * pi) * ((f0 * t) + ((beta * (t ** 3)) / 3)))
else:
phase = ((2 * pi) * ((f1 * t) + ((beta * (((t1 - t) ** 3) - (t1 ** 3))) / 3)))
elif (method in ['logarithmic', 'log', 'lo']):
if ((f0 * f1) <= 0.0):
raise ValueError('For a logarithmic chirp, f0 and f1 must be nonzero and have the same sign.')
if (f0 == f1):
phase = (((2 * pi) * f0) * t)
else:
beta = (t1 / log((f1 / f0)))
phase = ((((2 * pi) * beta) * f0) * (pow((f1 / f0), (t / t1)) - 1.0))
elif (method in ['hyperbolic', 'hyp']):
if ((f0 == 0) or (f1 == 0)):
raise ValueError('For a hyperbolic chirp, f0 and f1 must be nonzero.')
if (f0 == f1):
phase = (((2 * pi) * f0) * t)
else:
sing = (((- f1) * t1) / (f0 - f1))
phase = (((2 * pi) * ((- sing) * f0)) * log(cp.abs((1 - (t / sing)))))
else:
raise ValueError(("method must be 'linear', 'quadratic', 'logarithmic', or 'hyperbolic', but a value of %r was given." % method))
return phase
|
def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True):
'\n Calculate the phase used by `chirp` to generate its output.\n\n See `chirp` for a description of the arguments.\n\n '
t = asarray(t)
f0 = float(f0)
t1 = float(t1)
f1 = float(f1)
if (method in ['linear', 'lin', 'li']):
beta = ((f1 - f0) / t1)
phase = ((2 * pi) * ((f0 * t) + (((0.5 * beta) * t) * t)))
elif (method in ['quadratic', 'quad', 'q']):
beta = ((f1 - f0) / (t1 ** 2))
if vertex_zero:
phase = ((2 * pi) * ((f0 * t) + ((beta * (t ** 3)) / 3)))
else:
phase = ((2 * pi) * ((f1 * t) + ((beta * (((t1 - t) ** 3) - (t1 ** 3))) / 3)))
elif (method in ['logarithmic', 'log', 'lo']):
if ((f0 * f1) <= 0.0):
raise ValueError('For a logarithmic chirp, f0 and f1 must be nonzero and have the same sign.')
if (f0 == f1):
phase = (((2 * pi) * f0) * t)
else:
beta = (t1 / log((f1 / f0)))
phase = ((((2 * pi) * beta) * f0) * (pow((f1 / f0), (t / t1)) - 1.0))
elif (method in ['hyperbolic', 'hyp']):
if ((f0 == 0) or (f1 == 0)):
raise ValueError('For a hyperbolic chirp, f0 and f1 must be nonzero.')
if (f0 == f1):
phase = (((2 * pi) * f0) * t)
else:
sing = (((- f1) * t1) / (f0 - f1))
phase = (((2 * pi) * ((- sing) * f0)) * log(cp.abs((1 - (t / sing)))))
else:
raise ValueError(("method must be 'linear', 'quadratic', 'logarithmic', or 'hyperbolic', but a value of %r was given." % method))
return phase<|docstring|>Calculate the phase used by `chirp` to generate its output.
See `chirp` for a description of the arguments.<|endoftext|>
|
c0ebb1a838ce45be075b60ca58394c5ef3330c3d3c9c18ced1a45737e84a8da3
|
def unit_impulse(shape, idx=None, dtype=float):
"\n Unit impulse signal (discrete delta function) or unit basis vector.\n\n Parameters\n ----------\n shape : int or tuple of int\n Number of samples in the output (1-D), or a tuple that represents the\n shape of the output (N-D).\n idx : None or int or tuple of int or 'mid', optional\n Index at which the value is 1. If None, defaults to the 0th element.\n If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in\n all dimensions. If an int, the impulse will be at `idx` in all\n dimensions.\n dtype : data-type, optional\n The desired data-type for the array, e.g., ``numpy.int8``. Default is\n ``numpy.float64``.\n\n Returns\n -------\n y : ndarray\n Output array containing an impulse signal.\n\n Notes\n -----\n The 1D case is also known as the Kronecker delta.\n\n .. versionadded:: 0.19.0\n\n Examples\n --------\n An impulse at the 0th element (:math:`\\delta[n]`):\n\n >>> from scipy import signal\n >>> signal.unit_impulse(8)\n array([ 1., 0., 0., 0., 0., 0., 0., 0.])\n\n Impulse offset by 2 samples (:math:`\\delta[n-2]`):\n\n >>> signal.unit_impulse(7, 2)\n array([ 0., 0., 1., 0., 0., 0., 0.])\n\n 2-dimensional impulse, centered:\n\n >>> signal.unit_impulse((3, 3), 'mid')\n array([[ 0., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 0.]])\n\n Impulse at (2, 2), using broadcasting:\n\n >>> signal.unit_impulse((4, 4), 2)\n array([[ 0., 0., 0., 0.],\n [ 0., 0., 0., 0.],\n [ 0., 0., 1., 0.],\n [ 0., 0., 0., 0.]])\n\n Plot the impulse response of a 4th-order Butterworth lowpass filter:\n\n >>> imp = signal.unit_impulse(100, 'mid')\n >>> b, a = signal.butter(4, 0.2)\n >>> response = signal.lfilter(b, a, imp)\n\n >>> import matplotlib.pyplot as plt\n >>> plt.plot(np.arange(-50, 50), imp)\n >>> plt.plot(np.arange(-50, 50), response)\n >>> plt.margins(0.1, 0.1)\n >>> plt.xlabel('Time [samples]')\n >>> plt.ylabel('Amplitude')\n >>> plt.grid(True)\n >>> plt.show()\n\n "
out = zeros(shape, dtype)
shape = cp.atleast_1d(shape)
if (idx is None):
idx = ((0,) * len(shape))
elif (idx == 'mid'):
idx = tuple((shape // 2))
elif (not hasattr(idx, '__iter__')):
idx = ((idx,) * len(shape))
out[idx] = 1
return out
|
Unit impulse signal (discrete delta function) or unit basis vector.
Parameters
----------
shape : int or tuple of int
Number of samples in the output (1-D), or a tuple that represents the
shape of the output (N-D).
idx : None or int or tuple of int or 'mid', optional
Index at which the value is 1. If None, defaults to the 0th element.
If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in
all dimensions. If an int, the impulse will be at `idx` in all
dimensions.
dtype : data-type, optional
The desired data-type for the array, e.g., ``numpy.int8``. Default is
``numpy.float64``.
Returns
-------
y : ndarray
Output array containing an impulse signal.
Notes
-----
The 1D case is also known as the Kronecker delta.
.. versionadded:: 0.19.0
Examples
--------
An impulse at the 0th element (:math:`\delta[n]`):
>>> from scipy import signal
>>> signal.unit_impulse(8)
array([ 1., 0., 0., 0., 0., 0., 0., 0.])
Impulse offset by 2 samples (:math:`\delta[n-2]`):
>>> signal.unit_impulse(7, 2)
array([ 0., 0., 1., 0., 0., 0., 0.])
2-dimensional impulse, centered:
>>> signal.unit_impulse((3, 3), 'mid')
array([[ 0., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 0.]])
Impulse at (2, 2), using broadcasting:
>>> signal.unit_impulse((4, 4), 2)
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 0.]])
Plot the impulse response of a 4th-order Butterworth lowpass filter:
>>> imp = signal.unit_impulse(100, 'mid')
>>> b, a = signal.butter(4, 0.2)
>>> response = signal.lfilter(b, a, imp)
>>> import matplotlib.pyplot as plt
>>> plt.plot(np.arange(-50, 50), imp)
>>> plt.plot(np.arange(-50, 50), response)
>>> plt.margins(0.1, 0.1)
>>> plt.xlabel('Time [samples]')
>>> plt.ylabel('Amplitude')
>>> plt.grid(True)
>>> plt.show()
|
cusignal/waveforms.py
|
unit_impulse
|
andrewpalumbo/cusignal
| 1
|
python
|
def unit_impulse(shape, idx=None, dtype=float):
"\n Unit impulse signal (discrete delta function) or unit basis vector.\n\n Parameters\n ----------\n shape : int or tuple of int\n Number of samples in the output (1-D), or a tuple that represents the\n shape of the output (N-D).\n idx : None or int or tuple of int or 'mid', optional\n Index at which the value is 1. If None, defaults to the 0th element.\n If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in\n all dimensions. If an int, the impulse will be at `idx` in all\n dimensions.\n dtype : data-type, optional\n The desired data-type for the array, e.g., ``numpy.int8``. Default is\n ``numpy.float64``.\n\n Returns\n -------\n y : ndarray\n Output array containing an impulse signal.\n\n Notes\n -----\n The 1D case is also known as the Kronecker delta.\n\n .. versionadded:: 0.19.0\n\n Examples\n --------\n An impulse at the 0th element (:math:`\\delta[n]`):\n\n >>> from scipy import signal\n >>> signal.unit_impulse(8)\n array([ 1., 0., 0., 0., 0., 0., 0., 0.])\n\n Impulse offset by 2 samples (:math:`\\delta[n-2]`):\n\n >>> signal.unit_impulse(7, 2)\n array([ 0., 0., 1., 0., 0., 0., 0.])\n\n 2-dimensional impulse, centered:\n\n >>> signal.unit_impulse((3, 3), 'mid')\n array([[ 0., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 0.]])\n\n Impulse at (2, 2), using broadcasting:\n\n >>> signal.unit_impulse((4, 4), 2)\n array([[ 0., 0., 0., 0.],\n [ 0., 0., 0., 0.],\n [ 0., 0., 1., 0.],\n [ 0., 0., 0., 0.]])\n\n Plot the impulse response of a 4th-order Butterworth lowpass filter:\n\n >>> imp = signal.unit_impulse(100, 'mid')\n >>> b, a = signal.butter(4, 0.2)\n >>> response = signal.lfilter(b, a, imp)\n\n >>> import matplotlib.pyplot as plt\n >>> plt.plot(np.arange(-50, 50), imp)\n >>> plt.plot(np.arange(-50, 50), response)\n >>> plt.margins(0.1, 0.1)\n >>> plt.xlabel('Time [samples]')\n >>> plt.ylabel('Amplitude')\n >>> plt.grid(True)\n >>> plt.show()\n\n "
out = zeros(shape, dtype)
shape = cp.atleast_1d(shape)
if (idx is None):
idx = ((0,) * len(shape))
elif (idx == 'mid'):
idx = tuple((shape // 2))
elif (not hasattr(idx, '__iter__')):
idx = ((idx,) * len(shape))
out[idx] = 1
return out
|
def unit_impulse(shape, idx=None, dtype=float):
"\n Unit impulse signal (discrete delta function) or unit basis vector.\n\n Parameters\n ----------\n shape : int or tuple of int\n Number of samples in the output (1-D), or a tuple that represents the\n shape of the output (N-D).\n idx : None or int or tuple of int or 'mid', optional\n Index at which the value is 1. If None, defaults to the 0th element.\n If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in\n all dimensions. If an int, the impulse will be at `idx` in all\n dimensions.\n dtype : data-type, optional\n The desired data-type for the array, e.g., ``numpy.int8``. Default is\n ``numpy.float64``.\n\n Returns\n -------\n y : ndarray\n Output array containing an impulse signal.\n\n Notes\n -----\n The 1D case is also known as the Kronecker delta.\n\n .. versionadded:: 0.19.0\n\n Examples\n --------\n An impulse at the 0th element (:math:`\\delta[n]`):\n\n >>> from scipy import signal\n >>> signal.unit_impulse(8)\n array([ 1., 0., 0., 0., 0., 0., 0., 0.])\n\n Impulse offset by 2 samples (:math:`\\delta[n-2]`):\n\n >>> signal.unit_impulse(7, 2)\n array([ 0., 0., 1., 0., 0., 0., 0.])\n\n 2-dimensional impulse, centered:\n\n >>> signal.unit_impulse((3, 3), 'mid')\n array([[ 0., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 0.]])\n\n Impulse at (2, 2), using broadcasting:\n\n >>> signal.unit_impulse((4, 4), 2)\n array([[ 0., 0., 0., 0.],\n [ 0., 0., 0., 0.],\n [ 0., 0., 1., 0.],\n [ 0., 0., 0., 0.]])\n\n Plot the impulse response of a 4th-order Butterworth lowpass filter:\n\n >>> imp = signal.unit_impulse(100, 'mid')\n >>> b, a = signal.butter(4, 0.2)\n >>> response = signal.lfilter(b, a, imp)\n\n >>> import matplotlib.pyplot as plt\n >>> plt.plot(np.arange(-50, 50), imp)\n >>> plt.plot(np.arange(-50, 50), response)\n >>> plt.margins(0.1, 0.1)\n >>> plt.xlabel('Time [samples]')\n >>> plt.ylabel('Amplitude')\n >>> plt.grid(True)\n >>> plt.show()\n\n "
out = zeros(shape, dtype)
shape = cp.atleast_1d(shape)
if (idx is None):
idx = ((0,) * len(shape))
elif (idx == 'mid'):
idx = tuple((shape // 2))
elif (not hasattr(idx, '__iter__')):
idx = ((idx,) * len(shape))
out[idx] = 1
return out<|docstring|>Unit impulse signal (discrete delta function) or unit basis vector.
Parameters
----------
shape : int or tuple of int
Number of samples in the output (1-D), or a tuple that represents the
shape of the output (N-D).
idx : None or int or tuple of int or 'mid', optional
Index at which the value is 1. If None, defaults to the 0th element.
If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in
all dimensions. If an int, the impulse will be at `idx` in all
dimensions.
dtype : data-type, optional
The desired data-type for the array, e.g., ``numpy.int8``. Default is
``numpy.float64``.
Returns
-------
y : ndarray
Output array containing an impulse signal.
Notes
-----
The 1D case is also known as the Kronecker delta.
.. versionadded:: 0.19.0
Examples
--------
An impulse at the 0th element (:math:`\delta[n]`):
>>> from scipy import signal
>>> signal.unit_impulse(8)
array([ 1., 0., 0., 0., 0., 0., 0., 0.])
Impulse offset by 2 samples (:math:`\delta[n-2]`):
>>> signal.unit_impulse(7, 2)
array([ 0., 0., 1., 0., 0., 0., 0.])
2-dimensional impulse, centered:
>>> signal.unit_impulse((3, 3), 'mid')
array([[ 0., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 0.]])
Impulse at (2, 2), using broadcasting:
>>> signal.unit_impulse((4, 4), 2)
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 0.]])
Plot the impulse response of a 4th-order Butterworth lowpass filter:
>>> imp = signal.unit_impulse(100, 'mid')
>>> b, a = signal.butter(4, 0.2)
>>> response = signal.lfilter(b, a, imp)
>>> import matplotlib.pyplot as plt
>>> plt.plot(np.arange(-50, 50), imp)
>>> plt.plot(np.arange(-50, 50), response)
>>> plt.margins(0.1, 0.1)
>>> plt.xlabel('Time [samples]')
>>> plt.ylabel('Amplitude')
>>> plt.grid(True)
>>> plt.show()<|endoftext|>
|
b6d83f67f2ef05662b657c6b094d5552eb35d411362d7d6502c5ad844450173e
|
@staticmethod
def load_asset(name: str) -> str:
'\n Returns the asset path of the asset.\n\n :param str name: The asset.\n :return: The asset path.\n :rtype: str\n '
return os.path.join(os.path.dirname(__file__), 'assets', name)
|
Returns the asset path of the asset.
:param str name: The asset.
:return: The asset path.
:rtype: str
|
discordSuperUtils/imaging.py
|
load_asset
|
Zetriccc/Amina
| 91
|
python
|
@staticmethod
def load_asset(name: str) -> str:
'\n Returns the asset path of the asset.\n\n :param str name: The asset.\n :return: The asset path.\n :rtype: str\n '
return os.path.join(os.path.dirname(__file__), 'assets', name)
|
@staticmethod
def load_asset(name: str) -> str:
'\n Returns the asset path of the asset.\n\n :param str name: The asset.\n :return: The asset path.\n :rtype: str\n '
return os.path.join(os.path.dirname(__file__), 'assets', name)<|docstring|>Returns the asset path of the asset.
:param str name: The asset.
:return: The asset path.
:rtype: str<|endoftext|>
|
2a34783dbfae26f990e78b05eccae4d29c44c908fdc00b083dd7706e8e6308d5
|
@staticmethod
async def make_request(url: str) -> Optional[bytes]:
'\n Returns the bytes of the URL response, if applicable.\n\n :param str url: The url.\n :return: The response bytes.\n :rtype: Optional[bytes]\n '
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return (await response.read())
|
Returns the bytes of the URL response, if applicable.
:param str url: The url.
:return: The response bytes.
:rtype: Optional[bytes]
|
discordSuperUtils/imaging.py
|
make_request
|
Zetriccc/Amina
| 91
|
python
|
@staticmethod
async def make_request(url: str) -> Optional[bytes]:
'\n Returns the bytes of the URL response, if applicable.\n\n :param str url: The url.\n :return: The response bytes.\n :rtype: Optional[bytes]\n '
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return (await response.read())
|
@staticmethod
async def make_request(url: str) -> Optional[bytes]:
'\n Returns the bytes of the URL response, if applicable.\n\n :param str url: The url.\n :return: The response bytes.\n :rtype: Optional[bytes]\n '
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return (await response.read())<|docstring|>Returns the bytes of the URL response, if applicable.
:param str url: The url.
:return: The response bytes.
:rtype: Optional[bytes]<|endoftext|>
|
da6e863d9cb210edaf3bdef08e1b61844e7df7ab277f4583573bb179a803628c
|
@classmethod
async def convert_image(cls, url: str) -> Image.Image:
'\n Converts the image to a PIL image.\n\n :param str url: The URL.\n :return: The converted image.\n :rtype: Image.Image\n '
return PIL.Image.open(BytesIO((await cls.make_request(url)))).convert('RGBA')
|
Converts the image to a PIL image.
:param str url: The URL.
:return: The converted image.
:rtype: Image.Image
|
discordSuperUtils/imaging.py
|
convert_image
|
Zetriccc/Amina
| 91
|
python
|
@classmethod
async def convert_image(cls, url: str) -> Image.Image:
'\n Converts the image to a PIL image.\n\n :param str url: The URL.\n :return: The converted image.\n :rtype: Image.Image\n '
return PIL.Image.open(BytesIO((await cls.make_request(url)))).convert('RGBA')
|
@classmethod
async def convert_image(cls, url: str) -> Image.Image:
'\n Converts the image to a PIL image.\n\n :param str url: The URL.\n :return: The converted image.\n :rtype: Image.Image\n '
return PIL.Image.open(BytesIO((await cls.make_request(url)))).convert('RGBA')<|docstring|>Converts the image to a PIL image.
:param str url: The URL.
:return: The converted image.
:rtype: Image.Image<|endoftext|>
|
c00f73b0e8e3b6381ab55fd069d277e9833508eaeeea5ea891166cbb3016c1d7
|
@staticmethod
def human_format(num: int) -> str:
'\n Converts the number to a human readable format.\n\n :param int num: The number.\n :return: The human readable format.\n :rtype: str\n '
original_num = num
num = float('{:.3g}'.format(num))
magnitude = 0
matches = ['', 'K', 'M', 'B', 'T', 'Qua', 'Qui']
while (abs(num) >= 1000):
if (magnitude >= 5):
break
magnitude += 1
num /= 1000.0
try:
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), matches[magnitude])
except IndexError:
return str(original_num)
|
Converts the number to a human readable format.
:param int num: The number.
:return: The human readable format.
:rtype: str
|
discordSuperUtils/imaging.py
|
human_format
|
Zetriccc/Amina
| 91
|
python
|
@staticmethod
def human_format(num: int) -> str:
'\n Converts the number to a human readable format.\n\n :param int num: The number.\n :return: The human readable format.\n :rtype: str\n '
original_num = num
num = float('{:.3g}'.format(num))
magnitude = 0
matches = [, 'K', 'M', 'B', 'T', 'Qua', 'Qui']
while (abs(num) >= 1000):
if (magnitude >= 5):
break
magnitude += 1
num /= 1000.0
try:
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), matches[magnitude])
except IndexError:
return str(original_num)
|
@staticmethod
def human_format(num: int) -> str:
'\n Converts the number to a human readable format.\n\n :param int num: The number.\n :return: The human readable format.\n :rtype: str\n '
original_num = num
num = float('{:.3g}'.format(num))
magnitude = 0
matches = [, 'K', 'M', 'B', 'T', 'Qua', 'Qui']
while (abs(num) >= 1000):
if (magnitude >= 5):
break
magnitude += 1
num /= 1000.0
try:
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), matches[magnitude])
except IndexError:
return str(original_num)<|docstring|>Converts the number to a human readable format.
:param int num: The number.
:return: The human readable format.
:rtype: str<|endoftext|>
|
155a0c53b131ab4e30e3401e24ceb735ff048ce55baef5d2de5872b0aa95362a
|
@staticmethod
def multiline_text(card: Image.Image, text: str, font: FreeTypeFont, text_color: Tuple[(int, int, int)], start_height: Union[(int, float)], width: int) -> None:
'\n Draws multiline text on the card.\n\n :param Image.Image card: The card to draw on.\n :param str text: The text to write.\n :param FreeTypeFont font: The font.\n :param Tuple[int, int, int] text_color: The text color.\n :param Union[int, float] start_height:\n The start height of the text, the text will start there, and make its way downwards.\n :param int width: The width of the wrap.\n :return: None\n :rtype: None\n '
draw = ImageDraw.Draw(card)
(image_width, image_height) = card.size
y_text = start_height
lines = textwrap.wrap(text, width=width)
for line in lines:
(line_width, line_height) = font.getsize(line)
draw.text((((image_width - line_width) / 2), y_text), line, font=font, fill=text_color)
y_text += line_height
|
Draws multiline text on the card.
:param Image.Image card: The card to draw on.
:param str text: The text to write.
:param FreeTypeFont font: The font.
:param Tuple[int, int, int] text_color: The text color.
:param Union[int, float] start_height:
The start height of the text, the text will start there, and make its way downwards.
:param int width: The width of the wrap.
:return: None
:rtype: None
|
discordSuperUtils/imaging.py
|
multiline_text
|
Zetriccc/Amina
| 91
|
python
|
@staticmethod
def multiline_text(card: Image.Image, text: str, font: FreeTypeFont, text_color: Tuple[(int, int, int)], start_height: Union[(int, float)], width: int) -> None:
'\n Draws multiline text on the card.\n\n :param Image.Image card: The card to draw on.\n :param str text: The text to write.\n :param FreeTypeFont font: The font.\n :param Tuple[int, int, int] text_color: The text color.\n :param Union[int, float] start_height:\n The start height of the text, the text will start there, and make its way downwards.\n :param int width: The width of the wrap.\n :return: None\n :rtype: None\n '
draw = ImageDraw.Draw(card)
(image_width, image_height) = card.size
y_text = start_height
lines = textwrap.wrap(text, width=width)
for line in lines:
(line_width, line_height) = font.getsize(line)
draw.text((((image_width - line_width) / 2), y_text), line, font=font, fill=text_color)
y_text += line_height
|
@staticmethod
def multiline_text(card: Image.Image, text: str, font: FreeTypeFont, text_color: Tuple[(int, int, int)], start_height: Union[(int, float)], width: int) -> None:
'\n Draws multiline text on the card.\n\n :param Image.Image card: The card to draw on.\n :param str text: The text to write.\n :param FreeTypeFont font: The font.\n :param Tuple[int, int, int] text_color: The text color.\n :param Union[int, float] start_height:\n The start height of the text, the text will start there, and make its way downwards.\n :param int width: The width of the wrap.\n :return: None\n :rtype: None\n '
draw = ImageDraw.Draw(card)
(image_width, image_height) = card.size
y_text = start_height
lines = textwrap.wrap(text, width=width)
for line in lines:
(line_width, line_height) = font.getsize(line)
draw.text((((image_width - line_width) / 2), y_text), line, font=font, fill=text_color)
y_text += line_height<|docstring|>Draws multiline text on the card.
:param Image.Image card: The card to draw on.
:param str text: The text to write.
:param FreeTypeFont font: The font.
:param Tuple[int, int, int] text_color: The text color.
:param Union[int, float] start_height:
The start height of the text, the text will start there, and make its way downwards.
:param int width: The width of the wrap.
:return: None
:rtype: None<|endoftext|>
|
80bb1173ef86b8f9f37d1d9353df15124732682c11c0f0e3e5774fa056fcd677
|
async def draw_profile_picture(self, card: Image.Image, member: discord.Member, location: Tuple[(int, int)], size: int=180, outline_thickness: int=5, status: bool=True, outline_color: Tuple[(int, int, int)]=(255, 255, 255)) -> Image.Image:
"\n |coro|\n\n Pastes the profile picture on the card.\n\n :param Image.Image card: The card.\n :param discord.Member member: The member to get the profile picture from.\n :param Tuple[int, int] location: The center of the picture.\n :param int size: The size of the pasted profile picture.\n :param int outline_thickness: The outline thickness.\n :param bool status: A bool indicating if it should paste the member's status icon.\n :param Tuple[int, int, int] outline_color: The outline color.\n :return: The result image.\n :rtype: Image.Image\n "
blank = Image.new('RGBA', card.size, (255, 255, 255, 0))
location = tuple(((round((x - (size / 2))) if (i <= 1) else round((x + (size / 2)))) for (i, x) in enumerate((location + location))))
outline_dimensions = tuple((((x - outline_thickness) if (i <= 1) else (x + outline_thickness)) for (i, x) in enumerate(location)))
size_dimensions = (size, size)
status_dimensions = tuple((round((x / 4)) for x in size_dimensions))
mask = Image.new('RGBA', card.size, 0)
ImageDraw.Draw(mask).ellipse(location, fill=(255, 25, 255, 255))
avatar = (await self.convert_image(str(member.avatar_url))).resize(size_dimensions)
profile_pic_holder = Image.new('RGBA', card.size, (255, 255, 255, 255))
ImageDraw.Draw(card).ellipse(outline_dimensions, fill=outline_color)
profile_pic_holder.paste(avatar, location)
pre_card = Image.composite(profile_pic_holder, card, mask)
pre_card = pre_card.convert('RGBA')
if status:
status_picture = Image.open(self.load_asset(f'{member.status.name}.png'))
status_picture = status_picture.convert('RGBA').resize(status_dimensions)
blank.paste(status_picture, tuple(((x - status_dimensions[0]) for x in location[2:])))
return Image.alpha_composite(pre_card, blank)
|
|coro|
Pastes the profile picture on the card.
:param Image.Image card: The card.
:param discord.Member member: The member to get the profile picture from.
:param Tuple[int, int] location: The center of the picture.
:param int size: The size of the pasted profile picture.
:param int outline_thickness: The outline thickness.
:param bool status: A bool indicating if it should paste the member's status icon.
:param Tuple[int, int, int] outline_color: The outline color.
:return: The result image.
:rtype: Image.Image
|
discordSuperUtils/imaging.py
|
draw_profile_picture
|
Zetriccc/Amina
| 91
|
python
|
async def draw_profile_picture(self, card: Image.Image, member: discord.Member, location: Tuple[(int, int)], size: int=180, outline_thickness: int=5, status: bool=True, outline_color: Tuple[(int, int, int)]=(255, 255, 255)) -> Image.Image:
"\n |coro|\n\n Pastes the profile picture on the card.\n\n :param Image.Image card: The card.\n :param discord.Member member: The member to get the profile picture from.\n :param Tuple[int, int] location: The center of the picture.\n :param int size: The size of the pasted profile picture.\n :param int outline_thickness: The outline thickness.\n :param bool status: A bool indicating if it should paste the member's status icon.\n :param Tuple[int, int, int] outline_color: The outline color.\n :return: The result image.\n :rtype: Image.Image\n "
blank = Image.new('RGBA', card.size, (255, 255, 255, 0))
location = tuple(((round((x - (size / 2))) if (i <= 1) else round((x + (size / 2)))) for (i, x) in enumerate((location + location))))
outline_dimensions = tuple((((x - outline_thickness) if (i <= 1) else (x + outline_thickness)) for (i, x) in enumerate(location)))
size_dimensions = (size, size)
status_dimensions = tuple((round((x / 4)) for x in size_dimensions))
mask = Image.new('RGBA', card.size, 0)
ImageDraw.Draw(mask).ellipse(location, fill=(255, 25, 255, 255))
avatar = (await self.convert_image(str(member.avatar_url))).resize(size_dimensions)
profile_pic_holder = Image.new('RGBA', card.size, (255, 255, 255, 255))
ImageDraw.Draw(card).ellipse(outline_dimensions, fill=outline_color)
profile_pic_holder.paste(avatar, location)
pre_card = Image.composite(profile_pic_holder, card, mask)
pre_card = pre_card.convert('RGBA')
if status:
status_picture = Image.open(self.load_asset(f'{member.status.name}.png'))
status_picture = status_picture.convert('RGBA').resize(status_dimensions)
blank.paste(status_picture, tuple(((x - status_dimensions[0]) for x in location[2:])))
return Image.alpha_composite(pre_card, blank)
|
async def draw_profile_picture(self, card: Image.Image, member: discord.Member, location: Tuple[(int, int)], size: int=180, outline_thickness: int=5, status: bool=True, outline_color: Tuple[(int, int, int)]=(255, 255, 255)) -> Image.Image:
"\n |coro|\n\n Pastes the profile picture on the card.\n\n :param Image.Image card: The card.\n :param discord.Member member: The member to get the profile picture from.\n :param Tuple[int, int] location: The center of the picture.\n :param int size: The size of the pasted profile picture.\n :param int outline_thickness: The outline thickness.\n :param bool status: A bool indicating if it should paste the member's status icon.\n :param Tuple[int, int, int] outline_color: The outline color.\n :return: The result image.\n :rtype: Image.Image\n "
blank = Image.new('RGBA', card.size, (255, 255, 255, 0))
location = tuple(((round((x - (size / 2))) if (i <= 1) else round((x + (size / 2)))) for (i, x) in enumerate((location + location))))
outline_dimensions = tuple((((x - outline_thickness) if (i <= 1) else (x + outline_thickness)) for (i, x) in enumerate(location)))
size_dimensions = (size, size)
status_dimensions = tuple((round((x / 4)) for x in size_dimensions))
mask = Image.new('RGBA', card.size, 0)
ImageDraw.Draw(mask).ellipse(location, fill=(255, 25, 255, 255))
avatar = (await self.convert_image(str(member.avatar_url))).resize(size_dimensions)
profile_pic_holder = Image.new('RGBA', card.size, (255, 255, 255, 255))
ImageDraw.Draw(card).ellipse(outline_dimensions, fill=outline_color)
profile_pic_holder.paste(avatar, location)
pre_card = Image.composite(profile_pic_holder, card, mask)
pre_card = pre_card.convert('RGBA')
if status:
status_picture = Image.open(self.load_asset(f'{member.status.name}.png'))
status_picture = status_picture.convert('RGBA').resize(status_dimensions)
blank.paste(status_picture, tuple(((x - status_dimensions[0]) for x in location[2:])))
return Image.alpha_composite(pre_card, blank)<|docstring|>|coro|
Pastes the profile picture on the card.
:param Image.Image card: The card.
:param discord.Member member: The member to get the profile picture from.
:param Tuple[int, int] location: The center of the picture.
:param int size: The size of the pasted profile picture.
:param int outline_thickness: The outline thickness.
:param bool status: A bool indicating if it should paste the member's status icon.
:param Tuple[int, int, int] outline_color: The outline color.
:return: The result image.
:rtype: Image.Image<|endoftext|>
|
389e498ec488bec048c05360d216fd28f0c6d173abcd9fb330d430c8d3b4ce27
|
async def create_welcome_card(self, member: discord.Member, background: Union[(Backgrounds, str)], title: str, description: str, title_color: Tuple[(int, int, int)]=(255, 255, 255), description_color: Tuple[(int, int, int)]=(255, 255, 255), font_path: str=None, outline: int=5, transparency: int=0) -> discord.File:
'\n |coro|\n\n Creates a welcome image for the member and returns it as a discord.File.\n\n :param discord.Member member: The joined member.\n :param Union[Backgrounds, str] background: The background of the image, can be a Backgrounds enum or a URL.\n :param str title: The title.\n :param str description: The description.\n :param Tuple[int, int, int] title_color: The color of the title.\n :param Tuple[int, int, int] description_color: The color of the description.\n :param str font_path: The font path, uses the default font if not passed.\n :param int outline: The outline thickness.\n :param int transparency: The transparency of the background made.\n :return: The discord file.\n :rtype: discord.File\n '
result_bytes = BytesIO()
card = (Image.open(background.value) if isinstance(background, Backgrounds) else (await self.convert_image(background)))
card = card.resize((1024, 500))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
big_font = ImageFont.truetype(font_path, 36)
small_font = ImageFont.truetype(font_path, 30)
draw = ImageDraw.Draw(card, 'RGBA')
if (transparency and isinstance(background, Backgrounds)):
draw.rectangle((30, 30, 994, 470), fill=(0, 0, 0, transparency))
draw.text((512, 360), title, title_color, font=big_font, anchor='ms')
self.multiline_text(card, description, small_font, description_color, 380, 60)
final_card = (await self.draw_profile_picture(card, member, (512, 180), 260, outline_thickness=outline))
final_card.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='welcome_card.png')
|
|coro|
Creates a welcome image for the member and returns it as a discord.File.
:param discord.Member member: The joined member.
:param Union[Backgrounds, str] background: The background of the image, can be a Backgrounds enum or a URL.
:param str title: The title.
:param str description: The description.
:param Tuple[int, int, int] title_color: The color of the title.
:param Tuple[int, int, int] description_color: The color of the description.
:param str font_path: The font path, uses the default font if not passed.
:param int outline: The outline thickness.
:param int transparency: The transparency of the background made.
:return: The discord file.
:rtype: discord.File
|
discordSuperUtils/imaging.py
|
create_welcome_card
|
Zetriccc/Amina
| 91
|
python
|
async def create_welcome_card(self, member: discord.Member, background: Union[(Backgrounds, str)], title: str, description: str, title_color: Tuple[(int, int, int)]=(255, 255, 255), description_color: Tuple[(int, int, int)]=(255, 255, 255), font_path: str=None, outline: int=5, transparency: int=0) -> discord.File:
'\n |coro|\n\n Creates a welcome image for the member and returns it as a discord.File.\n\n :param discord.Member member: The joined member.\n :param Union[Backgrounds, str] background: The background of the image, can be a Backgrounds enum or a URL.\n :param str title: The title.\n :param str description: The description.\n :param Tuple[int, int, int] title_color: The color of the title.\n :param Tuple[int, int, int] description_color: The color of the description.\n :param str font_path: The font path, uses the default font if not passed.\n :param int outline: The outline thickness.\n :param int transparency: The transparency of the background made.\n :return: The discord file.\n :rtype: discord.File\n '
result_bytes = BytesIO()
card = (Image.open(background.value) if isinstance(background, Backgrounds) else (await self.convert_image(background)))
card = card.resize((1024, 500))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
big_font = ImageFont.truetype(font_path, 36)
small_font = ImageFont.truetype(font_path, 30)
draw = ImageDraw.Draw(card, 'RGBA')
if (transparency and isinstance(background, Backgrounds)):
draw.rectangle((30, 30, 994, 470), fill=(0, 0, 0, transparency))
draw.text((512, 360), title, title_color, font=big_font, anchor='ms')
self.multiline_text(card, description, small_font, description_color, 380, 60)
final_card = (await self.draw_profile_picture(card, member, (512, 180), 260, outline_thickness=outline))
final_card.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='welcome_card.png')
|
async def create_welcome_card(self, member: discord.Member, background: Union[(Backgrounds, str)], title: str, description: str, title_color: Tuple[(int, int, int)]=(255, 255, 255), description_color: Tuple[(int, int, int)]=(255, 255, 255), font_path: str=None, outline: int=5, transparency: int=0) -> discord.File:
'\n |coro|\n\n Creates a welcome image for the member and returns it as a discord.File.\n\n :param discord.Member member: The joined member.\n :param Union[Backgrounds, str] background: The background of the image, can be a Backgrounds enum or a URL.\n :param str title: The title.\n :param str description: The description.\n :param Tuple[int, int, int] title_color: The color of the title.\n :param Tuple[int, int, int] description_color: The color of the description.\n :param str font_path: The font path, uses the default font if not passed.\n :param int outline: The outline thickness.\n :param int transparency: The transparency of the background made.\n :return: The discord file.\n :rtype: discord.File\n '
result_bytes = BytesIO()
card = (Image.open(background.value) if isinstance(background, Backgrounds) else (await self.convert_image(background)))
card = card.resize((1024, 500))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
big_font = ImageFont.truetype(font_path, 36)
small_font = ImageFont.truetype(font_path, 30)
draw = ImageDraw.Draw(card, 'RGBA')
if (transparency and isinstance(background, Backgrounds)):
draw.rectangle((30, 30, 994, 470), fill=(0, 0, 0, transparency))
draw.text((512, 360), title, title_color, font=big_font, anchor='ms')
self.multiline_text(card, description, small_font, description_color, 380, 60)
final_card = (await self.draw_profile_picture(card, member, (512, 180), 260, outline_thickness=outline))
final_card.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='welcome_card.png')<|docstring|>|coro|
Creates a welcome image for the member and returns it as a discord.File.
:param discord.Member member: The joined member.
:param Union[Backgrounds, str] background: The background of the image, can be a Backgrounds enum or a URL.
:param str title: The title.
:param str description: The description.
:param Tuple[int, int, int] title_color: The color of the title.
:param Tuple[int, int, int] description_color: The color of the description.
:param str font_path: The font path, uses the default font if not passed.
:param int outline: The outline thickness.
:param int transparency: The transparency of the background made.
:return: The discord file.
:rtype: discord.File<|endoftext|>
|
062f0128f6d9ebcf84abd1159e08f654ff7287a862d59a927dcd3ff835335021
|
async def create_leveling_profile(self, member: discord.Member, member_account: LevelingAccount, background: Union[(Backgrounds, str)], rank: int, name_color: Tuple[(int, int, int)]=DEFAULT_COLOR, rank_color: Tuple[(int, int, int)]=DEFAULT_COLOR, level_color: Tuple[(int, int, int)]=DEFAULT_COLOR, xp_color: Tuple[(int, int, int)]=DEFAULT_COLOR, bar_outline_color: Tuple[(int, int, int)]=(255, 255, 255), bar_fill_color: Tuple[(int, int, int)]=DEFAULT_COLOR, bar_blank_color: Tuple[(int, int, int)]=(255, 255, 255), profile_outline_color: Tuple[(int, int, int)]=DEFAULT_COLOR, font_path: str=None, outline: int=5) -> discord.File:
"\n |coro|\n\n Creates a leveling image, converted to a discord.File.\n\n :param discord.Member member: The member.\n :param LevelingAccount member_account: The leveling account of the member.\n :param Union[Backgrounds, str] background: The background of the image.\n :param int rank: The guild rank of the member.\n :param Tuple[int, int, int] name_color: The color of the member's name.\n :param Tuple[int, int, int] rank_color: The color of the member's rank.\n :param Tuple[int, int, int] level_color: The color of the member's level.\n :param Tuple[int, int, int] xp_color: The color of the member's xp.\n :param Tuple[int, int, int] bar_outline_color: The color of the member's progress bar outline.\n :param Tuple[int, int, int] bar_fill_color: The color of the member's progress bar fill.\n :param Tuple[int, int, int] bar_blank_color: The color of the member's progress bar blank.\n :param Tuple[int, int, int] profile_outline_color: The color of the member's outliine.\n :param str font_path: The font path, uses the default font if not passed.\n :param int outline: The outline thickness.\n :return: The image, converted to a discord.File.\n :rtype: discord.File\n "
result_bytes = BytesIO()
card = (Image.open(background.value) if isinstance(background, Backgrounds) else (await self.convert_image(background)))
card = card.resize((850, 238))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
font_big = ImageFont.truetype(font_path, 36)
font_medium = ImageFont.truetype(font_path, 30)
font_normal = ImageFont.truetype(font_path, 25)
font_small = ImageFont.truetype(font_path, 20)
draw = ImageDraw.Draw(card)
draw.text((245, 90), str(member), name_color, font=font_big, anchor='ls')
draw.text((800, 90), f'Rank #{rank}', rank_color, font=font_medium, anchor='rs')
draw.text((245, 165), f'Level {(await member_account.level())}', level_color, font=font_normal, anchor='ls')
draw.text((800, 165), f'{self.human_format((await member_account.xp()))} / {self.human_format((await member_account.next_level()))} XP', xp_color, font=font_small, anchor='rs')
draw.rounded_rectangle((242, 182, 803, 208), fill=bar_blank_color, outline=bar_outline_color, radius=13, width=3)
length_of_bar = (((await member_account.percentage_next_level()) * 5.5) + 250)
draw.rounded_rectangle((245, 185, length_of_bar, 205), fill=bar_fill_color, radius=10)
final_card = (await self.draw_profile_picture(card, member, (109, 119), outline_thickness=outline, outline_color=profile_outline_color))
final_card.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='rankcard.png')
|
|coro|
Creates a leveling image, converted to a discord.File.
:param discord.Member member: The member.
:param LevelingAccount member_account: The leveling account of the member.
:param Union[Backgrounds, str] background: The background of the image.
:param int rank: The guild rank of the member.
:param Tuple[int, int, int] name_color: The color of the member's name.
:param Tuple[int, int, int] rank_color: The color of the member's rank.
:param Tuple[int, int, int] level_color: The color of the member's level.
:param Tuple[int, int, int] xp_color: The color of the member's xp.
:param Tuple[int, int, int] bar_outline_color: The color of the member's progress bar outline.
:param Tuple[int, int, int] bar_fill_color: The color of the member's progress bar fill.
:param Tuple[int, int, int] bar_blank_color: The color of the member's progress bar blank.
:param Tuple[int, int, int] profile_outline_color: The color of the member's outliine.
:param str font_path: The font path, uses the default font if not passed.
:param int outline: The outline thickness.
:return: The image, converted to a discord.File.
:rtype: discord.File
|
discordSuperUtils/imaging.py
|
create_leveling_profile
|
Zetriccc/Amina
| 91
|
python
|
async def create_leveling_profile(self, member: discord.Member, member_account: LevelingAccount, background: Union[(Backgrounds, str)], rank: int, name_color: Tuple[(int, int, int)]=DEFAULT_COLOR, rank_color: Tuple[(int, int, int)]=DEFAULT_COLOR, level_color: Tuple[(int, int, int)]=DEFAULT_COLOR, xp_color: Tuple[(int, int, int)]=DEFAULT_COLOR, bar_outline_color: Tuple[(int, int, int)]=(255, 255, 255), bar_fill_color: Tuple[(int, int, int)]=DEFAULT_COLOR, bar_blank_color: Tuple[(int, int, int)]=(255, 255, 255), profile_outline_color: Tuple[(int, int, int)]=DEFAULT_COLOR, font_path: str=None, outline: int=5) -> discord.File:
"\n |coro|\n\n Creates a leveling image, converted to a discord.File.\n\n :param discord.Member member: The member.\n :param LevelingAccount member_account: The leveling account of the member.\n :param Union[Backgrounds, str] background: The background of the image.\n :param int rank: The guild rank of the member.\n :param Tuple[int, int, int] name_color: The color of the member's name.\n :param Tuple[int, int, int] rank_color: The color of the member's rank.\n :param Tuple[int, int, int] level_color: The color of the member's level.\n :param Tuple[int, int, int] xp_color: The color of the member's xp.\n :param Tuple[int, int, int] bar_outline_color: The color of the member's progress bar outline.\n :param Tuple[int, int, int] bar_fill_color: The color of the member's progress bar fill.\n :param Tuple[int, int, int] bar_blank_color: The color of the member's progress bar blank.\n :param Tuple[int, int, int] profile_outline_color: The color of the member's outliine.\n :param str font_path: The font path, uses the default font if not passed.\n :param int outline: The outline thickness.\n :return: The image, converted to a discord.File.\n :rtype: discord.File\n "
result_bytes = BytesIO()
card = (Image.open(background.value) if isinstance(background, Backgrounds) else (await self.convert_image(background)))
card = card.resize((850, 238))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
font_big = ImageFont.truetype(font_path, 36)
font_medium = ImageFont.truetype(font_path, 30)
font_normal = ImageFont.truetype(font_path, 25)
font_small = ImageFont.truetype(font_path, 20)
draw = ImageDraw.Draw(card)
draw.text((245, 90), str(member), name_color, font=font_big, anchor='ls')
draw.text((800, 90), f'Rank #{rank}', rank_color, font=font_medium, anchor='rs')
draw.text((245, 165), f'Level {(await member_account.level())}', level_color, font=font_normal, anchor='ls')
draw.text((800, 165), f'{self.human_format((await member_account.xp()))} / {self.human_format((await member_account.next_level()))} XP', xp_color, font=font_small, anchor='rs')
draw.rounded_rectangle((242, 182, 803, 208), fill=bar_blank_color, outline=bar_outline_color, radius=13, width=3)
length_of_bar = (((await member_account.percentage_next_level()) * 5.5) + 250)
draw.rounded_rectangle((245, 185, length_of_bar, 205), fill=bar_fill_color, radius=10)
final_card = (await self.draw_profile_picture(card, member, (109, 119), outline_thickness=outline, outline_color=profile_outline_color))
final_card.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='rankcard.png')
|
async def create_leveling_profile(self, member: discord.Member, member_account: LevelingAccount, background: Union[(Backgrounds, str)], rank: int, name_color: Tuple[(int, int, int)]=DEFAULT_COLOR, rank_color: Tuple[(int, int, int)]=DEFAULT_COLOR, level_color: Tuple[(int, int, int)]=DEFAULT_COLOR, xp_color: Tuple[(int, int, int)]=DEFAULT_COLOR, bar_outline_color: Tuple[(int, int, int)]=(255, 255, 255), bar_fill_color: Tuple[(int, int, int)]=DEFAULT_COLOR, bar_blank_color: Tuple[(int, int, int)]=(255, 255, 255), profile_outline_color: Tuple[(int, int, int)]=DEFAULT_COLOR, font_path: str=None, outline: int=5) -> discord.File:
"\n |coro|\n\n Creates a leveling image, converted to a discord.File.\n\n :param discord.Member member: The member.\n :param LevelingAccount member_account: The leveling account of the member.\n :param Union[Backgrounds, str] background: The background of the image.\n :param int rank: The guild rank of the member.\n :param Tuple[int, int, int] name_color: The color of the member's name.\n :param Tuple[int, int, int] rank_color: The color of the member's rank.\n :param Tuple[int, int, int] level_color: The color of the member's level.\n :param Tuple[int, int, int] xp_color: The color of the member's xp.\n :param Tuple[int, int, int] bar_outline_color: The color of the member's progress bar outline.\n :param Tuple[int, int, int] bar_fill_color: The color of the member's progress bar fill.\n :param Tuple[int, int, int] bar_blank_color: The color of the member's progress bar blank.\n :param Tuple[int, int, int] profile_outline_color: The color of the member's outliine.\n :param str font_path: The font path, uses the default font if not passed.\n :param int outline: The outline thickness.\n :return: The image, converted to a discord.File.\n :rtype: discord.File\n "
result_bytes = BytesIO()
card = (Image.open(background.value) if isinstance(background, Backgrounds) else (await self.convert_image(background)))
card = card.resize((850, 238))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
font_big = ImageFont.truetype(font_path, 36)
font_medium = ImageFont.truetype(font_path, 30)
font_normal = ImageFont.truetype(font_path, 25)
font_small = ImageFont.truetype(font_path, 20)
draw = ImageDraw.Draw(card)
draw.text((245, 90), str(member), name_color, font=font_big, anchor='ls')
draw.text((800, 90), f'Rank #{rank}', rank_color, font=font_medium, anchor='rs')
draw.text((245, 165), f'Level {(await member_account.level())}', level_color, font=font_normal, anchor='ls')
draw.text((800, 165), f'{self.human_format((await member_account.xp()))} / {self.human_format((await member_account.next_level()))} XP', xp_color, font=font_small, anchor='rs')
draw.rounded_rectangle((242, 182, 803, 208), fill=bar_blank_color, outline=bar_outline_color, radius=13, width=3)
length_of_bar = (((await member_account.percentage_next_level()) * 5.5) + 250)
draw.rounded_rectangle((245, 185, length_of_bar, 205), fill=bar_fill_color, radius=10)
final_card = (await self.draw_profile_picture(card, member, (109, 119), outline_thickness=outline, outline_color=profile_outline_color))
final_card.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='rankcard.png')<|docstring|>|coro|
Creates a leveling image, converted to a discord.File.
:param discord.Member member: The member.
:param LevelingAccount member_account: The leveling account of the member.
:param Union[Backgrounds, str] background: The background of the image.
:param int rank: The guild rank of the member.
:param Tuple[int, int, int] name_color: The color of the member's name.
:param Tuple[int, int, int] rank_color: The color of the member's rank.
:param Tuple[int, int, int] level_color: The color of the member's level.
:param Tuple[int, int, int] xp_color: The color of the member's xp.
:param Tuple[int, int, int] bar_outline_color: The color of the member's progress bar outline.
:param Tuple[int, int, int] bar_fill_color: The color of the member's progress bar fill.
:param Tuple[int, int, int] bar_blank_color: The color of the member's progress bar blank.
:param Tuple[int, int, int] profile_outline_color: The color of the member's outliine.
:param str font_path: The font path, uses the default font if not passed.
:param int outline: The outline thickness.
:return: The image, converted to a discord.File.
:rtype: discord.File<|endoftext|>
|
b701f17829d988a77740d3c93e64c0cc72e364771c792b55e09f5e4f041ca715
|
async def create_spotify_card(self, spotify_activity: discord.Spotify, font_path: str=None) -> discord.File:
'\n |coro|\n\n Creates a Spotify activity image for the Spotify song and returns it as a discord.File.\n\n :param discord.Spotify spotify_activity: The Spotify activity.\n :param str font_path: The font path, uses the default font if not passed.\n :return: The discord file.\n :rtype: discord.File\n '
result_bytes = BytesIO()
album_image = (await self.convert_image(spotify_activity.album_cover_url))
paletted = album_image.convert('P', palette=Image.ADAPTIVE, colors=1)
palette = paletted.getpalette()
color_counts = paletted.getcolors()
palette_index = color_counts[0][1]
dominant_color = tuple(palette[(palette_index * 3):((palette_index * 3) + 3)])
brightness = (((0.21 * dominant_color[0]) + (0.72 * dominant_color[1])) + (0.07 * dominant_color[2]))
if (brightness < 100):
text_color = 'white'
bg_img = 'spotify_white.png'
else:
text_color = 'black'
bg_img = 'spotify_black.png'
track_background_image = Image.open(self.load_asset(bg_img))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
title_font = ImageFont.truetype(font_path, 16)
artist_font = ImageFont.truetype(font_path, 14)
album_font = ImageFont.truetype(font_path, 14)
start_duration_font = ImageFont.truetype(font_path, 12)
end_duration_font = ImageFont.truetype(font_path, 12)
title_text_position = (150, 30)
artist_text_position = (150, 60)
album_text_position = (150, 80)
start_duration_text_position = (150, 119)
end_duration_text_position = (508, 119)
played_duration = (datetime.datetime.utcnow() - spotify_activity.start).total_seconds()
total_duration = spotify_activity.duration.total_seconds()
played = (played_duration / total_duration)
start_duration = time.strftime('%H:%M:%S', time.gmtime(played_duration))
end_duration = time.strftime('%H:%M:%S', time.gmtime(total_duration))
draw_on_image = ImageDraw.Draw(track_background_image)
draw_on_image.text(title_text_position, spotify_activity.title, text_color, font=title_font)
draw_on_image.text(artist_text_position, f'by {spotify_activity.artist}', text_color, font=artist_font)
draw_on_image.text(album_text_position, spotify_activity.album, text_color, font=album_font)
draw_on_image.text(start_duration_text_position, start_duration, text_color, font=start_duration_font)
draw_on_image.text(end_duration_text_position, end_duration, text_color, font=end_duration_font)
draw_on_image.rounded_rectangle((198, 125, (198 + (300 * played)), 129), fill=text_color, outline=None, radius=3, width=0)
background_image_color = Image.new('RGBA', track_background_image.size, dominant_color)
background_image_color.paste(track_background_image, (0, 0), track_background_image)
album_image_resize = album_image.resize((140, 160))
background_image_color.paste(album_image_resize, (0, 0), album_image_resize)
background_image_color.convert('RGB')
background_image_color.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='spotify.png')
|
|coro|
Creates a Spotify activity image for the Spotify song and returns it as a discord.File.
:param discord.Spotify spotify_activity: The Spotify activity.
:param str font_path: The font path, uses the default font if not passed.
:return: The discord file.
:rtype: discord.File
|
discordSuperUtils/imaging.py
|
create_spotify_card
|
Zetriccc/Amina
| 91
|
python
|
async def create_spotify_card(self, spotify_activity: discord.Spotify, font_path: str=None) -> discord.File:
'\n |coro|\n\n Creates a Spotify activity image for the Spotify song and returns it as a discord.File.\n\n :param discord.Spotify spotify_activity: The Spotify activity.\n :param str font_path: The font path, uses the default font if not passed.\n :return: The discord file.\n :rtype: discord.File\n '
result_bytes = BytesIO()
album_image = (await self.convert_image(spotify_activity.album_cover_url))
paletted = album_image.convert('P', palette=Image.ADAPTIVE, colors=1)
palette = paletted.getpalette()
color_counts = paletted.getcolors()
palette_index = color_counts[0][1]
dominant_color = tuple(palette[(palette_index * 3):((palette_index * 3) + 3)])
brightness = (((0.21 * dominant_color[0]) + (0.72 * dominant_color[1])) + (0.07 * dominant_color[2]))
if (brightness < 100):
text_color = 'white'
bg_img = 'spotify_white.png'
else:
text_color = 'black'
bg_img = 'spotify_black.png'
track_background_image = Image.open(self.load_asset(bg_img))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
title_font = ImageFont.truetype(font_path, 16)
artist_font = ImageFont.truetype(font_path, 14)
album_font = ImageFont.truetype(font_path, 14)
start_duration_font = ImageFont.truetype(font_path, 12)
end_duration_font = ImageFont.truetype(font_path, 12)
title_text_position = (150, 30)
artist_text_position = (150, 60)
album_text_position = (150, 80)
start_duration_text_position = (150, 119)
end_duration_text_position = (508, 119)
played_duration = (datetime.datetime.utcnow() - spotify_activity.start).total_seconds()
total_duration = spotify_activity.duration.total_seconds()
played = (played_duration / total_duration)
start_duration = time.strftime('%H:%M:%S', time.gmtime(played_duration))
end_duration = time.strftime('%H:%M:%S', time.gmtime(total_duration))
draw_on_image = ImageDraw.Draw(track_background_image)
draw_on_image.text(title_text_position, spotify_activity.title, text_color, font=title_font)
draw_on_image.text(artist_text_position, f'by {spotify_activity.artist}', text_color, font=artist_font)
draw_on_image.text(album_text_position, spotify_activity.album, text_color, font=album_font)
draw_on_image.text(start_duration_text_position, start_duration, text_color, font=start_duration_font)
draw_on_image.text(end_duration_text_position, end_duration, text_color, font=end_duration_font)
draw_on_image.rounded_rectangle((198, 125, (198 + (300 * played)), 129), fill=text_color, outline=None, radius=3, width=0)
background_image_color = Image.new('RGBA', track_background_image.size, dominant_color)
background_image_color.paste(track_background_image, (0, 0), track_background_image)
album_image_resize = album_image.resize((140, 160))
background_image_color.paste(album_image_resize, (0, 0), album_image_resize)
background_image_color.convert('RGB')
background_image_color.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='spotify.png')
|
async def create_spotify_card(self, spotify_activity: discord.Spotify, font_path: str=None) -> discord.File:
'\n |coro|\n\n Creates a Spotify activity image for the Spotify song and returns it as a discord.File.\n\n :param discord.Spotify spotify_activity: The Spotify activity.\n :param str font_path: The font path, uses the default font if not passed.\n :return: The discord file.\n :rtype: discord.File\n '
result_bytes = BytesIO()
album_image = (await self.convert_image(spotify_activity.album_cover_url))
paletted = album_image.convert('P', palette=Image.ADAPTIVE, colors=1)
palette = paletted.getpalette()
color_counts = paletted.getcolors()
palette_index = color_counts[0][1]
dominant_color = tuple(palette[(palette_index * 3):((palette_index * 3) + 3)])
brightness = (((0.21 * dominant_color[0]) + (0.72 * dominant_color[1])) + (0.07 * dominant_color[2]))
if (brightness < 100):
text_color = 'white'
bg_img = 'spotify_white.png'
else:
text_color = 'black'
bg_img = 'spotify_black.png'
track_background_image = Image.open(self.load_asset(bg_img))
font_path = (font_path if font_path else self.load_asset('font.ttf'))
title_font = ImageFont.truetype(font_path, 16)
artist_font = ImageFont.truetype(font_path, 14)
album_font = ImageFont.truetype(font_path, 14)
start_duration_font = ImageFont.truetype(font_path, 12)
end_duration_font = ImageFont.truetype(font_path, 12)
title_text_position = (150, 30)
artist_text_position = (150, 60)
album_text_position = (150, 80)
start_duration_text_position = (150, 119)
end_duration_text_position = (508, 119)
played_duration = (datetime.datetime.utcnow() - spotify_activity.start).total_seconds()
total_duration = spotify_activity.duration.total_seconds()
played = (played_duration / total_duration)
start_duration = time.strftime('%H:%M:%S', time.gmtime(played_duration))
end_duration = time.strftime('%H:%M:%S', time.gmtime(total_duration))
draw_on_image = ImageDraw.Draw(track_background_image)
draw_on_image.text(title_text_position, spotify_activity.title, text_color, font=title_font)
draw_on_image.text(artist_text_position, f'by {spotify_activity.artist}', text_color, font=artist_font)
draw_on_image.text(album_text_position, spotify_activity.album, text_color, font=album_font)
draw_on_image.text(start_duration_text_position, start_duration, text_color, font=start_duration_font)
draw_on_image.text(end_duration_text_position, end_duration, text_color, font=end_duration_font)
draw_on_image.rounded_rectangle((198, 125, (198 + (300 * played)), 129), fill=text_color, outline=None, radius=3, width=0)
background_image_color = Image.new('RGBA', track_background_image.size, dominant_color)
background_image_color.paste(track_background_image, (0, 0), track_background_image)
album_image_resize = album_image.resize((140, 160))
background_image_color.paste(album_image_resize, (0, 0), album_image_resize)
background_image_color.convert('RGB')
background_image_color.save(result_bytes, format='PNG')
result_bytes.seek(0)
return discord.File(result_bytes, filename='spotify.png')<|docstring|>|coro|
Creates a Spotify activity image for the Spotify song and returns it as a discord.File.
:param discord.Spotify spotify_activity: The Spotify activity.
:param str font_path: The font path, uses the default font if not passed.
:return: The discord file.
:rtype: discord.File<|endoftext|>
|
b3586487906f71a7d49600894078201c9da251cf13a2ac315240471fd3c8cbc1
|
def __init__(self, case_config: OrderedDict, xrformat=False):
' Parameters\n ----------\n case_config : OrderedDict\n A dictionary containing case information. This is usually read from a yaml\n file but may also be generated manually. The format of the yaml file to\n generate this dictionary:\n\n Case:\n CIMEROOT: ...\n CASEROOT: ...\n RUNDIR: ...\n HIST_FILE_PREFIX: ...\n\n xrformat : boolean, optional\n If True, returns an xarray Dataset with the grid. Otherwise (default), returns an\n object with numpy arrays.\n\n '
self._config = case_config
self._cime_case = None
self._grid = None
self._casename = None
self.diag_files = None
self.diag_fields = None
self.xrformat = xrformat
rundir_provided = ('RUNDIR' in self._config)
dout_s_root_provided = ('DOUT_S_ROOT' in self._config)
caseroot_provided = ('CASEROOT' in self._config)
cimeroot_provided = ('CIMEROOT' in self._config)
if (not (rundir_provided or dout_s_root_provided)):
assert (caseroot_provided and cimeroot_provided), "If 'RUNDIR' or 'DOUT_S_ROOT' are not provided, both 'CASEROOT' and 'CIMEROOT' must be provided."
|
Parameters
----------
case_config : OrderedDict
A dictionary containing case information. This is usually read from a yaml
file but may also be generated manually. The format of the yaml file to
generate this dictionary:
Case:
CIMEROOT: ...
CASEROOT: ...
RUNDIR: ...
HIST_FILE_PREFIX: ...
xrformat : boolean, optional
If True, returns an xarray Dataset with the grid. Otherwise (default), returns an
object with numpy arrays.
|
mom6_tools/DiagsCase.py
|
__init__
|
NCAR/mom6-tools
| 8
|
python
|
def __init__(self, case_config: OrderedDict, xrformat=False):
' Parameters\n ----------\n case_config : OrderedDict\n A dictionary containing case information. This is usually read from a yaml\n file but may also be generated manually. The format of the yaml file to\n generate this dictionary:\n\n Case:\n CIMEROOT: ...\n CASEROOT: ...\n RUNDIR: ...\n HIST_FILE_PREFIX: ...\n\n xrformat : boolean, optional\n If True, returns an xarray Dataset with the grid. Otherwise (default), returns an\n object with numpy arrays.\n\n '
self._config = case_config
self._cime_case = None
self._grid = None
self._casename = None
self.diag_files = None
self.diag_fields = None
self.xrformat = xrformat
rundir_provided = ('RUNDIR' in self._config)
dout_s_root_provided = ('DOUT_S_ROOT' in self._config)
caseroot_provided = ('CASEROOT' in self._config)
cimeroot_provided = ('CIMEROOT' in self._config)
if (not (rundir_provided or dout_s_root_provided)):
assert (caseroot_provided and cimeroot_provided), "If 'RUNDIR' or 'DOUT_S_ROOT' are not provided, both 'CASEROOT' and 'CIMEROOT' must be provided."
|
def __init__(self, case_config: OrderedDict, xrformat=False):
' Parameters\n ----------\n case_config : OrderedDict\n A dictionary containing case information. This is usually read from a yaml\n file but may also be generated manually. The format of the yaml file to\n generate this dictionary:\n\n Case:\n CIMEROOT: ...\n CASEROOT: ...\n RUNDIR: ...\n HIST_FILE_PREFIX: ...\n\n xrformat : boolean, optional\n If True, returns an xarray Dataset with the grid. Otherwise (default), returns an\n object with numpy arrays.\n\n '
self._config = case_config
self._cime_case = None
self._grid = None
self._casename = None
self.diag_files = None
self.diag_fields = None
self.xrformat = xrformat
rundir_provided = ('RUNDIR' in self._config)
dout_s_root_provided = ('DOUT_S_ROOT' in self._config)
caseroot_provided = ('CASEROOT' in self._config)
cimeroot_provided = ('CIMEROOT' in self._config)
if (not (rundir_provided or dout_s_root_provided)):
assert (caseroot_provided and cimeroot_provided), "If 'RUNDIR' or 'DOUT_S_ROOT' are not provided, both 'CASEROOT' and 'CIMEROOT' must be provided."<|docstring|>Parameters
----------
case_config : OrderedDict
A dictionary containing case information. This is usually read from a yaml
file but may also be generated manually. The format of the yaml file to
generate this dictionary:
Case:
CIMEROOT: ...
CASEROOT: ...
RUNDIR: ...
HIST_FILE_PREFIX: ...
xrformat : boolean, optional
If True, returns an xarray Dataset with the grid. Otherwise (default), returns an
object with numpy arrays.<|endoftext|>
|
cf968d926da4166e0b70ecca0ff81e7df1ca5e533219641346a981c7de48e9dc
|
@property
def cime_case(self):
' Returns a CIME case object. Must provide the CIME source root\n in case_config dict when instantiating this class. Any CIME xml variable,\n e.g., OCN_GRID, may be retrieved from the returned object using get_value\n method.'
if (not self._cime_case):
caseroot = self.get_value('CASEROOT')
cimeroot = self.get_value('CIMEROOT')
if (caseroot and cimeroot):
sys.path.append(os.path.join(cimeroot, 'scripts', 'lib'))
from CIME.case.case import Case
self._cime_case = Case(caseroot)
return self._cime_case
|
Returns a CIME case object. Must provide the CIME source root
in case_config dict when instantiating this class. Any CIME xml variable,
e.g., OCN_GRID, may be retrieved from the returned object using get_value
method.
|
mom6_tools/DiagsCase.py
|
cime_case
|
NCAR/mom6-tools
| 8
|
python
|
@property
def cime_case(self):
' Returns a CIME case object. Must provide the CIME source root\n in case_config dict when instantiating this class. Any CIME xml variable,\n e.g., OCN_GRID, may be retrieved from the returned object using get_value\n method.'
if (not self._cime_case):
caseroot = self.get_value('CASEROOT')
cimeroot = self.get_value('CIMEROOT')
if (caseroot and cimeroot):
sys.path.append(os.path.join(cimeroot, 'scripts', 'lib'))
from CIME.case.case import Case
self._cime_case = Case(caseroot)
return self._cime_case
|
@property
def cime_case(self):
' Returns a CIME case object. Must provide the CIME source root\n in case_config dict when instantiating this class. Any CIME xml variable,\n e.g., OCN_GRID, may be retrieved from the returned object using get_value\n method.'
if (not self._cime_case):
caseroot = self.get_value('CASEROOT')
cimeroot = self.get_value('CIMEROOT')
if (caseroot and cimeroot):
sys.path.append(os.path.join(cimeroot, 'scripts', 'lib'))
from CIME.case.case import Case
self._cime_case = Case(caseroot)
return self._cime_case<|docstring|>Returns a CIME case object. Must provide the CIME source root
in case_config dict when instantiating this class. Any CIME xml variable,
e.g., OCN_GRID, may be retrieved from the returned object using get_value
method.<|endoftext|>
|
4ad2c0c6057ffa479e87c2377d5b6fd9cf3c7b2bec99afc577c2b9dfe0163f45
|
@property
def casename(self):
' Returns case name by inferring it from CASEROOT. '
if (not self._casename):
self._deduce_case_name()
return self._casename
|
Returns case name by inferring it from CASEROOT.
|
mom6_tools/DiagsCase.py
|
casename
|
NCAR/mom6-tools
| 8
|
python
|
@property
def casename(self):
' '
if (not self._casename):
self._deduce_case_name()
return self._casename
|
@property
def casename(self):
' '
if (not self._casename):
self._deduce_case_name()
return self._casename<|docstring|>Returns case name by inferring it from CASEROOT.<|endoftext|>
|
db28dfac64e4d1194309badea748ab796f78395555b72866a86b3eae6bea7b4b
|
def get_value(self, var):
' Returns the value of a variable in yaml config file. If the variable is not\n in yaml config file, then checks to see if it can retrieve the var from cime_case\n instance.\n\n Parameters\n ----------\n var : string\n Variable name\n\n '
val = None
if (var in self._config):
val = self._config[var]
elif self.cime_case:
val = self.cime_case.get_value(var)
if ((type(val) == type('')) and (val.lower() == 'none')):
val = None
log.info(f'''get_value::
requsted variable: {var}
returning value: {val}
type: {type(val)}''')
return val
|
Returns the value of a variable in yaml config file. If the variable is not
in yaml config file, then checks to see if it can retrieve the var from cime_case
instance.
Parameters
----------
var : string
Variable name
|
mom6_tools/DiagsCase.py
|
get_value
|
NCAR/mom6-tools
| 8
|
python
|
def get_value(self, var):
' Returns the value of a variable in yaml config file. If the variable is not\n in yaml config file, then checks to see if it can retrieve the var from cime_case\n instance.\n\n Parameters\n ----------\n var : string\n Variable name\n\n '
val = None
if (var in self._config):
val = self._config[var]
elif self.cime_case:
val = self.cime_case.get_value(var)
if ((type(val) == type()) and (val.lower() == 'none')):
val = None
log.info(f'get_value::
requsted variable: {var}
returning value: {val}
type: {type(val)}')
return val
|
def get_value(self, var):
' Returns the value of a variable in yaml config file. If the variable is not\n in yaml config file, then checks to see if it can retrieve the var from cime_case\n instance.\n\n Parameters\n ----------\n var : string\n Variable name\n\n '
val = None
if (var in self._config):
val = self._config[var]
elif self.cime_case:
val = self.cime_case.get_value(var)
if ((type(val) == type()) and (val.lower() == 'none')):
val = None
log.info(f'get_value::
requsted variable: {var}
returning value: {val}
type: {type(val)}')
return val<|docstring|>Returns the value of a variable in yaml config file. If the variable is not
in yaml config file, then checks to see if it can retrieve the var from cime_case
instance.
Parameters
----------
var : string
Variable name<|endoftext|>
|
9b9f83789a16bf204ef573ee3e96c5dd566cb04821f755beb8d9ddd679f639bf
|
def get_file_prefix(self, fld_to_search: str, output_freq=None, output_freq_units=None) -> str:
'Returns the prefix of file including a given field'
candidate_files = set()
for (fld_name, file_name) in self.diag_fields:
if (fld_to_search == fld_name):
log.info(f'{fld_to_search}, {fld_name}, {file_name}')
candidate_files.add(file_name)
log.info(f'{fld_to_search} found in {candidate_files}')
if ((output_freq != None) or (output_freq_units != None)):
non_matching_files = set()
for matched_file in candidate_files:
if ((output_freq and (self.diag_files[matched_file].output_freq != output_freq)) or (output_freq_units and (self.diag_files[matched_file].output_freq_units != output_freq_units))):
non_matching_files.add(matched_file)
candidate_files -= non_matching_files
if (len(candidate_files) == 0):
raise RuntimeError(f"Cannot find '{fld_to_search}' in diag_table")
elif (len(candidate_files) > 1):
raise RuntimeError(f"Multiple '{fld_to_search}' entries in diag_table. Provide HIST_FILE_PREFIX!")
else:
pass
file_prefix = candidate_files.pop()
log.info(f'returning {file_prefix} including {fld_to_search}')
return file_prefix
|
Returns the prefix of file including a given field
|
mom6_tools/DiagsCase.py
|
get_file_prefix
|
NCAR/mom6-tools
| 8
|
python
|
def get_file_prefix(self, fld_to_search: str, output_freq=None, output_freq_units=None) -> str:
candidate_files = set()
for (fld_name, file_name) in self.diag_fields:
if (fld_to_search == fld_name):
log.info(f'{fld_to_search}, {fld_name}, {file_name}')
candidate_files.add(file_name)
log.info(f'{fld_to_search} found in {candidate_files}')
if ((output_freq != None) or (output_freq_units != None)):
non_matching_files = set()
for matched_file in candidate_files:
if ((output_freq and (self.diag_files[matched_file].output_freq != output_freq)) or (output_freq_units and (self.diag_files[matched_file].output_freq_units != output_freq_units))):
non_matching_files.add(matched_file)
candidate_files -= non_matching_files
if (len(candidate_files) == 0):
raise RuntimeError(f"Cannot find '{fld_to_search}' in diag_table")
elif (len(candidate_files) > 1):
raise RuntimeError(f"Multiple '{fld_to_search}' entries in diag_table. Provide HIST_FILE_PREFIX!")
else:
pass
file_prefix = candidate_files.pop()
log.info(f'returning {file_prefix} including {fld_to_search}')
return file_prefix
|
def get_file_prefix(self, fld_to_search: str, output_freq=None, output_freq_units=None) -> str:
candidate_files = set()
for (fld_name, file_name) in self.diag_fields:
if (fld_to_search == fld_name):
log.info(f'{fld_to_search}, {fld_name}, {file_name}')
candidate_files.add(file_name)
log.info(f'{fld_to_search} found in {candidate_files}')
if ((output_freq != None) or (output_freq_units != None)):
non_matching_files = set()
for matched_file in candidate_files:
if ((output_freq and (self.diag_files[matched_file].output_freq != output_freq)) or (output_freq_units and (self.diag_files[matched_file].output_freq_units != output_freq_units))):
non_matching_files.add(matched_file)
candidate_files -= non_matching_files
if (len(candidate_files) == 0):
raise RuntimeError(f"Cannot find '{fld_to_search}' in diag_table")
elif (len(candidate_files) > 1):
raise RuntimeError(f"Multiple '{fld_to_search}' entries in diag_table. Provide HIST_FILE_PREFIX!")
else:
pass
file_prefix = candidate_files.pop()
log.info(f'returning {file_prefix} including {fld_to_search}')
return file_prefix<|docstring|>Returns the prefix of file including a given field<|endoftext|>
|
cd946efc682834dde4260ed9ff442d5c38412abe7f244ffff23d75545de61246
|
@property
def grid(self):
' MOM6grid instance '
if (not self._grid):
self._generate_grid()
return self._grid
|
MOM6grid instance
|
mom6_tools/DiagsCase.py
|
grid
|
NCAR/mom6-tools
| 8
|
python
|
@property
def grid(self):
' '
if (not self._grid):
self._generate_grid()
return self._grid
|
@property
def grid(self):
' '
if (not self._grid):
self._generate_grid()
return self._grid<|docstring|>MOM6grid instance<|endoftext|>
|
c04f8ee6702bd7ec596fa7f237ac6ed8f171bfac3b79f79e9bbd7e256bb25e62
|
def stage_dset(self, fields: list):
' Generates a dataset containing the given fields for the entire\n duration of a run\n\n Parameters\n ----------\n fields : list\n The list of fields of this case to include in the dataset to be generated."\n\n Returns\n -------\n xarray.Dataset\n '
log.info(f'Constructing a dataset for fields: {fields}')
file_list = self._get_file_list(fields)
dset = xr.open_mfdataset(file_list)
if ('average_T1' not in fields):
fields.append('average_T1')
if ('average_T2' not in fields):
fields.append('average_T2')
dset = dset[fields]
return dset
|
Generates a dataset containing the given fields for the entire
duration of a run
Parameters
----------
fields : list
The list of fields of this case to include in the dataset to be generated."
Returns
-------
xarray.Dataset
|
mom6_tools/DiagsCase.py
|
stage_dset
|
NCAR/mom6-tools
| 8
|
python
|
def stage_dset(self, fields: list):
' Generates a dataset containing the given fields for the entire\n duration of a run\n\n Parameters\n ----------\n fields : list\n The list of fields of this case to include in the dataset to be generated."\n\n Returns\n -------\n xarray.Dataset\n '
log.info(f'Constructing a dataset for fields: {fields}')
file_list = self._get_file_list(fields)
dset = xr.open_mfdataset(file_list)
if ('average_T1' not in fields):
fields.append('average_T1')
if ('average_T2' not in fields):
fields.append('average_T2')
dset = dset[fields]
return dset
|
def stage_dset(self, fields: list):
' Generates a dataset containing the given fields for the entire\n duration of a run\n\n Parameters\n ----------\n fields : list\n The list of fields of this case to include in the dataset to be generated."\n\n Returns\n -------\n xarray.Dataset\n '
log.info(f'Constructing a dataset for fields: {fields}')
file_list = self._get_file_list(fields)
dset = xr.open_mfdataset(file_list)
if ('average_T1' not in fields):
fields.append('average_T1')
if ('average_T2' not in fields):
fields.append('average_T2')
dset = dset[fields]
return dset<|docstring|>Generates a dataset containing the given fields for the entire
duration of a run
Parameters
----------
fields : list
The list of fields of this case to include in the dataset to be generated."
Returns
-------
xarray.Dataset<|endoftext|>
|
fde7295432908a4d3e910379a885c7f502ff744cb5fafc0524c05fd8653616a8
|
@property
def error_code(self):
'\n Error code, if the operation caused an error.\n '
return self._error_code
|
Error code, if the operation caused an error.
|
generated-libraries/python/netapp/coredump/coredump_delete_core_iter_info.py
|
error_code
|
radekg/netapp-ontap-lib-get
| 2
|
python
|
@property
def error_code(self):
'\n \n '
return self._error_code
|
@property
def error_code(self):
'\n \n '
return self._error_code<|docstring|>Error code, if the operation caused an error.<|endoftext|>
|
39023b414eb859464c9548e47de883890d481ae19135b086c4a8589e78196074
|
@property
def coredump_key(self):
'\n The keys for the coredump object to which the operation\n applies.\n '
return self._coredump_key
|
The keys for the coredump object to which the operation
applies.
|
generated-libraries/python/netapp/coredump/coredump_delete_core_iter_info.py
|
coredump_key
|
radekg/netapp-ontap-lib-get
| 2
|
python
|
@property
def coredump_key(self):
'\n The keys for the coredump object to which the operation\n applies.\n '
return self._coredump_key
|
@property
def coredump_key(self):
'\n The keys for the coredump object to which the operation\n applies.\n '
return self._coredump_key<|docstring|>The keys for the coredump object to which the operation
applies.<|endoftext|>
|
bbd4697442789bf0990a939b2404e6a6d9dfe4825c00e9aa6ab4d1c55d600a7f
|
@property
def error_message(self):
'\n Error description, if the operation caused an error.\n '
return self._error_message
|
Error description, if the operation caused an error.
|
generated-libraries/python/netapp/coredump/coredump_delete_core_iter_info.py
|
error_message
|
radekg/netapp-ontap-lib-get
| 2
|
python
|
@property
def error_message(self):
'\n \n '
return self._error_message
|
@property
def error_message(self):
'\n \n '
return self._error_message<|docstring|>Error description, if the operation caused an error.<|endoftext|>
|
d2503de929573a2797e9feee004658a8736c556231f971b37a83123a6a93e91c
|
async def get_bucket_object(bucket=None, name=None, opts=None):
'\n Gets an existing object inside an existing bucket in Google Cloud Storage service (GCS).\n See [the official documentation](https://cloud.google.com/storage/docs/key-terms#objects)\n and\n [API](https://cloud.google.com/storage/docs/json_api/v1/objects).\n '
__args__ = dict()
__args__['bucket'] = bucket
__args__['name'] = name
__ret__ = (await pulumi.runtime.invoke('gcp:storage/getBucketObject:getBucketObject', __args__, opts=opts))
return GetBucketObjectResult(cache_control=__ret__.get('cacheControl'), content=__ret__.get('content'), content_disposition=__ret__.get('contentDisposition'), content_encoding=__ret__.get('contentEncoding'), content_language=__ret__.get('contentLanguage'), content_type=__ret__.get('contentType'), crc32c=__ret__.get('crc32c'), detect_md5hash=__ret__.get('detectMd5hash'), md5hash=__ret__.get('md5hash'), output_name=__ret__.get('outputName'), predefined_acl=__ret__.get('predefinedAcl'), self_link=__ret__.get('selfLink'), source=__ret__.get('source'), storage_class=__ret__.get('storageClass'), id=__ret__.get('id'))
|
Gets an existing object inside an existing bucket in Google Cloud Storage service (GCS).
See [the official documentation](https://cloud.google.com/storage/docs/key-terms#objects)
and
[API](https://cloud.google.com/storage/docs/json_api/v1/objects).
|
sdk/python/pulumi_gcp/storage/get_bucket_object.py
|
get_bucket_object
|
stack72/pulumi-gcp
| 0
|
python
|
async def get_bucket_object(bucket=None, name=None, opts=None):
'\n Gets an existing object inside an existing bucket in Google Cloud Storage service (GCS).\n See [the official documentation](https://cloud.google.com/storage/docs/key-terms#objects)\n and\n [API](https://cloud.google.com/storage/docs/json_api/v1/objects).\n '
__args__ = dict()
__args__['bucket'] = bucket
__args__['name'] = name
__ret__ = (await pulumi.runtime.invoke('gcp:storage/getBucketObject:getBucketObject', __args__, opts=opts))
return GetBucketObjectResult(cache_control=__ret__.get('cacheControl'), content=__ret__.get('content'), content_disposition=__ret__.get('contentDisposition'), content_encoding=__ret__.get('contentEncoding'), content_language=__ret__.get('contentLanguage'), content_type=__ret__.get('contentType'), crc32c=__ret__.get('crc32c'), detect_md5hash=__ret__.get('detectMd5hash'), md5hash=__ret__.get('md5hash'), output_name=__ret__.get('outputName'), predefined_acl=__ret__.get('predefinedAcl'), self_link=__ret__.get('selfLink'), source=__ret__.get('source'), storage_class=__ret__.get('storageClass'), id=__ret__.get('id'))
|
async def get_bucket_object(bucket=None, name=None, opts=None):
'\n Gets an existing object inside an existing bucket in Google Cloud Storage service (GCS).\n See [the official documentation](https://cloud.google.com/storage/docs/key-terms#objects)\n and\n [API](https://cloud.google.com/storage/docs/json_api/v1/objects).\n '
__args__ = dict()
__args__['bucket'] = bucket
__args__['name'] = name
__ret__ = (await pulumi.runtime.invoke('gcp:storage/getBucketObject:getBucketObject', __args__, opts=opts))
return GetBucketObjectResult(cache_control=__ret__.get('cacheControl'), content=__ret__.get('content'), content_disposition=__ret__.get('contentDisposition'), content_encoding=__ret__.get('contentEncoding'), content_language=__ret__.get('contentLanguage'), content_type=__ret__.get('contentType'), crc32c=__ret__.get('crc32c'), detect_md5hash=__ret__.get('detectMd5hash'), md5hash=__ret__.get('md5hash'), output_name=__ret__.get('outputName'), predefined_acl=__ret__.get('predefinedAcl'), self_link=__ret__.get('selfLink'), source=__ret__.get('source'), storage_class=__ret__.get('storageClass'), id=__ret__.get('id'))<|docstring|>Gets an existing object inside an existing bucket in Google Cloud Storage service (GCS).
See [the official documentation](https://cloud.google.com/storage/docs/key-terms#objects)
and
[API](https://cloud.google.com/storage/docs/json_api/v1/objects).<|endoftext|>
|
cc30bf1997f978fef4a9020b90eade5a2193e5037d89ed54454dd2904b54d39a
|
def get_main_content(response: requests.Response):
" Function that gets <div id='main-content'>..</div> from the response. "
soup = BeautifulSoup(response.content)
return soup.find('div', {'id': 'main-content'})
|
Function that gets <div id='main-content'>..</div> from the response.
|
calorizator_parser/parser.py
|
get_main_content
|
healty-diet/calorizator_parser
| 2
|
python
|
def get_main_content(response: requests.Response):
" "
soup = BeautifulSoup(response.content)
return soup.find('div', {'id': 'main-content'})
|
def get_main_content(response: requests.Response):
" "
soup = BeautifulSoup(response.content)
return soup.find('div', {'id': 'main-content'})<|docstring|>Function that gets <div id='main-content'>..</div> from the response.<|endoftext|>
|
6e57f5150fb8e61883ad71f808f2c34ffa0a1c2fa9e5077b268b4f2ddf6ac9eb
|
def get_calorizator_pages_amount() -> int:
' Returns the amount of pages on the calorizator site. '
response = requests.get(CALORIZATOR_URL)
if (response.status_code != 200):
raise CalorizatorApiError('Error while getting calorizator pages amount: {}'.format(response.status_code))
main_content = get_main_content(response)
pager_last = main_content.find('li', {'class': 'pager-last'})
return int(pager_last.string)
|
Returns the amount of pages on the calorizator site.
|
calorizator_parser/parser.py
|
get_calorizator_pages_amount
|
healty-diet/calorizator_parser
| 2
|
python
|
def get_calorizator_pages_amount() -> int:
' '
response = requests.get(CALORIZATOR_URL)
if (response.status_code != 200):
raise CalorizatorApiError('Error while getting calorizator pages amount: {}'.format(response.status_code))
main_content = get_main_content(response)
pager_last = main_content.find('li', {'class': 'pager-last'})
return int(pager_last.string)
|
def get_calorizator_pages_amount() -> int:
' '
response = requests.get(CALORIZATOR_URL)
if (response.status_code != 200):
raise CalorizatorApiError('Error while getting calorizator pages amount: {}'.format(response.status_code))
main_content = get_main_content(response)
pager_last = main_content.find('li', {'class': 'pager-last'})
return int(pager_last.string)<|docstring|>Returns the amount of pages on the calorizator site.<|endoftext|>
|
2723478d7726ea34e3f1393ffb249446cfb3f5f4f27bf0f9245a85aa09c05445
|
def get_calorizator_page(page_idx: int) -> requests.Response:
' Function to get the page from calorizator site. '
response = requests.get(CALORIZATOR_URL, {'page': page_idx})
if (response.status_code != 200):
raise CalorizatorApiError('Error while getting calorizator page {}: {}'.format(page_idx, response.status_code))
return response
|
Function to get the page from calorizator site.
|
calorizator_parser/parser.py
|
get_calorizator_page
|
healty-diet/calorizator_parser
| 2
|
python
|
def get_calorizator_page(page_idx: int) -> requests.Response:
' '
response = requests.get(CALORIZATOR_URL, {'page': page_idx})
if (response.status_code != 200):
raise CalorizatorApiError('Error while getting calorizator page {}: {}'.format(page_idx, response.status_code))
return response
|
def get_calorizator_page(page_idx: int) -> requests.Response:
' '
response = requests.get(CALORIZATOR_URL, {'page': page_idx})
if (response.status_code != 200):
raise CalorizatorApiError('Error while getting calorizator page {}: {}'.format(page_idx, response.status_code))
return response<|docstring|>Function to get the page from calorizator site.<|endoftext|>
|
a82cbc6f8cf1d2aa4fded64de787ba8b76e7ad6894fee2846dcd0d5b6afdb74a
|
def parse_float(data: str) -> float:
' Parses float from string. If parsing failed, returns 0.0 '
try:
return float(data.strip())
except ValueError:
return 0.0
|
Parses float from string. If parsing failed, returns 0.0
|
calorizator_parser/parser.py
|
parse_float
|
healty-diet/calorizator_parser
| 2
|
python
|
def parse_float(data: str) -> float:
' '
try:
return float(data.strip())
except ValueError:
return 0.0
|
def parse_float(data: str) -> float:
' '
try:
return float(data.strip())
except ValueError:
return 0.0<|docstring|>Parses float from string. If parsing failed, returns 0.0<|endoftext|>
|
c2526b7790da6f9298c9bf92da75ea25b91dfc109b41520468aaf29cc201d809
|
def parse_calorizator_page(page: requests.Response) -> Dict[(str, Dict[(str, float)])]:
' Parses the calorizator page and extracts the calories data. '
main_content = get_main_content(page)
main_table = None
for table in main_content.find_all('table'):
try:
entries = table.thead.find('tr').find_all('th')[2:]
entries_names = list(map((lambda x: x.a.string), entries))
expected = ['Бел, г', 'Жир, г', 'Угл, г', 'Кал, ккал']
if (entries_names == expected):
main_table = table
break
except AttributeError:
pass
if (not main_table):
raise CalorizatorApiError('Not found main table on page {}'.format(page))
result = {}
for entry in main_table.find('tbody').find_all('tr'):
columns = entry.find_all('td')
name = columns[1].a.string.strip()
parsed_entry = {'protein': parse_float(columns[2].string), 'fat': parse_float(columns[3].string), 'carbohydrates': parse_float(columns[4].string), 'calories': parse_float(columns[5].string)}
result[name] = parsed_entry
return result
|
Parses the calorizator page and extracts the calories data.
|
calorizator_parser/parser.py
|
parse_calorizator_page
|
healty-diet/calorizator_parser
| 2
|
python
|
def parse_calorizator_page(page: requests.Response) -> Dict[(str, Dict[(str, float)])]:
' '
main_content = get_main_content(page)
main_table = None
for table in main_content.find_all('table'):
try:
entries = table.thead.find('tr').find_all('th')[2:]
entries_names = list(map((lambda x: x.a.string), entries))
expected = ['Бел, г', 'Жир, г', 'Угл, г', 'Кал, ккал']
if (entries_names == expected):
main_table = table
break
except AttributeError:
pass
if (not main_table):
raise CalorizatorApiError('Not found main table on page {}'.format(page))
result = {}
for entry in main_table.find('tbody').find_all('tr'):
columns = entry.find_all('td')
name = columns[1].a.string.strip()
parsed_entry = {'protein': parse_float(columns[2].string), 'fat': parse_float(columns[3].string), 'carbohydrates': parse_float(columns[4].string), 'calories': parse_float(columns[5].string)}
result[name] = parsed_entry
return result
|
def parse_calorizator_page(page: requests.Response) -> Dict[(str, Dict[(str, float)])]:
' '
main_content = get_main_content(page)
main_table = None
for table in main_content.find_all('table'):
try:
entries = table.thead.find('tr').find_all('th')[2:]
entries_names = list(map((lambda x: x.a.string), entries))
expected = ['Бел, г', 'Жир, г', 'Угл, г', 'Кал, ккал']
if (entries_names == expected):
main_table = table
break
except AttributeError:
pass
if (not main_table):
raise CalorizatorApiError('Not found main table on page {}'.format(page))
result = {}
for entry in main_table.find('tbody').find_all('tr'):
columns = entry.find_all('td')
name = columns[1].a.string.strip()
parsed_entry = {'protein': parse_float(columns[2].string), 'fat': parse_float(columns[3].string), 'carbohydrates': parse_float(columns[4].string), 'calories': parse_float(columns[5].string)}
result[name] = parsed_entry
return result<|docstring|>Parses the calorizator page and extracts the calories data.<|endoftext|>
|
b7fb78ca9ee22f4b8c5da99d29ec39b741c11a89a245386dd4ea1dafbcf675e0
|
def get_wait_interval(start, stop) -> float:
' Function to choose a random number between start and stop. '
interval = (stop - start)
random_shift = (random.random() * interval)
return (start + random_shift)
|
Function to choose a random number between start and stop.
|
calorizator_parser/parser.py
|
get_wait_interval
|
healty-diet/calorizator_parser
| 2
|
python
|
def get_wait_interval(start, stop) -> float:
' '
interval = (stop - start)
random_shift = (random.random() * interval)
return (start + random_shift)
|
def get_wait_interval(start, stop) -> float:
' '
interval = (stop - start)
random_shift = (random.random() * interval)
return (start + random_shift)<|docstring|>Function to choose a random number between start and stop.<|endoftext|>
|
87ce08d5f55b2abc7b69e6082ba3b4296ec004894117e2efe9a42ce7f75fdb4c
|
def wait():
' Function that sleeps for a short period of time to prevent high load of the site. '
wait_interval = get_wait_interval(1, 3)
time.sleep(wait_interval)
|
Function that sleeps for a short period of time to prevent high load of the site.
|
calorizator_parser/parser.py
|
wait
|
healty-diet/calorizator_parser
| 2
|
python
|
def wait():
' '
wait_interval = get_wait_interval(1, 3)
time.sleep(wait_interval)
|
def wait():
' '
wait_interval = get_wait_interval(1, 3)
time.sleep(wait_interval)<|docstring|>Function that sleeps for a short period of time to prevent high load of the site.<|endoftext|>
|
9538537e8b81bbd51a5706780c00fa640e2f37a1c93b5cba490452e259c26dc8
|
def main(args):
' Main parser function. '
page_num = get_calorizator_pages_amount()
result_entries: Dict[(str, Dict[(str, float)])] = {}
for page_idx in range(page_num):
page = get_calorizator_page(page_idx)
page_data = parse_calorizator_page(page)
result_entries.update(page_data)
wait()
with open(args.output, 'w') as file:
file.write(json.dumps(result_entries))
|
Main parser function.
|
calorizator_parser/parser.py
|
main
|
healty-diet/calorizator_parser
| 2
|
python
|
def main(args):
' '
page_num = get_calorizator_pages_amount()
result_entries: Dict[(str, Dict[(str, float)])] = {}
for page_idx in range(page_num):
page = get_calorizator_page(page_idx)
page_data = parse_calorizator_page(page)
result_entries.update(page_data)
wait()
with open(args.output, 'w') as file:
file.write(json.dumps(result_entries))
|
def main(args):
' '
page_num = get_calorizator_pages_amount()
result_entries: Dict[(str, Dict[(str, float)])] = {}
for page_idx in range(page_num):
page = get_calorizator_page(page_idx)
page_data = parse_calorizator_page(page)
result_entries.update(page_data)
wait()
with open(args.output, 'w') as file:
file.write(json.dumps(result_entries))<|docstring|>Main parser function.<|endoftext|>
|
0121cb712334b01575e07293926516f9e39a7e1550d60b65ecf685aec88c50f8
|
def __init__(self, urls, **kwargs):
"Create a new instance of a Publisher class\n\n :param urls: List of RabbitMQ cluster URLs\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.exchange_declare method\n\n :returns: Object of type Publisher\n :rtype: ExchangePublisher\n\n "
self._urls = urls
self._arguments = kwargs
self._connection = None
self._channel = None
self._confirm_delivery = False
if ('confirm_delivery' in kwargs):
self._confirm_delivery = True
self._arguments.pop('confirm_delivery', None)
|
Create a new instance of a Publisher class
:param urls: List of RabbitMQ cluster URLs
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/value pairs passed to the arguments
parameter of pika's channel.exchange_declare method
:returns: Object of type Publisher
:rtype: ExchangePublisher
|
sdc/rabbit/publishers.py
|
__init__
|
ONSdigital/sdc-rabbit-python
| 1
|
python
|
def __init__(self, urls, **kwargs):
"Create a new instance of a Publisher class\n\n :param urls: List of RabbitMQ cluster URLs\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.exchange_declare method\n\n :returns: Object of type Publisher\n :rtype: ExchangePublisher\n\n "
self._urls = urls
self._arguments = kwargs
self._connection = None
self._channel = None
self._confirm_delivery = False
if ('confirm_delivery' in kwargs):
self._confirm_delivery = True
self._arguments.pop('confirm_delivery', None)
|
def __init__(self, urls, **kwargs):
"Create a new instance of a Publisher class\n\n :param urls: List of RabbitMQ cluster URLs\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.exchange_declare method\n\n :returns: Object of type Publisher\n :rtype: ExchangePublisher\n\n "
self._urls = urls
self._arguments = kwargs
self._connection = None
self._channel = None
self._confirm_delivery = False
if ('confirm_delivery' in kwargs):
self._confirm_delivery = True
self._arguments.pop('confirm_delivery', None)<|docstring|>Create a new instance of a Publisher class
:param urls: List of RabbitMQ cluster URLs
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/value pairs passed to the arguments
parameter of pika's channel.exchange_declare method
:returns: Object of type Publisher
:rtype: ExchangePublisher<|endoftext|>
|
45c71b5c530167c76dd96c639b986efd664cefa5278042c047f62c62be84edb6
|
def _connect(self):
'\n Connect to a RabbitMQ instance\n\n :returns: Boolean corresponding to success of connection\n :rtype: bool\n\n '
logger.info('Connecting to rabbit')
for url in self._urls:
try:
self._connection = pika.BlockingConnection(pika.URLParameters(url))
self._channel = self._connection.channel()
self._declare()
if self._confirm_delivery:
self._channel.confirm_delivery()
logger.info('Enabled delivery confirmation')
logger.debug('Connected to rabbit')
return True
except pika.exceptions.AMQPConnectionError:
logger.exception('Unable to connect to rabbit')
continue
except Exception:
logger.exception('Unexpected exception connecting to rabbit')
continue
raise pika.exceptions.AMQPConnectionError
|
Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool
|
sdc/rabbit/publishers.py
|
_connect
|
ONSdigital/sdc-rabbit-python
| 1
|
python
|
def _connect(self):
'\n Connect to a RabbitMQ instance\n\n :returns: Boolean corresponding to success of connection\n :rtype: bool\n\n '
logger.info('Connecting to rabbit')
for url in self._urls:
try:
self._connection = pika.BlockingConnection(pika.URLParameters(url))
self._channel = self._connection.channel()
self._declare()
if self._confirm_delivery:
self._channel.confirm_delivery()
logger.info('Enabled delivery confirmation')
logger.debug('Connected to rabbit')
return True
except pika.exceptions.AMQPConnectionError:
logger.exception('Unable to connect to rabbit')
continue
except Exception:
logger.exception('Unexpected exception connecting to rabbit')
continue
raise pika.exceptions.AMQPConnectionError
|
def _connect(self):
'\n Connect to a RabbitMQ instance\n\n :returns: Boolean corresponding to success of connection\n :rtype: bool\n\n '
logger.info('Connecting to rabbit')
for url in self._urls:
try:
self._connection = pika.BlockingConnection(pika.URLParameters(url))
self._channel = self._connection.channel()
self._declare()
if self._confirm_delivery:
self._channel.confirm_delivery()
logger.info('Enabled delivery confirmation')
logger.debug('Connected to rabbit')
return True
except pika.exceptions.AMQPConnectionError:
logger.exception('Unable to connect to rabbit')
continue
except Exception:
logger.exception('Unexpected exception connecting to rabbit')
continue
raise pika.exceptions.AMQPConnectionError<|docstring|>Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool<|endoftext|>
|
effd6fe10e511d256509f84ee59e2896f7b7880f4202f07267b0443c80ada29e
|
def _disconnect(self):
'\n Cleanly close a RabbitMQ connection.\n\n :returns: None\n\n '
try:
self._connection.close()
logger.debug('Disconnected from rabbit')
except ConnectionWrongStateError:
logger.exception('Close called on closed connection')
except Exception:
logger.exception('Unable to close connection')
|
Cleanly close a RabbitMQ connection.
:returns: None
|
sdc/rabbit/publishers.py
|
_disconnect
|
ONSdigital/sdc-rabbit-python
| 1
|
python
|
def _disconnect(self):
'\n Cleanly close a RabbitMQ connection.\n\n :returns: None\n\n '
try:
self._connection.close()
logger.debug('Disconnected from rabbit')
except ConnectionWrongStateError:
logger.exception('Close called on closed connection')
except Exception:
logger.exception('Unable to close connection')
|
def _disconnect(self):
'\n Cleanly close a RabbitMQ connection.\n\n :returns: None\n\n '
try:
self._connection.close()
logger.debug('Disconnected from rabbit')
except ConnectionWrongStateError:
logger.exception('Close called on closed connection')
except Exception:
logger.exception('Unable to close connection')<|docstring|>Cleanly close a RabbitMQ connection.
:returns: None<|endoftext|>
|
f8621dbc3a3c906bf4233a5b3cc9a957e5d4a0ead6bc5302928edcd21950ed1f
|
def publish_message(self, message, content_type=None, headers=None, mandatory=False):
'\n Publish a response message to a RabbitMQ instance.\n\n :param message: Response message\n :param content_type: Pika BasicProperties content_type value\n :param headers: Message header properties\n :param mandatory: The mandatory flag\n\n :returns: Boolean corresponding to the success of publishing\n :rtype: bool\n\n '
logger.debug('Publishing message')
try:
self._connect()
self._do_publish(mandatory=mandatory, content_type=content_type, headers=headers, message=message)
return True
except pika.exceptions.AMQPConnectionError:
logger.error('AMQPConnectionError occurred. Message not published.')
raise PublishMessageError
except NackError:
logger.error('NackError occurred. Message not published.')
raise PublishMessageError
except UnroutableError:
logger.error('UnroutableError occurred. Message not published.')
raise PublishMessageError
except Exception:
logger.exception('Unknown exception occurred. Message not published.')
raise PublishMessageError
|
Publish a response message to a RabbitMQ instance.
:param message: Response message
:param content_type: Pika BasicProperties content_type value
:param headers: Message header properties
:param mandatory: The mandatory flag
:returns: Boolean corresponding to the success of publishing
:rtype: bool
|
sdc/rabbit/publishers.py
|
publish_message
|
ONSdigital/sdc-rabbit-python
| 1
|
python
|
def publish_message(self, message, content_type=None, headers=None, mandatory=False):
'\n Publish a response message to a RabbitMQ instance.\n\n :param message: Response message\n :param content_type: Pika BasicProperties content_type value\n :param headers: Message header properties\n :param mandatory: The mandatory flag\n\n :returns: Boolean corresponding to the success of publishing\n :rtype: bool\n\n '
logger.debug('Publishing message')
try:
self._connect()
self._do_publish(mandatory=mandatory, content_type=content_type, headers=headers, message=message)
return True
except pika.exceptions.AMQPConnectionError:
logger.error('AMQPConnectionError occurred. Message not published.')
raise PublishMessageError
except NackError:
logger.error('NackError occurred. Message not published.')
raise PublishMessageError
except UnroutableError:
logger.error('UnroutableError occurred. Message not published.')
raise PublishMessageError
except Exception:
logger.exception('Unknown exception occurred. Message not published.')
raise PublishMessageError
|
def publish_message(self, message, content_type=None, headers=None, mandatory=False):
'\n Publish a response message to a RabbitMQ instance.\n\n :param message: Response message\n :param content_type: Pika BasicProperties content_type value\n :param headers: Message header properties\n :param mandatory: The mandatory flag\n\n :returns: Boolean corresponding to the success of publishing\n :rtype: bool\n\n '
logger.debug('Publishing message')
try:
self._connect()
self._do_publish(mandatory=mandatory, content_type=content_type, headers=headers, message=message)
return True
except pika.exceptions.AMQPConnectionError:
logger.error('AMQPConnectionError occurred. Message not published.')
raise PublishMessageError
except NackError:
logger.error('NackError occurred. Message not published.')
raise PublishMessageError
except UnroutableError:
logger.error('UnroutableError occurred. Message not published.')
raise PublishMessageError
except Exception:
logger.exception('Unknown exception occurred. Message not published.')
raise PublishMessageError<|docstring|>Publish a response message to a RabbitMQ instance.
:param message: Response message
:param content_type: Pika BasicProperties content_type value
:param headers: Message header properties
:param mandatory: The mandatory flag
:returns: Boolean corresponding to the success of publishing
:rtype: bool<|endoftext|>
|
6120f2bdf9ec3241927e9d3bb4d292177ec34b36cb88976610dc45fe5328fbef
|
def __init__(self, urls, exchange, exchange_type='fanout', **kwargs):
"Create a new instance of the ExchangePublisher class\n\n :param urls: List of RabbitMQ cluster URLs\n :param exchange: Exchange name\n :param exchange_type: Type of exchange to declare\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.exchange_declare method\n\n :returns: Object of type ExchangePublisher\n :rtype: ExchangePublisher\n\n "
self._exchange = exchange
self._exchange_type = exchange_type
super(ExchangePublisher, self).__init__(urls, **kwargs)
|
Create a new instance of the ExchangePublisher class
:param urls: List of RabbitMQ cluster URLs
:param exchange: Exchange name
:param exchange_type: Type of exchange to declare
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/value pairs passed to the arguments
parameter of pika's channel.exchange_declare method
:returns: Object of type ExchangePublisher
:rtype: ExchangePublisher
|
sdc/rabbit/publishers.py
|
__init__
|
ONSdigital/sdc-rabbit-python
| 1
|
python
|
def __init__(self, urls, exchange, exchange_type='fanout', **kwargs):
"Create a new instance of the ExchangePublisher class\n\n :param urls: List of RabbitMQ cluster URLs\n :param exchange: Exchange name\n :param exchange_type: Type of exchange to declare\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.exchange_declare method\n\n :returns: Object of type ExchangePublisher\n :rtype: ExchangePublisher\n\n "
self._exchange = exchange
self._exchange_type = exchange_type
super(ExchangePublisher, self).__init__(urls, **kwargs)
|
def __init__(self, urls, exchange, exchange_type='fanout', **kwargs):
"Create a new instance of the ExchangePublisher class\n\n :param urls: List of RabbitMQ cluster URLs\n :param exchange: Exchange name\n :param exchange_type: Type of exchange to declare\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.exchange_declare method\n\n :returns: Object of type ExchangePublisher\n :rtype: ExchangePublisher\n\n "
self._exchange = exchange
self._exchange_type = exchange_type
super(ExchangePublisher, self).__init__(urls, **kwargs)<|docstring|>Create a new instance of the ExchangePublisher class
:param urls: List of RabbitMQ cluster URLs
:param exchange: Exchange name
:param exchange_type: Type of exchange to declare
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/value pairs passed to the arguments
parameter of pika's channel.exchange_declare method
:returns: Object of type ExchangePublisher
:rtype: ExchangePublisher<|endoftext|>
|
8da3f1ceaaa6d274b6f902cd47609afc7551baf528ae576abc0aa97da3ef4090
|
def __init__(self, urls, queue, **kwargs):
"Create a new instance of the QueuePublisher class\n\n :param urls: List of RabbitMQ cluster URLs.\n :param queue: Queue name\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.queue_declare method\n\n :returns: Object of type QueuePublisher\n :rtype: QueuePublisher\n\n "
self._queue = queue
super(QueuePublisher, self).__init__(urls, **kwargs)
|
Create a new instance of the QueuePublisher class
:param urls: List of RabbitMQ cluster URLs.
:param queue: Queue name
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/value pairs passed to the arguments
parameter of pika's channel.queue_declare method
:returns: Object of type QueuePublisher
:rtype: QueuePublisher
|
sdc/rabbit/publishers.py
|
__init__
|
ONSdigital/sdc-rabbit-python
| 1
|
python
|
def __init__(self, urls, queue, **kwargs):
"Create a new instance of the QueuePublisher class\n\n :param urls: List of RabbitMQ cluster URLs.\n :param queue: Queue name\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.queue_declare method\n\n :returns: Object of type QueuePublisher\n :rtype: QueuePublisher\n\n "
self._queue = queue
super(QueuePublisher, self).__init__(urls, **kwargs)
|
def __init__(self, urls, queue, **kwargs):
"Create a new instance of the QueuePublisher class\n\n :param urls: List of RabbitMQ cluster URLs.\n :param queue: Queue name\n :param confirm_delivery: Delivery confirmations toggle\n :param **kwargs: Custom key/value pairs passed to the arguments\n parameter of pika's channel.queue_declare method\n\n :returns: Object of type QueuePublisher\n :rtype: QueuePublisher\n\n "
self._queue = queue
super(QueuePublisher, self).__init__(urls, **kwargs)<|docstring|>Create a new instance of the QueuePublisher class
:param urls: List of RabbitMQ cluster URLs.
:param queue: Queue name
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/value pairs passed to the arguments
parameter of pika's channel.queue_declare method
:returns: Object of type QueuePublisher
:rtype: QueuePublisher<|endoftext|>
|
1af39f32232a97a40e77340a282e40c931c08598afe78eee25ca92ac7f7eab2b
|
def read(self):
'Returns the value of the pin, float for analogue - the voltage,\n and boolean for digital - True for high and False for low.'
if (not self.is_input):
raise TypeError('Trying to read a non-input pin')
return self._run()
|
Returns the value of the pin, float for analogue - the voltage,
and boolean for digital - True for high and False for low.
|
controllers/ruggeduino.py
|
read
|
simon816/BRK-Student-Robotics-2015
| 0
|
python
|
def read(self):
'Returns the value of the pin, float for analogue - the voltage,\n and boolean for digital - True for high and False for low.'
if (not self.is_input):
raise TypeError('Trying to read a non-input pin')
return self._run()
|
def read(self):
'Returns the value of the pin, float for analogue - the voltage,\n and boolean for digital - True for high and False for low.'
if (not self.is_input):
raise TypeError('Trying to read a non-input pin')
return self._run()<|docstring|>Returns the value of the pin, float for analogue - the voltage,
and boolean for digital - True for high and False for low.<|endoftext|>
|
19bfb3f1e73e0b781b8c49359a091ade024142539f779a4cfd03c9ae1bd77264
|
def write(self, value):
'Write a value to the pin,\n boolean only - True for high and False for low.'
if (not self.is_output):
raise TypeError('Trying to write to a non-output pin')
return self._run(value)
|
Write a value to the pin,
boolean only - True for high and False for low.
|
controllers/ruggeduino.py
|
write
|
simon816/BRK-Student-Robotics-2015
| 0
|
python
|
def write(self, value):
'Write a value to the pin,\n boolean only - True for high and False for low.'
if (not self.is_output):
raise TypeError('Trying to write to a non-output pin')
return self._run(value)
|
def write(self, value):
'Write a value to the pin,\n boolean only - True for high and False for low.'
if (not self.is_output):
raise TypeError('Trying to write to a non-output pin')
return self._run(value)<|docstring|>Write a value to the pin,
boolean only - True for high and False for low.<|endoftext|>
|
ec3c49248e041c841459410a20229d1533ddac519fd3815c64e28ef686f725b8
|
def getxmlfloc():
' Returns the supposed location of the XML file\n '
filepath = path.dirname(path.abspath(__file__))
return path.join(filepath, 'class_list.xml')
|
Returns the supposed location of the XML file
|
tools/docdump/makedocs.py
|
getxmlfloc
|
Acidburn0zzz/godot
| 33
|
python
|
def getxmlfloc():
' \n '
filepath = path.dirname(path.abspath(__file__))
return path.join(filepath, 'class_list.xml')
|
def getxmlfloc():
' \n '
filepath = path.dirname(path.abspath(__file__))
return path.join(filepath, 'class_list.xml')<|docstring|>Returns the supposed location of the XML file<|endoftext|>
|
b4958aa132fe9f69873f4a343cba9ec76a3c8d13b6a652029a08e11a42d6e40d
|
def langavailable():
' Return a list of languages available for translation\n '
filepath = path.join(path.dirname(path.abspath(__file__)), 'locales')
files = listdir(filepath)
choices = [x for x in files]
choices.insert(0, 'none')
return choices
|
Return a list of languages available for translation
|
tools/docdump/makedocs.py
|
langavailable
|
Acidburn0zzz/godot
| 33
|
python
|
def langavailable():
' \n '
filepath = path.join(path.dirname(path.abspath(__file__)), 'locales')
files = listdir(filepath)
choices = [x for x in files]
choices.insert(0, 'none')
return choices
|
def langavailable():
' \n '
filepath = path.join(path.dirname(path.abspath(__file__)), 'locales')
files = listdir(filepath)
choices = [x for x in files]
choices.insert(0, 'none')
return choices<|docstring|>Return a list of languages available for translation<|endoftext|>
|
2bc4e01561b9a0f8387cb9f921c22117db17db0d2207c965c868079ccdfcd40c
|
def tb(string):
' Return a byte representation of a string\n '
return bytes(string, 'UTF-8')
|
Return a byte representation of a string
|
tools/docdump/makedocs.py
|
tb
|
Acidburn0zzz/godot
| 33
|
python
|
def tb(string):
' \n '
return bytes(string, 'UTF-8')
|
def tb(string):
' \n '
return bytes(string, 'UTF-8')<|docstring|>Return a byte representation of a string<|endoftext|>
|
19c38fb21beae8a7e0303e22360420b014c6cf7961c36f63e8b4d22fba2b84d1
|
def sortkey(c):
' Symbols are first, letters second\n '
if ('_' == c.attrib['name'][0]):
return 'A'
else:
return c.attrib['name']
|
Symbols are first, letters second
|
tools/docdump/makedocs.py
|
sortkey
|
Acidburn0zzz/godot
| 33
|
python
|
def sortkey(c):
' \n '
if ('_' == c.attrib['name'][0]):
return 'A'
else:
return c.attrib['name']
|
def sortkey(c):
' \n '
if ('_' == c.attrib['name'][0]):
return 'A'
else:
return c.attrib['name']<|docstring|>Symbols are first, letters second<|endoftext|>
|
84b5efc41d6674d6aab32b3fe03412c87cefa2c70be483ea9d547a2d0e411603
|
def toOP(text):
' Convert commands in text to Open Project commands\n '
groups = re.finditer('\\[html (?P<command>/?\\w+/?)(\\]| |=)?(\\]| |=)?(?P<arg>\\w+)?(\\]| |=)?(?P<value>"[^"]+")?/?\\]', text)
alignstr = ''
for group in groups:
gd = group.groupdict()
if (gd['command'] == 'br/'):
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == 'div'):
if (gd['value'] == '"center"'):
alignstr = '{display:block; margin-left:auto; margin-right:auto;}'
elif (gd['value'] == '"left"'):
alignstr = '<'
elif (gd['value'] == '"right"'):
alignstr = '>'
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == '/div'):
alignstr = ''
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == 'img'):
text = text.replace(group.group(0), '!{align}{src}!'.format(align=alignstr, src=gd['value'].strip('"')), 1)
elif ((gd['command'] == 'b') or (gd['command'] == '/b')):
text = text.replace(group.group(0), '*', 1)
elif ((gd['command'] == 'i') or (gd['command'] == '/i')):
text = text.replace(group.group(0), '_', 1)
elif ((gd['command'] == 'u') or (gd['command'] == '/u')):
text = text.replace(group.group(0), '+', 1)
groups = re.finditer('\\[method ((?P<class>[aA0-zZ9_]+)(?:\\.))?(?P<method>[aA0-zZ9_]+)\\]', text)
for group in groups:
gd = group.groupdict()
if gd['class']:
replacewith = MC_LINK.format(gclass=gd['class'], method=gd['method'], lkclass=gd['class'].lower(), lkmethod=gd['method'].lower())
else:
replacewith = TM_JUMP.format(method=gd['method'], lkmethod=gd['method'].lower())
text = text.replace(group.group(0), replacewith, 1)
groups = re.finditer('\\[(?P<class>[az0-AZ0_]+)\\]', text)
for group in groups:
gd = group.groupdict()
replacewith = C_LINK.format(gclass=gd['class'], lkclass=gd['class'].lower())
text = text.replace(group.group(0), replacewith, 1)
return (text + '\n\n')
|
Convert commands in text to Open Project commands
|
tools/docdump/makedocs.py
|
toOP
|
Acidburn0zzz/godot
| 33
|
python
|
def toOP(text):
' \n '
groups = re.finditer('\\[html (?P<command>/?\\w+/?)(\\]| |=)?(\\]| |=)?(?P<arg>\\w+)?(\\]| |=)?(?P<value>"[^"]+")?/?\\]', text)
alignstr =
for group in groups:
gd = group.groupdict()
if (gd['command'] == 'br/'):
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == 'div'):
if (gd['value'] == '"center"'):
alignstr = '{display:block; margin-left:auto; margin-right:auto;}'
elif (gd['value'] == '"left"'):
alignstr = '<'
elif (gd['value'] == '"right"'):
alignstr = '>'
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == '/div'):
alignstr =
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == 'img'):
text = text.replace(group.group(0), '!{align}{src}!'.format(align=alignstr, src=gd['value'].strip('"')), 1)
elif ((gd['command'] == 'b') or (gd['command'] == '/b')):
text = text.replace(group.group(0), '*', 1)
elif ((gd['command'] == 'i') or (gd['command'] == '/i')):
text = text.replace(group.group(0), '_', 1)
elif ((gd['command'] == 'u') or (gd['command'] == '/u')):
text = text.replace(group.group(0), '+', 1)
groups = re.finditer('\\[method ((?P<class>[aA0-zZ9_]+)(?:\\.))?(?P<method>[aA0-zZ9_]+)\\]', text)
for group in groups:
gd = group.groupdict()
if gd['class']:
replacewith = MC_LINK.format(gclass=gd['class'], method=gd['method'], lkclass=gd['class'].lower(), lkmethod=gd['method'].lower())
else:
replacewith = TM_JUMP.format(method=gd['method'], lkmethod=gd['method'].lower())
text = text.replace(group.group(0), replacewith, 1)
groups = re.finditer('\\[(?P<class>[az0-AZ0_]+)\\]', text)
for group in groups:
gd = group.groupdict()
replacewith = C_LINK.format(gclass=gd['class'], lkclass=gd['class'].lower())
text = text.replace(group.group(0), replacewith, 1)
return (text + '\n\n')
|
def toOP(text):
' \n '
groups = re.finditer('\\[html (?P<command>/?\\w+/?)(\\]| |=)?(\\]| |=)?(?P<arg>\\w+)?(\\]| |=)?(?P<value>"[^"]+")?/?\\]', text)
alignstr =
for group in groups:
gd = group.groupdict()
if (gd['command'] == 'br/'):
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == 'div'):
if (gd['value'] == '"center"'):
alignstr = '{display:block; margin-left:auto; margin-right:auto;}'
elif (gd['value'] == '"left"'):
alignstr = '<'
elif (gd['value'] == '"right"'):
alignstr = '>'
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == '/div'):
alignstr =
text = text.replace(group.group(0), '\n\n', 1)
elif (gd['command'] == 'img'):
text = text.replace(group.group(0), '!{align}{src}!'.format(align=alignstr, src=gd['value'].strip('"')), 1)
elif ((gd['command'] == 'b') or (gd['command'] == '/b')):
text = text.replace(group.group(0), '*', 1)
elif ((gd['command'] == 'i') or (gd['command'] == '/i')):
text = text.replace(group.group(0), '_', 1)
elif ((gd['command'] == 'u') or (gd['command'] == '/u')):
text = text.replace(group.group(0), '+', 1)
groups = re.finditer('\\[method ((?P<class>[aA0-zZ9_]+)(?:\\.))?(?P<method>[aA0-zZ9_]+)\\]', text)
for group in groups:
gd = group.groupdict()
if gd['class']:
replacewith = MC_LINK.format(gclass=gd['class'], method=gd['method'], lkclass=gd['class'].lower(), lkmethod=gd['method'].lower())
else:
replacewith = TM_JUMP.format(method=gd['method'], lkmethod=gd['method'].lower())
text = text.replace(group.group(0), replacewith, 1)
groups = re.finditer('\\[(?P<class>[az0-AZ0_]+)\\]', text)
for group in groups:
gd = group.groupdict()
replacewith = C_LINK.format(gclass=gd['class'], lkclass=gd['class'].lower())
text = text.replace(group.group(0), replacewith, 1)
return (text + '\n\n')<|docstring|>Convert commands in text to Open Project commands<|endoftext|>
|
8a021e029f1b44bededa3c7870ece312b5b46f915a08b7580a2480553cf2401f
|
def mkfn(node, is_signal=False):
' Return a string containing a unsorted item for a function\n '
finalstr = ''
name = node.attrib['name']
rtype = node.find('return')
if rtype:
rtype = rtype.attrib['type']
else:
rtype = 'void'
finalstr += '* '
if (not is_signal):
if (rtype != 'void'):
finalstr += GTC_LINK.format(rtype=rtype, link=rtype.lower())
else:
finalstr += ' void '
if (not is_signal):
finalstr += DFN_JUMP.format(funcname=name, link=name.lower())
else:
finalstr += '*{funcname}* <b>(</b>'.format(funcname=name)
args = []
for arg in sorted(node.iter(tag='argument'), key=(lambda a: int(a.attrib['index']))):
ntype = arg.attrib['type']
nname = arg.attrib['name']
if ('default' in arg.attrib):
args.insert((- 1), M_ARG_DEFAULT.format(gclass=ntype, lkclass=ntype.lower(), name=nname, default=arg.attrib['default']))
else:
args.insert((- 1), M_ARG.format(gclass=ntype, lkclass=ntype.lower(), name=nname))
finalstr += ', '.join(args)
finalstr += ' <b>)</b>'
if ('qualifiers' in node.attrib):
qualifier = node.attrib['qualifiers']
finalstr += (' ' + qualifier)
finalstr += '\n'
return finalstr
|
Return a string containing a unsorted item for a function
|
tools/docdump/makedocs.py
|
mkfn
|
Acidburn0zzz/godot
| 33
|
python
|
def mkfn(node, is_signal=False):
' \n '
finalstr =
name = node.attrib['name']
rtype = node.find('return')
if rtype:
rtype = rtype.attrib['type']
else:
rtype = 'void'
finalstr += '* '
if (not is_signal):
if (rtype != 'void'):
finalstr += GTC_LINK.format(rtype=rtype, link=rtype.lower())
else:
finalstr += ' void '
if (not is_signal):
finalstr += DFN_JUMP.format(funcname=name, link=name.lower())
else:
finalstr += '*{funcname}* <b>(</b>'.format(funcname=name)
args = []
for arg in sorted(node.iter(tag='argument'), key=(lambda a: int(a.attrib['index']))):
ntype = arg.attrib['type']
nname = arg.attrib['name']
if ('default' in arg.attrib):
args.insert((- 1), M_ARG_DEFAULT.format(gclass=ntype, lkclass=ntype.lower(), name=nname, default=arg.attrib['default']))
else:
args.insert((- 1), M_ARG.format(gclass=ntype, lkclass=ntype.lower(), name=nname))
finalstr += ', '.join(args)
finalstr += ' <b>)</b>'
if ('qualifiers' in node.attrib):
qualifier = node.attrib['qualifiers']
finalstr += (' ' + qualifier)
finalstr += '\n'
return finalstr
|
def mkfn(node, is_signal=False):
' \n '
finalstr =
name = node.attrib['name']
rtype = node.find('return')
if rtype:
rtype = rtype.attrib['type']
else:
rtype = 'void'
finalstr += '* '
if (not is_signal):
if (rtype != 'void'):
finalstr += GTC_LINK.format(rtype=rtype, link=rtype.lower())
else:
finalstr += ' void '
if (not is_signal):
finalstr += DFN_JUMP.format(funcname=name, link=name.lower())
else:
finalstr += '*{funcname}* <b>(</b>'.format(funcname=name)
args = []
for arg in sorted(node.iter(tag='argument'), key=(lambda a: int(a.attrib['index']))):
ntype = arg.attrib['type']
nname = arg.attrib['name']
if ('default' in arg.attrib):
args.insert((- 1), M_ARG_DEFAULT.format(gclass=ntype, lkclass=ntype.lower(), name=nname, default=arg.attrib['default']))
else:
args.insert((- 1), M_ARG.format(gclass=ntype, lkclass=ntype.lower(), name=nname))
finalstr += ', '.join(args)
finalstr += ' <b>)</b>'
if ('qualifiers' in node.attrib):
qualifier = node.attrib['qualifiers']
finalstr += (' ' + qualifier)
finalstr += '\n'
return finalstr<|docstring|>Return a string containing a unsorted item for a function<|endoftext|>
|
e81b05ad42bf03dfea99940afd5988fcdf6c7a8bae5bc2cee5d30101ab91bcac
|
@contextlib.contextmanager
def working_directory(path):
"Changes working directory and returns to previous on exit.\n\n Exceptions:\n FileNotFoundError when could not change to directory provided.\n\n Args:\n path (str): Directory to change\n\n Returns:\n str Path to the changed directory\n\n Example:\n >>> import os\n >>> from tempfile import gettempdir\n >>> from bdc_core.decorators.utils import working_directory\n ...\n ...\n >>> TEMP_DIR = gettempdir()\n >>> @working_directory(TEMP_DIR)\n ... def create_file(filename):\n ... # Create file in Temporary folder\n ... print('Current dir: {}'.format(os.getcwd()))\n ... with open(filename, 'w') as f:\n ... f.write('Hello World')\n "
owd = os.getcwd()
logger.debug('Changing working dir from %s to %s', owd, path)
try:
os.chdir(path)
(yield path)
finally:
logger.debug('Back to working dir %s', owd)
os.chdir(owd)
|
Changes working directory and returns to previous on exit.
Exceptions:
FileNotFoundError when could not change to directory provided.
Args:
path (str): Directory to change
Returns:
str Path to the changed directory
Example:
>>> import os
>>> from tempfile import gettempdir
>>> from bdc_core.decorators.utils import working_directory
...
...
>>> TEMP_DIR = gettempdir()
>>> @working_directory(TEMP_DIR)
... def create_file(filename):
... # Create file in Temporary folder
... print('Current dir: {}'.format(os.getcwd()))
... with open(filename, 'w') as f:
... f.write('Hello World')
|
bdc_core/decorators/utils.py
|
working_directory
|
brazil-data-cube/bdc-core
| 1
|
python
|
@contextlib.contextmanager
def working_directory(path):
"Changes working directory and returns to previous on exit.\n\n Exceptions:\n FileNotFoundError when could not change to directory provided.\n\n Args:\n path (str): Directory to change\n\n Returns:\n str Path to the changed directory\n\n Example:\n >>> import os\n >>> from tempfile import gettempdir\n >>> from bdc_core.decorators.utils import working_directory\n ...\n ...\n >>> TEMP_DIR = gettempdir()\n >>> @working_directory(TEMP_DIR)\n ... def create_file(filename):\n ... # Create file in Temporary folder\n ... print('Current dir: {}'.format(os.getcwd()))\n ... with open(filename, 'w') as f:\n ... f.write('Hello World')\n "
owd = os.getcwd()
logger.debug('Changing working dir from %s to %s', owd, path)
try:
os.chdir(path)
(yield path)
finally:
logger.debug('Back to working dir %s', owd)
os.chdir(owd)
|
@contextlib.contextmanager
def working_directory(path):
"Changes working directory and returns to previous on exit.\n\n Exceptions:\n FileNotFoundError when could not change to directory provided.\n\n Args:\n path (str): Directory to change\n\n Returns:\n str Path to the changed directory\n\n Example:\n >>> import os\n >>> from tempfile import gettempdir\n >>> from bdc_core.decorators.utils import working_directory\n ...\n ...\n >>> TEMP_DIR = gettempdir()\n >>> @working_directory(TEMP_DIR)\n ... def create_file(filename):\n ... # Create file in Temporary folder\n ... print('Current dir: {}'.format(os.getcwd()))\n ... with open(filename, 'w') as f:\n ... f.write('Hello World')\n "
owd = os.getcwd()
logger.debug('Changing working dir from %s to %s', owd, path)
try:
os.chdir(path)
(yield path)
finally:
logger.debug('Back to working dir %s', owd)
os.chdir(owd)<|docstring|>Changes working directory and returns to previous on exit.
Exceptions:
FileNotFoundError when could not change to directory provided.
Args:
path (str): Directory to change
Returns:
str Path to the changed directory
Example:
>>> import os
>>> from tempfile import gettempdir
>>> from bdc_core.decorators.utils import working_directory
...
...
>>> TEMP_DIR = gettempdir()
>>> @working_directory(TEMP_DIR)
... def create_file(filename):
... # Create file in Temporary folder
... print('Current dir: {}'.format(os.getcwd()))
... with open(filename, 'w') as f:
... f.write('Hello World')<|endoftext|>
|
f8abce1dd606c138b9fd173b0cbd47e5c109d72582a1c57895ac3fc0fe878266
|
def func(x):
'This is the function that we want to integrate'
return np.sin(x)
|
This is the function that we want to integrate
|
RS_scikitlearn.py
|
func
|
BrooksIan/EstimatingPi
| 0
|
python
|
def func(x):
return np.sin(x)
|
def func(x):
return np.sin(x)<|docstring|>This is the function that we want to integrate<|endoftext|>
|
7e4ed40d1b5cd8a1ee847e0ec843675578e551ab9f7c7774ce176f8a5a582fda
|
def generate_ae(model_configs, trans_configs, data, labels, attack_configs, save=False, output_dir=None):
'\n Generate adversarial examples\n :param model: WeakDefense. The targeted model.\n :param data: array. The benign samples to generate adversarial for.\n :param labels: array or list. The true labels.\n :param attack_configs: dictionary. Attacks and corresponding settings.\n :param save: boolean. True, if save the adversarial examples.\n :param output_dir: str or path. Location to save the adversarial examples.\n It cannot be None when save is True.\n :return:\n '
cnn = os.path.join(model_configs.get('dir'), model_configs.get('um_file'))
um = load_lenet(file=cnn, wrap=True)
baseline = load_lenet(file=model_configs.get('pgd_trained'), trans_configs=None, use_logits=False, wrap=False)
(pool, _) = load_pool(trans_configs=trans_configs, model_configs=model_configs, active_list=True, wrap=True)
wds = list(pool.values())
ens = Ensemble(classifiers=wds, strategy=ENSEMBLE_STRATEGY.AVEP.value)
(img_rows, img_cols) = (data.shape[1], data.shape[2])
num_attacks = attack_configs.get('num_attacks')
print('> Getting subsamples of bs for AE generation')
(data, labels) = subsampling(data, labels, 10, ratio=0.2, filepath='samples/')
data_loader = (data, labels)
if (len(labels.shape) > 1):
labels = np.asarray([np.argmax(p) for p in labels])
attack_dict = attack_configs.get('attacks')
for attack_type in attack_dict:
attacks = attack_dict[attack_type]
if (not os.path.isdir(os.path.join(output_dir, attack_type))):
os.mkdir(os.path.join(output_dir, attack_type))
type_results = {}
print('> Generating AEs for {}'.format(attack_type))
for attack in attacks:
results = {}
data_adv = generate(model=um, data_loader=data_loader, a_type=attack_type, attack_args=attack)
print('> Getting predictions from Undefended Model')
pred_um = um.predict(data_adv)
pred_um = np.asarray([np.argmax(p) for p in pred_um])
err_um = error_rate(y_pred=pred_um, y_true=labels)
results['UM'] = err_um
print('>>> UM error rate:', err_um)
print('> Getting predictions from Ensemble')
pred_ens = ens.predict(data_adv)
pred_ens = np.asarray([np.argmax(p) for p in pred_ens])
err_ens = error_rate(y_pred=pred_ens, y_true=labels)
results['Ensemble'] = err_ens
print('> Ensemble error rate:', err_ens)
pred_bl = baseline.predict(data_adv)
pred_bl = np.asarray([np.argmax(p) for p in pred_bl])
err_bl = error_rate(y_pred=pred_bl, y_true=labels)
print('> Baseline error rate:', err_bl)
results['Baseline'] = err_bl
type_results[attack.get('description')] = results
if save:
if (output_dir is None):
raise ValueError('Cannot save images to a none path.')
img = data_adv[0].reshape((img_rows, img_cols))
plt.imshow(img, cmap='gray')
title = '{}'.format(attack.get('description'))
plt.title(title)
plt.savefig(os.path.join(output_dir, '{}/{}.png'.format(attack_type, attack.get('description'))), dpi=300, bbox_inches='tight')
plt.show()
plt.close()
file = os.path.join(output_dir, '{}/{}.npy'.format(attack_type, attack.get('description')))
print('Save the adversarial examples to file [{}].'.format(file))
np.save(file, data_adv)
if save:
if (output_dir is None):
raise ValueError('Cannot save images to a none path.')
with open(os.path.join(output_dir, '{}/fgsm_results.json'.format(attack_type)), 'w') as f:
json.dump(type_results, f)
|
Generate adversarial examples
:param model: WeakDefense. The targeted model.
:param data: array. The benign samples to generate adversarial for.
:param labels: array or list. The true labels.
:param attack_configs: dictionary. Attacks and corresponding settings.
:param save: boolean. True, if save the adversarial examples.
:param output_dir: str or path. Location to save the adversarial examples.
It cannot be None when save is True.
:return:
|
src/generate_ae_zk/craft_ae_zk.py
|
generate_ae
|
MaxCorbel/project-athena
| 0
|
python
|
def generate_ae(model_configs, trans_configs, data, labels, attack_configs, save=False, output_dir=None):
'\n Generate adversarial examples\n :param model: WeakDefense. The targeted model.\n :param data: array. The benign samples to generate adversarial for.\n :param labels: array or list. The true labels.\n :param attack_configs: dictionary. Attacks and corresponding settings.\n :param save: boolean. True, if save the adversarial examples.\n :param output_dir: str or path. Location to save the adversarial examples.\n It cannot be None when save is True.\n :return:\n '
cnn = os.path.join(model_configs.get('dir'), model_configs.get('um_file'))
um = load_lenet(file=cnn, wrap=True)
baseline = load_lenet(file=model_configs.get('pgd_trained'), trans_configs=None, use_logits=False, wrap=False)
(pool, _) = load_pool(trans_configs=trans_configs, model_configs=model_configs, active_list=True, wrap=True)
wds = list(pool.values())
ens = Ensemble(classifiers=wds, strategy=ENSEMBLE_STRATEGY.AVEP.value)
(img_rows, img_cols) = (data.shape[1], data.shape[2])
num_attacks = attack_configs.get('num_attacks')
print('> Getting subsamples of bs for AE generation')
(data, labels) = subsampling(data, labels, 10, ratio=0.2, filepath='samples/')
data_loader = (data, labels)
if (len(labels.shape) > 1):
labels = np.asarray([np.argmax(p) for p in labels])
attack_dict = attack_configs.get('attacks')
for attack_type in attack_dict:
attacks = attack_dict[attack_type]
if (not os.path.isdir(os.path.join(output_dir, attack_type))):
os.mkdir(os.path.join(output_dir, attack_type))
type_results = {}
print('> Generating AEs for {}'.format(attack_type))
for attack in attacks:
results = {}
data_adv = generate(model=um, data_loader=data_loader, a_type=attack_type, attack_args=attack)
print('> Getting predictions from Undefended Model')
pred_um = um.predict(data_adv)
pred_um = np.asarray([np.argmax(p) for p in pred_um])
err_um = error_rate(y_pred=pred_um, y_true=labels)
results['UM'] = err_um
print('>>> UM error rate:', err_um)
print('> Getting predictions from Ensemble')
pred_ens = ens.predict(data_adv)
pred_ens = np.asarray([np.argmax(p) for p in pred_ens])
err_ens = error_rate(y_pred=pred_ens, y_true=labels)
results['Ensemble'] = err_ens
print('> Ensemble error rate:', err_ens)
pred_bl = baseline.predict(data_adv)
pred_bl = np.asarray([np.argmax(p) for p in pred_bl])
err_bl = error_rate(y_pred=pred_bl, y_true=labels)
print('> Baseline error rate:', err_bl)
results['Baseline'] = err_bl
type_results[attack.get('description')] = results
if save:
if (output_dir is None):
raise ValueError('Cannot save images to a none path.')
img = data_adv[0].reshape((img_rows, img_cols))
plt.imshow(img, cmap='gray')
title = '{}'.format(attack.get('description'))
plt.title(title)
plt.savefig(os.path.join(output_dir, '{}/{}.png'.format(attack_type, attack.get('description'))), dpi=300, bbox_inches='tight')
plt.show()
plt.close()
file = os.path.join(output_dir, '{}/{}.npy'.format(attack_type, attack.get('description')))
print('Save the adversarial examples to file [{}].'.format(file))
np.save(file, data_adv)
if save:
if (output_dir is None):
raise ValueError('Cannot save images to a none path.')
with open(os.path.join(output_dir, '{}/fgsm_results.json'.format(attack_type)), 'w') as f:
json.dump(type_results, f)
|
def generate_ae(model_configs, trans_configs, data, labels, attack_configs, save=False, output_dir=None):
'\n Generate adversarial examples\n :param model: WeakDefense. The targeted model.\n :param data: array. The benign samples to generate adversarial for.\n :param labels: array or list. The true labels.\n :param attack_configs: dictionary. Attacks and corresponding settings.\n :param save: boolean. True, if save the adversarial examples.\n :param output_dir: str or path. Location to save the adversarial examples.\n It cannot be None when save is True.\n :return:\n '
cnn = os.path.join(model_configs.get('dir'), model_configs.get('um_file'))
um = load_lenet(file=cnn, wrap=True)
baseline = load_lenet(file=model_configs.get('pgd_trained'), trans_configs=None, use_logits=False, wrap=False)
(pool, _) = load_pool(trans_configs=trans_configs, model_configs=model_configs, active_list=True, wrap=True)
wds = list(pool.values())
ens = Ensemble(classifiers=wds, strategy=ENSEMBLE_STRATEGY.AVEP.value)
(img_rows, img_cols) = (data.shape[1], data.shape[2])
num_attacks = attack_configs.get('num_attacks')
print('> Getting subsamples of bs for AE generation')
(data, labels) = subsampling(data, labels, 10, ratio=0.2, filepath='samples/')
data_loader = (data, labels)
if (len(labels.shape) > 1):
labels = np.asarray([np.argmax(p) for p in labels])
attack_dict = attack_configs.get('attacks')
for attack_type in attack_dict:
attacks = attack_dict[attack_type]
if (not os.path.isdir(os.path.join(output_dir, attack_type))):
os.mkdir(os.path.join(output_dir, attack_type))
type_results = {}
print('> Generating AEs for {}'.format(attack_type))
for attack in attacks:
results = {}
data_adv = generate(model=um, data_loader=data_loader, a_type=attack_type, attack_args=attack)
print('> Getting predictions from Undefended Model')
pred_um = um.predict(data_adv)
pred_um = np.asarray([np.argmax(p) for p in pred_um])
err_um = error_rate(y_pred=pred_um, y_true=labels)
results['UM'] = err_um
print('>>> UM error rate:', err_um)
print('> Getting predictions from Ensemble')
pred_ens = ens.predict(data_adv)
pred_ens = np.asarray([np.argmax(p) for p in pred_ens])
err_ens = error_rate(y_pred=pred_ens, y_true=labels)
results['Ensemble'] = err_ens
print('> Ensemble error rate:', err_ens)
pred_bl = baseline.predict(data_adv)
pred_bl = np.asarray([np.argmax(p) for p in pred_bl])
err_bl = error_rate(y_pred=pred_bl, y_true=labels)
print('> Baseline error rate:', err_bl)
results['Baseline'] = err_bl
type_results[attack.get('description')] = results
if save:
if (output_dir is None):
raise ValueError('Cannot save images to a none path.')
img = data_adv[0].reshape((img_rows, img_cols))
plt.imshow(img, cmap='gray')
title = '{}'.format(attack.get('description'))
plt.title(title)
plt.savefig(os.path.join(output_dir, '{}/{}.png'.format(attack_type, attack.get('description'))), dpi=300, bbox_inches='tight')
plt.show()
plt.close()
file = os.path.join(output_dir, '{}/{}.npy'.format(attack_type, attack.get('description')))
print('Save the adversarial examples to file [{}].'.format(file))
np.save(file, data_adv)
if save:
if (output_dir is None):
raise ValueError('Cannot save images to a none path.')
with open(os.path.join(output_dir, '{}/fgsm_results.json'.format(attack_type)), 'w') as f:
json.dump(type_results, f)<|docstring|>Generate adversarial examples
:param model: WeakDefense. The targeted model.
:param data: array. The benign samples to generate adversarial for.
:param labels: array or list. The true labels.
:param attack_configs: dictionary. Attacks and corresponding settings.
:param save: boolean. True, if save the adversarial examples.
:param output_dir: str or path. Location to save the adversarial examples.
It cannot be None when save is True.
:return:<|endoftext|>
|
327318e9dc38de41709eef0321cfea52df4240a5d426b0b0eaf72fc5cd66a763
|
def generate_response(response):
'\n response of server always contains "\r\n", need to remove it\n :param response: response of server\n :return:\n '
if (response is not None):
resp = response.split('\r\n')
resp = resp[0]
return resp
else:
raise Exception('response of server is none, please confirm it.')
|
response of server always contains "
", need to remove it
:param response: response of server
:return:
|
util.py
|
generate_response
|
SmirkCao/obscmd
| 11
|
python
|
def generate_response(response):
'\n response of server always contains "\r\n", need to remove it\n :param response: response of server\n :return:\n '
if (response is not None):
resp = response.split('\r\n')
resp = resp[0]
return resp
else:
raise Exception('response of server is none, please confirm it.')
|
def generate_response(response):
'\n response of server always contains "\r\n", need to remove it\n :param response: response of server\n :return:\n '
if (response is not None):
resp = response.split('\r\n')
resp = resp[0]
return resp
else:
raise Exception('response of server is none, please confirm it.')<|docstring|>response of server always contains "
", need to remove it
:param response: response of server
:return:<|endoftext|>
|
f13b5e62f9e33e7718bc5ca9d52d7b2daf17651ece68e47e575268c6f660120c
|
def __init__(self, *, id_: Optional[FhirString]=None, extension: Optional[FhirList[ExtensionBase]]=None, modifierExtension: Optional[FhirList[ExtensionBase]]=None, parameterName: Optional[FhirList[FhirString]]=None, comment: Optional[FhirString]=None) -> None:
"\n A formal computable definition of an operation (on the RESTful interface) or a\n named query (using the search interaction).\n\n :param id_: None\n :param extension: May be used to represent additional information that is not part of the basic\n definition of the element. To make the use of extensions safe and manageable,\n there is a strict set of governance applied to the definition and use of\n extensions. Though any implementer can define an extension, there is a set of\n requirements that SHALL be met as part of the definition of the extension.\n :param modifierExtension: May be used to represent additional information that is not part of the basic\n definition of the element and that modifies the understanding of the element\n in which it is contained and/or the understanding of the containing element's\n descendants. Usually modifier elements provide negation or qualification. To\n make the use of extensions safe and manageable, there is a strict set of\n governance applied to the definition and use of extensions. Though any\n implementer can define an extension, there is a set of requirements that SHALL\n be met as part of the definition of the extension. Applications processing a\n resource are required to check for modifier extensions.\n\n Modifier extensions SHALL NOT change the meaning of any elements on Resource\n or DomainResource (including cannot change the meaning of modifierExtension\n itself).\n :param parameterName: Name of parameter to include in overload.\n :param comment: Comments to go on overload.\n "
super().__init__(id_=id_, extension=extension, modifierExtension=modifierExtension, parameterName=parameterName, comment=comment)
|
A formal computable definition of an operation (on the RESTful interface) or a
named query (using the search interaction).
:param id_: None
:param extension: May be used to represent additional information that is not part of the basic
definition of the element. To make the use of extensions safe and manageable,
there is a strict set of governance applied to the definition and use of
extensions. Though any implementer can define an extension, there is a set of
requirements that SHALL be met as part of the definition of the extension.
:param modifierExtension: May be used to represent additional information that is not part of the basic
definition of the element and that modifies the understanding of the element
in which it is contained and/or the understanding of the containing element's
descendants. Usually modifier elements provide negation or qualification. To
make the use of extensions safe and manageable, there is a strict set of
governance applied to the definition and use of extensions. Though any
implementer can define an extension, there is a set of requirements that SHALL
be met as part of the definition of the extension. Applications processing a
resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource
or DomainResource (including cannot change the meaning of modifierExtension
itself).
:param parameterName: Name of parameter to include in overload.
:param comment: Comments to go on overload.
|
spark_auto_mapper_fhir/backbone_elements/operation_definition_overload.py
|
__init__
|
imranq2/SparkAutoMapper.FHIR
| 1
|
python
|
def __init__(self, *, id_: Optional[FhirString]=None, extension: Optional[FhirList[ExtensionBase]]=None, modifierExtension: Optional[FhirList[ExtensionBase]]=None, parameterName: Optional[FhirList[FhirString]]=None, comment: Optional[FhirString]=None) -> None:
"\n A formal computable definition of an operation (on the RESTful interface) or a\n named query (using the search interaction).\n\n :param id_: None\n :param extension: May be used to represent additional information that is not part of the basic\n definition of the element. To make the use of extensions safe and manageable,\n there is a strict set of governance applied to the definition and use of\n extensions. Though any implementer can define an extension, there is a set of\n requirements that SHALL be met as part of the definition of the extension.\n :param modifierExtension: May be used to represent additional information that is not part of the basic\n definition of the element and that modifies the understanding of the element\n in which it is contained and/or the understanding of the containing element's\n descendants. Usually modifier elements provide negation or qualification. To\n make the use of extensions safe and manageable, there is a strict set of\n governance applied to the definition and use of extensions. Though any\n implementer can define an extension, there is a set of requirements that SHALL\n be met as part of the definition of the extension. Applications processing a\n resource are required to check for modifier extensions.\n\n Modifier extensions SHALL NOT change the meaning of any elements on Resource\n or DomainResource (including cannot change the meaning of modifierExtension\n itself).\n :param parameterName: Name of parameter to include in overload.\n :param comment: Comments to go on overload.\n "
super().__init__(id_=id_, extension=extension, modifierExtension=modifierExtension, parameterName=parameterName, comment=comment)
|
def __init__(self, *, id_: Optional[FhirString]=None, extension: Optional[FhirList[ExtensionBase]]=None, modifierExtension: Optional[FhirList[ExtensionBase]]=None, parameterName: Optional[FhirList[FhirString]]=None, comment: Optional[FhirString]=None) -> None:
"\n A formal computable definition of an operation (on the RESTful interface) or a\n named query (using the search interaction).\n\n :param id_: None\n :param extension: May be used to represent additional information that is not part of the basic\n definition of the element. To make the use of extensions safe and manageable,\n there is a strict set of governance applied to the definition and use of\n extensions. Though any implementer can define an extension, there is a set of\n requirements that SHALL be met as part of the definition of the extension.\n :param modifierExtension: May be used to represent additional information that is not part of the basic\n definition of the element and that modifies the understanding of the element\n in which it is contained and/or the understanding of the containing element's\n descendants. Usually modifier elements provide negation or qualification. To\n make the use of extensions safe and manageable, there is a strict set of\n governance applied to the definition and use of extensions. Though any\n implementer can define an extension, there is a set of requirements that SHALL\n be met as part of the definition of the extension. Applications processing a\n resource are required to check for modifier extensions.\n\n Modifier extensions SHALL NOT change the meaning of any elements on Resource\n or DomainResource (including cannot change the meaning of modifierExtension\n itself).\n :param parameterName: Name of parameter to include in overload.\n :param comment: Comments to go on overload.\n "
super().__init__(id_=id_, extension=extension, modifierExtension=modifierExtension, parameterName=parameterName, comment=comment)<|docstring|>A formal computable definition of an operation (on the RESTful interface) or a
named query (using the search interaction).
:param id_: None
:param extension: May be used to represent additional information that is not part of the basic
definition of the element. To make the use of extensions safe and manageable,
there is a strict set of governance applied to the definition and use of
extensions. Though any implementer can define an extension, there is a set of
requirements that SHALL be met as part of the definition of the extension.
:param modifierExtension: May be used to represent additional information that is not part of the basic
definition of the element and that modifies the understanding of the element
in which it is contained and/or the understanding of the containing element's
descendants. Usually modifier elements provide negation or qualification. To
make the use of extensions safe and manageable, there is a strict set of
governance applied to the definition and use of extensions. Though any
implementer can define an extension, there is a set of requirements that SHALL
be met as part of the definition of the extension. Applications processing a
resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource
or DomainResource (including cannot change the meaning of modifierExtension
itself).
:param parameterName: Name of parameter to include in overload.
:param comment: Comments to go on overload.<|endoftext|>
|
28120204f7a5efd00a5900000a50a690bab1c547f1a88f41b8f8a682f74b3abd
|
def beer_lambert_law(raw, ppf=0.1):
'Convert NIRS optical density data to haemoglobin concentration.\n\n Parameters\n ----------\n raw : instance of Raw\n The optical density data.\n ppf : float\n The partial pathlength factor.\n\n Returns\n -------\n raw : instance of Raw\n The modified raw instance.\n '
raw = raw.copy().load_data()
_validate_type(raw, BaseRaw, 'raw')
freqs = np.unique(_channel_frequencies(raw))
picks = _check_channels_ordered(raw, freqs)
abs_coef = _load_absorption(freqs)
distances = source_detector_distances(raw.info)
for ii in picks[::2]:
EL = ((abs_coef * distances[ii]) * ppf)
iEL = linalg.pinv(EL)
raw._data[[ii, (ii + 1)]] = ((raw._data[[ii, (ii + 1)]].T @ iEL.T).T * 0.001)
coil_dict = dict(hbo=FIFF.FIFFV_COIL_FNIRS_HBO, hbr=FIFF.FIFFV_COIL_FNIRS_HBR)
for (ki, kind) in enumerate(('hbo', 'hbr')):
ch = raw.info['chs'][(ii + ki)]
ch.update(coil_type=coil_dict[kind], unit=FIFF.FIFF_UNIT_MOL)
raw.rename_channels({ch['ch_name']: ('%s %s' % (ch['ch_name'][:(- 4)], kind))})
return raw
|
Convert NIRS optical density data to haemoglobin concentration.
Parameters
----------
raw : instance of Raw
The optical density data.
ppf : float
The partial pathlength factor.
Returns
-------
raw : instance of Raw
The modified raw instance.
|
mne/preprocessing/nirs/_beer_lambert_law.py
|
beer_lambert_law
|
hardik-prajapati/mne-python
| 1
|
python
|
def beer_lambert_law(raw, ppf=0.1):
'Convert NIRS optical density data to haemoglobin concentration.\n\n Parameters\n ----------\n raw : instance of Raw\n The optical density data.\n ppf : float\n The partial pathlength factor.\n\n Returns\n -------\n raw : instance of Raw\n The modified raw instance.\n '
raw = raw.copy().load_data()
_validate_type(raw, BaseRaw, 'raw')
freqs = np.unique(_channel_frequencies(raw))
picks = _check_channels_ordered(raw, freqs)
abs_coef = _load_absorption(freqs)
distances = source_detector_distances(raw.info)
for ii in picks[::2]:
EL = ((abs_coef * distances[ii]) * ppf)
iEL = linalg.pinv(EL)
raw._data[[ii, (ii + 1)]] = ((raw._data[[ii, (ii + 1)]].T @ iEL.T).T * 0.001)
coil_dict = dict(hbo=FIFF.FIFFV_COIL_FNIRS_HBO, hbr=FIFF.FIFFV_COIL_FNIRS_HBR)
for (ki, kind) in enumerate(('hbo', 'hbr')):
ch = raw.info['chs'][(ii + ki)]
ch.update(coil_type=coil_dict[kind], unit=FIFF.FIFF_UNIT_MOL)
raw.rename_channels({ch['ch_name']: ('%s %s' % (ch['ch_name'][:(- 4)], kind))})
return raw
|
def beer_lambert_law(raw, ppf=0.1):
'Convert NIRS optical density data to haemoglobin concentration.\n\n Parameters\n ----------\n raw : instance of Raw\n The optical density data.\n ppf : float\n The partial pathlength factor.\n\n Returns\n -------\n raw : instance of Raw\n The modified raw instance.\n '
raw = raw.copy().load_data()
_validate_type(raw, BaseRaw, 'raw')
freqs = np.unique(_channel_frequencies(raw))
picks = _check_channels_ordered(raw, freqs)
abs_coef = _load_absorption(freqs)
distances = source_detector_distances(raw.info)
for ii in picks[::2]:
EL = ((abs_coef * distances[ii]) * ppf)
iEL = linalg.pinv(EL)
raw._data[[ii, (ii + 1)]] = ((raw._data[[ii, (ii + 1)]].T @ iEL.T).T * 0.001)
coil_dict = dict(hbo=FIFF.FIFFV_COIL_FNIRS_HBO, hbr=FIFF.FIFFV_COIL_FNIRS_HBR)
for (ki, kind) in enumerate(('hbo', 'hbr')):
ch = raw.info['chs'][(ii + ki)]
ch.update(coil_type=coil_dict[kind], unit=FIFF.FIFF_UNIT_MOL)
raw.rename_channels({ch['ch_name']: ('%s %s' % (ch['ch_name'][:(- 4)], kind))})
return raw<|docstring|>Convert NIRS optical density data to haemoglobin concentration.
Parameters
----------
raw : instance of Raw
The optical density data.
ppf : float
The partial pathlength factor.
Returns
-------
raw : instance of Raw
The modified raw instance.<|endoftext|>
|
f67b5a00cd41f4d47108ff99ae1a7be072f8d4591aa2bce129fba9aa51dee0cf
|
def _channel_frequencies(raw):
'Return the light frequency for each channel.'
picks = _picks_to_idx(raw.info, 'fnirs_od')
freqs = np.empty(picks.size, int)
for ii in picks:
freqs[ii] = raw.info['chs'][ii]['loc'][9]
return freqs
|
Return the light frequency for each channel.
|
mne/preprocessing/nirs/_beer_lambert_law.py
|
_channel_frequencies
|
hardik-prajapati/mne-python
| 1
|
python
|
def _channel_frequencies(raw):
picks = _picks_to_idx(raw.info, 'fnirs_od')
freqs = np.empty(picks.size, int)
for ii in picks:
freqs[ii] = raw.info['chs'][ii]['loc'][9]
return freqs
|
def _channel_frequencies(raw):
picks = _picks_to_idx(raw.info, 'fnirs_od')
freqs = np.empty(picks.size, int)
for ii in picks:
freqs[ii] = raw.info['chs'][ii]['loc'][9]
return freqs<|docstring|>Return the light frequency for each channel.<|endoftext|>
|
631b39abf723921956ef091923f5f05ec46ee5953fbe2cfed0e7d29ad6d05f30
|
def _check_channels_ordered(raw, freqs):
'Check channels followed expected fNIRS format.'
picks = _picks_to_idx(raw.info, 'fnirs_od')
for ii in picks[::2]:
ch1_name_info = re.match('S(\\d+)_D(\\d+) (\\d+)', raw.info['chs'][ii]['ch_name'])
ch2_name_info = re.match('S(\\d+)_D(\\d+) (\\d+)', raw.info['chs'][(ii + 1)]['ch_name'])
if ((ch1_name_info.groups()[0] != ch2_name_info.groups()[0]) or (ch1_name_info.groups()[1] != ch2_name_info.groups()[1]) or (int(ch1_name_info.groups()[2]) != freqs[0]) or (int(ch2_name_info.groups()[2]) != freqs[1])):
raise RuntimeError('NIRS channels not ordered correctly')
return picks
|
Check channels followed expected fNIRS format.
|
mne/preprocessing/nirs/_beer_lambert_law.py
|
_check_channels_ordered
|
hardik-prajapati/mne-python
| 1
|
python
|
def _check_channels_ordered(raw, freqs):
picks = _picks_to_idx(raw.info, 'fnirs_od')
for ii in picks[::2]:
ch1_name_info = re.match('S(\\d+)_D(\\d+) (\\d+)', raw.info['chs'][ii]['ch_name'])
ch2_name_info = re.match('S(\\d+)_D(\\d+) (\\d+)', raw.info['chs'][(ii + 1)]['ch_name'])
if ((ch1_name_info.groups()[0] != ch2_name_info.groups()[0]) or (ch1_name_info.groups()[1] != ch2_name_info.groups()[1]) or (int(ch1_name_info.groups()[2]) != freqs[0]) or (int(ch2_name_info.groups()[2]) != freqs[1])):
raise RuntimeError('NIRS channels not ordered correctly')
return picks
|
def _check_channels_ordered(raw, freqs):
picks = _picks_to_idx(raw.info, 'fnirs_od')
for ii in picks[::2]:
ch1_name_info = re.match('S(\\d+)_D(\\d+) (\\d+)', raw.info['chs'][ii]['ch_name'])
ch2_name_info = re.match('S(\\d+)_D(\\d+) (\\d+)', raw.info['chs'][(ii + 1)]['ch_name'])
if ((ch1_name_info.groups()[0] != ch2_name_info.groups()[0]) or (ch1_name_info.groups()[1] != ch2_name_info.groups()[1]) or (int(ch1_name_info.groups()[2]) != freqs[0]) or (int(ch2_name_info.groups()[2]) != freqs[1])):
raise RuntimeError('NIRS channels not ordered correctly')
return picks<|docstring|>Check channels followed expected fNIRS format.<|endoftext|>
|
c3cf089a6f501e1909eda1945815456c9461bbab39bc1b2fcd565ad8c6577c48
|
def _load_absorption(freqs):
'Load molar extinction coefficients.'
from scipy.io import loadmat
from scipy.interpolate import interp1d
extinction_fname = op.join(op.dirname(__file__), '..', '..', 'data', 'extinction_coef.mat')
a = loadmat(extinction_fname)['extinct_coef']
interp_hbo = interp1d(a[(:, 0)], a[(:, 1)], kind='linear')
interp_hb = interp1d(a[(:, 0)], a[(:, 2)], kind='linear')
ext_coef = np.array([[interp_hbo(freqs[0]), interp_hb(freqs[0])], [interp_hbo(freqs[1]), interp_hb(freqs[1])]])
abs_coef = (ext_coef * 0.2303)
return abs_coef
|
Load molar extinction coefficients.
|
mne/preprocessing/nirs/_beer_lambert_law.py
|
_load_absorption
|
hardik-prajapati/mne-python
| 1
|
python
|
def _load_absorption(freqs):
from scipy.io import loadmat
from scipy.interpolate import interp1d
extinction_fname = op.join(op.dirname(__file__), '..', '..', 'data', 'extinction_coef.mat')
a = loadmat(extinction_fname)['extinct_coef']
interp_hbo = interp1d(a[(:, 0)], a[(:, 1)], kind='linear')
interp_hb = interp1d(a[(:, 0)], a[(:, 2)], kind='linear')
ext_coef = np.array([[interp_hbo(freqs[0]), interp_hb(freqs[0])], [interp_hbo(freqs[1]), interp_hb(freqs[1])]])
abs_coef = (ext_coef * 0.2303)
return abs_coef
|
def _load_absorption(freqs):
from scipy.io import loadmat
from scipy.interpolate import interp1d
extinction_fname = op.join(op.dirname(__file__), '..', '..', 'data', 'extinction_coef.mat')
a = loadmat(extinction_fname)['extinct_coef']
interp_hbo = interp1d(a[(:, 0)], a[(:, 1)], kind='linear')
interp_hb = interp1d(a[(:, 0)], a[(:, 2)], kind='linear')
ext_coef = np.array([[interp_hbo(freqs[0]), interp_hb(freqs[0])], [interp_hbo(freqs[1]), interp_hb(freqs[1])]])
abs_coef = (ext_coef * 0.2303)
return abs_coef<|docstring|>Load molar extinction coefficients.<|endoftext|>
|
ec60d4adfea2b03e8e1626d3580ba102ec32345003bdc04d258e5cb7cf763ca6
|
def filter_dict(dict, keywords):
'\n Returns only the keywords that are part of a dictionary\n\n Parameters\n ----------\n dictionary : dict\n Dictionary for filtering\n keywords : list of str\n Keywords that will be filtered\n\n Returns\n -------\n keywords : list of str\n List containing the keywords that are keys in dictionary\n '
return [key for key in keywords if (key in dict)]
|
Returns only the keywords that are part of a dictionary
Parameters
----------
dictionary : dict
Dictionary for filtering
keywords : list of str
Keywords that will be filtered
Returns
-------
keywords : list of str
List containing the keywords that are keys in dictionary
|
kp2d/datasets/augmentations.py
|
filter_dict
|
gleefe1995/kp2d
| 149
|
python
|
def filter_dict(dict, keywords):
'\n Returns only the keywords that are part of a dictionary\n\n Parameters\n ----------\n dictionary : dict\n Dictionary for filtering\n keywords : list of str\n Keywords that will be filtered\n\n Returns\n -------\n keywords : list of str\n List containing the keywords that are keys in dictionary\n '
return [key for key in keywords if (key in dict)]
|
def filter_dict(dict, keywords):
'\n Returns only the keywords that are part of a dictionary\n\n Parameters\n ----------\n dictionary : dict\n Dictionary for filtering\n keywords : list of str\n Keywords that will be filtered\n\n Returns\n -------\n keywords : list of str\n List containing the keywords that are keys in dictionary\n '
return [key for key in keywords if (key in dict)]<|docstring|>Returns only the keywords that are part of a dictionary
Parameters
----------
dictionary : dict
Dictionary for filtering
keywords : list of str
Keywords that will be filtered
Returns
-------
keywords : list of str
List containing the keywords that are keys in dictionary<|endoftext|>
|
05078bbfc5c61d7fc840348cd4ecb0b4e5adf7e51bc50064c9bf1f082f6adce4
|
def resize_sample(sample, image_shape, image_interpolation=Image.ANTIALIAS):
"\n Resizes a sample, which contains an input image.\n\n Parameters\n ----------\n sample : dict\n Dictionary with sample values (output from a dataset's __getitem__ method)\n shape : tuple (H,W)\n Output shape\n image_interpolation : int\n Interpolation mode\n\n Returns\n -------\n sample : dict\n Resized sample\n "
image_transform = transforms.Resize(image_shape, interpolation=image_interpolation)
sample['image'] = image_transform(sample['image'])
return sample
|
Resizes a sample, which contains an input image.
Parameters
----------
sample : dict
Dictionary with sample values (output from a dataset's __getitem__ method)
shape : tuple (H,W)
Output shape
image_interpolation : int
Interpolation mode
Returns
-------
sample : dict
Resized sample
|
kp2d/datasets/augmentations.py
|
resize_sample
|
gleefe1995/kp2d
| 149
|
python
|
def resize_sample(sample, image_shape, image_interpolation=Image.ANTIALIAS):
"\n Resizes a sample, which contains an input image.\n\n Parameters\n ----------\n sample : dict\n Dictionary with sample values (output from a dataset's __getitem__ method)\n shape : tuple (H,W)\n Output shape\n image_interpolation : int\n Interpolation mode\n\n Returns\n -------\n sample : dict\n Resized sample\n "
image_transform = transforms.Resize(image_shape, interpolation=image_interpolation)
sample['image'] = image_transform(sample['image'])
return sample
|
def resize_sample(sample, image_shape, image_interpolation=Image.ANTIALIAS):
"\n Resizes a sample, which contains an input image.\n\n Parameters\n ----------\n sample : dict\n Dictionary with sample values (output from a dataset's __getitem__ method)\n shape : tuple (H,W)\n Output shape\n image_interpolation : int\n Interpolation mode\n\n Returns\n -------\n sample : dict\n Resized sample\n "
image_transform = transforms.Resize(image_shape, interpolation=image_interpolation)
sample['image'] = image_transform(sample['image'])
return sample<|docstring|>Resizes a sample, which contains an input image.
Parameters
----------
sample : dict
Dictionary with sample values (output from a dataset's __getitem__ method)
shape : tuple (H,W)
Output shape
image_interpolation : int
Interpolation mode
Returns
-------
sample : dict
Resized sample<|endoftext|>
|
10a3c6e02a096b01404aff4914109d82b22af72fca8ef8632452009a560efa39
|
def to_tensor_sample(sample, tensor_type='torch.FloatTensor'):
'\n Casts the keys of sample to tensors.\n\n Parameters\n ----------\n sample : dict\n Input sample\n tensor_type : str\n Type of tensor we are casting to\n\n Returns\n -------\n sample : dict\n Sample with keys cast as tensors\n '
transform = transforms.ToTensor()
sample['image'] = transform(sample['image']).type(tensor_type)
return sample
|
Casts the keys of sample to tensors.
Parameters
----------
sample : dict
Input sample
tensor_type : str
Type of tensor we are casting to
Returns
-------
sample : dict
Sample with keys cast as tensors
|
kp2d/datasets/augmentations.py
|
to_tensor_sample
|
gleefe1995/kp2d
| 149
|
python
|
def to_tensor_sample(sample, tensor_type='torch.FloatTensor'):
'\n Casts the keys of sample to tensors.\n\n Parameters\n ----------\n sample : dict\n Input sample\n tensor_type : str\n Type of tensor we are casting to\n\n Returns\n -------\n sample : dict\n Sample with keys cast as tensors\n '
transform = transforms.ToTensor()
sample['image'] = transform(sample['image']).type(tensor_type)
return sample
|
def to_tensor_sample(sample, tensor_type='torch.FloatTensor'):
'\n Casts the keys of sample to tensors.\n\n Parameters\n ----------\n sample : dict\n Input sample\n tensor_type : str\n Type of tensor we are casting to\n\n Returns\n -------\n sample : dict\n Sample with keys cast as tensors\n '
transform = transforms.ToTensor()
sample['image'] = transform(sample['image']).type(tensor_type)
return sample<|docstring|>Casts the keys of sample to tensors.
Parameters
----------
sample : dict
Input sample
tensor_type : str
Type of tensor we are casting to
Returns
-------
sample : dict
Sample with keys cast as tensors<|endoftext|>
|
5bd293b3f0f29d898de9c74eb7ff6a691bc678c973712effc62b6abadb75685a
|
def spatial_augment_sample(sample):
' Apply spatial augmentation to an image (flipping and random affine transformation).'
augment_image = transforms.Compose([transforms.RandomVerticalFlip(p=0.5), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomAffine(15, translate=(0.1, 0.1), scale=(0.9, 1.1))])
sample['image'] = augment_image(sample['image'])
return sample
|
Apply spatial augmentation to an image (flipping and random affine transformation).
|
kp2d/datasets/augmentations.py
|
spatial_augment_sample
|
gleefe1995/kp2d
| 149
|
python
|
def spatial_augment_sample(sample):
' '
augment_image = transforms.Compose([transforms.RandomVerticalFlip(p=0.5), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomAffine(15, translate=(0.1, 0.1), scale=(0.9, 1.1))])
sample['image'] = augment_image(sample['image'])
return sample
|
def spatial_augment_sample(sample):
' '
augment_image = transforms.Compose([transforms.RandomVerticalFlip(p=0.5), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomAffine(15, translate=(0.1, 0.1), scale=(0.9, 1.1))])
sample['image'] = augment_image(sample['image'])
return sample<|docstring|>Apply spatial augmentation to an image (flipping and random affine transformation).<|endoftext|>
|
067658d7ad65604027502941a7f2f0ab44eea308465a80a237ea7e451429d861
|
def unnormalize_image(tensor, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)):
' Counterpart method of torchvision.transforms.Normalize.'
for (t, m, s) in zip(tensor, mean, std):
t.div_((1 / s)).sub_((- m))
return tensor
|
Counterpart method of torchvision.transforms.Normalize.
|
kp2d/datasets/augmentations.py
|
unnormalize_image
|
gleefe1995/kp2d
| 149
|
python
|
def unnormalize_image(tensor, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)):
' '
for (t, m, s) in zip(tensor, mean, std):
t.div_((1 / s)).sub_((- m))
return tensor
|
def unnormalize_image(tensor, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)):
' '
for (t, m, s) in zip(tensor, mean, std):
t.div_((1 / s)).sub_((- m))
return tensor<|docstring|>Counterpart method of torchvision.transforms.Normalize.<|endoftext|>
|
81f708f392aa237dfddcad7c819b527501a6610823eab538e1bd36eadf3dc5ae
|
def sample_homography(shape, perspective=True, scaling=True, rotation=True, translation=True, n_scales=100, n_angles=100, scaling_amplitude=0.1, perspective_amplitude=0.4, patch_ratio=0.8, max_angle=(pi / 4)):
' Sample a random homography that includes perspective, scale, translation and rotation operations.'
width = float(shape[1])
hw_ratio = (float(shape[0]) / float(shape[1]))
pts1 = np.stack([[(- 1.0), (- 1.0)], [(- 1.0), 1.0], [1.0, (- 1.0)], [1.0, 1.0]], axis=0)
pts2 = (pts1.copy() * patch_ratio)
pts2[(:, 1)] *= hw_ratio
if perspective:
perspective_amplitude_x = np.random.normal(0.0, (perspective_amplitude / 2), 2)
perspective_amplitude_y = np.random.normal(0.0, ((hw_ratio * perspective_amplitude) / 2), 2)
perspective_amplitude_x = np.clip(perspective_amplitude_x, ((- perspective_amplitude) / 2), (perspective_amplitude / 2))
perspective_amplitude_y = np.clip(perspective_amplitude_y, ((hw_ratio * (- perspective_amplitude)) / 2), ((hw_ratio * perspective_amplitude) / 2))
pts2[(0, 0)] -= perspective_amplitude_x[1]
pts2[(0, 1)] -= perspective_amplitude_y[1]
pts2[(1, 0)] -= perspective_amplitude_x[0]
pts2[(1, 1)] += perspective_amplitude_y[1]
pts2[(2, 0)] += perspective_amplitude_x[1]
pts2[(2, 1)] -= perspective_amplitude_y[0]
pts2[(3, 0)] += perspective_amplitude_x[0]
pts2[(3, 1)] += perspective_amplitude_y[0]
if scaling:
random_scales = np.random.normal(1, (scaling_amplitude / 2), n_scales)
random_scales = np.clip(random_scales, (1 - (scaling_amplitude / 2)), (1 + (scaling_amplitude / 2)))
scales = np.concatenate([[1.0], random_scales], 0)
center = np.mean(pts2, axis=0, keepdims=True)
scaled = ((np.expand_dims((pts2 - center), axis=0) * np.expand_dims(np.expand_dims(scales, 1), 1)) + center)
valid = np.arange(n_scales)
idx = valid[np.random.randint(valid.shape[0])]
pts2 = scaled[idx]
if translation:
(t_min, t_max) = (np.min((pts2 - [(- 1.0), (- hw_ratio)]), axis=0), np.min(([1.0, hw_ratio] - pts2), axis=0))
pts2 += np.expand_dims(np.stack([np.random.uniform((- t_min[0]), t_max[0]), np.random.uniform((- t_min[1]), t_max[1])]), axis=0)
if rotation:
angles = np.linspace((- max_angle), max_angle, n_angles)
angles = np.concatenate([[0.0], angles], axis=0)
center = np.mean(pts2, axis=0, keepdims=True)
rot_mat = np.reshape(np.stack([np.cos(angles), (- np.sin(angles)), np.sin(angles), np.cos(angles)], axis=1), [(- 1), 2, 2])
rotated = (np.matmul(np.tile(np.expand_dims((pts2 - center), axis=0), [(n_angles + 1), 1, 1]), rot_mat) + center)
valid = np.where(np.all(((rotated >= [(- 1.0), (- hw_ratio)]) & (rotated < [1.0, hw_ratio])), axis=(1, 2)))[0]
idx = valid[np.random.randint(valid.shape[0])]
pts2 = rotated[idx]
pts2[(:, 1)] /= hw_ratio
def ax(p, q):
return [p[0], p[1], 1, 0, 0, 0, ((- p[0]) * q[0]), ((- p[1]) * q[0])]
def ay(p, q):
return [0, 0, 0, p[0], p[1], 1, ((- p[0]) * q[1]), ((- p[1]) * q[1])]
a_mat = np.stack([f(pts1[i], pts2[i]) for i in range(4) for f in (ax, ay)], axis=0)
p_mat = np.transpose(np.stack([[pts2[i][j] for i in range(4) for j in range(2)]], axis=0))
homography = np.matmul(np.linalg.pinv(a_mat), p_mat).squeeze()
homography = np.concatenate([homography, [1.0]]).reshape(3, 3)
return homography
|
Sample a random homography that includes perspective, scale, translation and rotation operations.
|
kp2d/datasets/augmentations.py
|
sample_homography
|
gleefe1995/kp2d
| 149
|
python
|
def sample_homography(shape, perspective=True, scaling=True, rotation=True, translation=True, n_scales=100, n_angles=100, scaling_amplitude=0.1, perspective_amplitude=0.4, patch_ratio=0.8, max_angle=(pi / 4)):
' '
width = float(shape[1])
hw_ratio = (float(shape[0]) / float(shape[1]))
pts1 = np.stack([[(- 1.0), (- 1.0)], [(- 1.0), 1.0], [1.0, (- 1.0)], [1.0, 1.0]], axis=0)
pts2 = (pts1.copy() * patch_ratio)
pts2[(:, 1)] *= hw_ratio
if perspective:
perspective_amplitude_x = np.random.normal(0.0, (perspective_amplitude / 2), 2)
perspective_amplitude_y = np.random.normal(0.0, ((hw_ratio * perspective_amplitude) / 2), 2)
perspective_amplitude_x = np.clip(perspective_amplitude_x, ((- perspective_amplitude) / 2), (perspective_amplitude / 2))
perspective_amplitude_y = np.clip(perspective_amplitude_y, ((hw_ratio * (- perspective_amplitude)) / 2), ((hw_ratio * perspective_amplitude) / 2))
pts2[(0, 0)] -= perspective_amplitude_x[1]
pts2[(0, 1)] -= perspective_amplitude_y[1]
pts2[(1, 0)] -= perspective_amplitude_x[0]
pts2[(1, 1)] += perspective_amplitude_y[1]
pts2[(2, 0)] += perspective_amplitude_x[1]
pts2[(2, 1)] -= perspective_amplitude_y[0]
pts2[(3, 0)] += perspective_amplitude_x[0]
pts2[(3, 1)] += perspective_amplitude_y[0]
if scaling:
random_scales = np.random.normal(1, (scaling_amplitude / 2), n_scales)
random_scales = np.clip(random_scales, (1 - (scaling_amplitude / 2)), (1 + (scaling_amplitude / 2)))
scales = np.concatenate([[1.0], random_scales], 0)
center = np.mean(pts2, axis=0, keepdims=True)
scaled = ((np.expand_dims((pts2 - center), axis=0) * np.expand_dims(np.expand_dims(scales, 1), 1)) + center)
valid = np.arange(n_scales)
idx = valid[np.random.randint(valid.shape[0])]
pts2 = scaled[idx]
if translation:
(t_min, t_max) = (np.min((pts2 - [(- 1.0), (- hw_ratio)]), axis=0), np.min(([1.0, hw_ratio] - pts2), axis=0))
pts2 += np.expand_dims(np.stack([np.random.uniform((- t_min[0]), t_max[0]), np.random.uniform((- t_min[1]), t_max[1])]), axis=0)
if rotation:
angles = np.linspace((- max_angle), max_angle, n_angles)
angles = np.concatenate([[0.0], angles], axis=0)
center = np.mean(pts2, axis=0, keepdims=True)
rot_mat = np.reshape(np.stack([np.cos(angles), (- np.sin(angles)), np.sin(angles), np.cos(angles)], axis=1), [(- 1), 2, 2])
rotated = (np.matmul(np.tile(np.expand_dims((pts2 - center), axis=0), [(n_angles + 1), 1, 1]), rot_mat) + center)
valid = np.where(np.all(((rotated >= [(- 1.0), (- hw_ratio)]) & (rotated < [1.0, hw_ratio])), axis=(1, 2)))[0]
idx = valid[np.random.randint(valid.shape[0])]
pts2 = rotated[idx]
pts2[(:, 1)] /= hw_ratio
def ax(p, q):
return [p[0], p[1], 1, 0, 0, 0, ((- p[0]) * q[0]), ((- p[1]) * q[0])]
def ay(p, q):
return [0, 0, 0, p[0], p[1], 1, ((- p[0]) * q[1]), ((- p[1]) * q[1])]
a_mat = np.stack([f(pts1[i], pts2[i]) for i in range(4) for f in (ax, ay)], axis=0)
p_mat = np.transpose(np.stack([[pts2[i][j] for i in range(4) for j in range(2)]], axis=0))
homography = np.matmul(np.linalg.pinv(a_mat), p_mat).squeeze()
homography = np.concatenate([homography, [1.0]]).reshape(3, 3)
return homography
|
def sample_homography(shape, perspective=True, scaling=True, rotation=True, translation=True, n_scales=100, n_angles=100, scaling_amplitude=0.1, perspective_amplitude=0.4, patch_ratio=0.8, max_angle=(pi / 4)):
' '
width = float(shape[1])
hw_ratio = (float(shape[0]) / float(shape[1]))
pts1 = np.stack([[(- 1.0), (- 1.0)], [(- 1.0), 1.0], [1.0, (- 1.0)], [1.0, 1.0]], axis=0)
pts2 = (pts1.copy() * patch_ratio)
pts2[(:, 1)] *= hw_ratio
if perspective:
perspective_amplitude_x = np.random.normal(0.0, (perspective_amplitude / 2), 2)
perspective_amplitude_y = np.random.normal(0.0, ((hw_ratio * perspective_amplitude) / 2), 2)
perspective_amplitude_x = np.clip(perspective_amplitude_x, ((- perspective_amplitude) / 2), (perspective_amplitude / 2))
perspective_amplitude_y = np.clip(perspective_amplitude_y, ((hw_ratio * (- perspective_amplitude)) / 2), ((hw_ratio * perspective_amplitude) / 2))
pts2[(0, 0)] -= perspective_amplitude_x[1]
pts2[(0, 1)] -= perspective_amplitude_y[1]
pts2[(1, 0)] -= perspective_amplitude_x[0]
pts2[(1, 1)] += perspective_amplitude_y[1]
pts2[(2, 0)] += perspective_amplitude_x[1]
pts2[(2, 1)] -= perspective_amplitude_y[0]
pts2[(3, 0)] += perspective_amplitude_x[0]
pts2[(3, 1)] += perspective_amplitude_y[0]
if scaling:
random_scales = np.random.normal(1, (scaling_amplitude / 2), n_scales)
random_scales = np.clip(random_scales, (1 - (scaling_amplitude / 2)), (1 + (scaling_amplitude / 2)))
scales = np.concatenate([[1.0], random_scales], 0)
center = np.mean(pts2, axis=0, keepdims=True)
scaled = ((np.expand_dims((pts2 - center), axis=0) * np.expand_dims(np.expand_dims(scales, 1), 1)) + center)
valid = np.arange(n_scales)
idx = valid[np.random.randint(valid.shape[0])]
pts2 = scaled[idx]
if translation:
(t_min, t_max) = (np.min((pts2 - [(- 1.0), (- hw_ratio)]), axis=0), np.min(([1.0, hw_ratio] - pts2), axis=0))
pts2 += np.expand_dims(np.stack([np.random.uniform((- t_min[0]), t_max[0]), np.random.uniform((- t_min[1]), t_max[1])]), axis=0)
if rotation:
angles = np.linspace((- max_angle), max_angle, n_angles)
angles = np.concatenate([[0.0], angles], axis=0)
center = np.mean(pts2, axis=0, keepdims=True)
rot_mat = np.reshape(np.stack([np.cos(angles), (- np.sin(angles)), np.sin(angles), np.cos(angles)], axis=1), [(- 1), 2, 2])
rotated = (np.matmul(np.tile(np.expand_dims((pts2 - center), axis=0), [(n_angles + 1), 1, 1]), rot_mat) + center)
valid = np.where(np.all(((rotated >= [(- 1.0), (- hw_ratio)]) & (rotated < [1.0, hw_ratio])), axis=(1, 2)))[0]
idx = valid[np.random.randint(valid.shape[0])]
pts2 = rotated[idx]
pts2[(:, 1)] /= hw_ratio
def ax(p, q):
return [p[0], p[1], 1, 0, 0, 0, ((- p[0]) * q[0]), ((- p[1]) * q[0])]
def ay(p, q):
return [0, 0, 0, p[0], p[1], 1, ((- p[0]) * q[1]), ((- p[1]) * q[1])]
a_mat = np.stack([f(pts1[i], pts2[i]) for i in range(4) for f in (ax, ay)], axis=0)
p_mat = np.transpose(np.stack([[pts2[i][j] for i in range(4) for j in range(2)]], axis=0))
homography = np.matmul(np.linalg.pinv(a_mat), p_mat).squeeze()
homography = np.concatenate([homography, [1.0]]).reshape(3, 3)
return homography<|docstring|>Sample a random homography that includes perspective, scale, translation and rotation operations.<|endoftext|>
|
f7c62243ff87793e5674b39b457eac346d1adc8e7e0fa146738decac4a5893e9
|
def warp_homography(sources, homography):
'Warp features given a homography\n\n Parameters\n ----------\n sources: torch.tensor (1,H,W,2)\n Keypoint vector.\n homography: torch.Tensor (3,3)\n Homography.\n\n Returns\n -------\n warped_sources: torch.tensor (1,H,W,2)\n Warped feature vector.\n '
(_, H, W, _) = sources.shape
warped_sources = sources.clone().squeeze()
warped_sources = warped_sources.view((- 1), 2)
warped_sources = torch.addmm(homography[(:, 2)], warped_sources, homography[(:, :2)].t())
warped_sources.mul_((1 / warped_sources[(:, 2)].unsqueeze(1)))
warped_sources = warped_sources[(:, :2)].contiguous().view(1, H, W, 2)
return warped_sources
|
Warp features given a homography
Parameters
----------
sources: torch.tensor (1,H,W,2)
Keypoint vector.
homography: torch.Tensor (3,3)
Homography.
Returns
-------
warped_sources: torch.tensor (1,H,W,2)
Warped feature vector.
|
kp2d/datasets/augmentations.py
|
warp_homography
|
gleefe1995/kp2d
| 149
|
python
|
def warp_homography(sources, homography):
'Warp features given a homography\n\n Parameters\n ----------\n sources: torch.tensor (1,H,W,2)\n Keypoint vector.\n homography: torch.Tensor (3,3)\n Homography.\n\n Returns\n -------\n warped_sources: torch.tensor (1,H,W,2)\n Warped feature vector.\n '
(_, H, W, _) = sources.shape
warped_sources = sources.clone().squeeze()
warped_sources = warped_sources.view((- 1), 2)
warped_sources = torch.addmm(homography[(:, 2)], warped_sources, homography[(:, :2)].t())
warped_sources.mul_((1 / warped_sources[(:, 2)].unsqueeze(1)))
warped_sources = warped_sources[(:, :2)].contiguous().view(1, H, W, 2)
return warped_sources
|
def warp_homography(sources, homography):
'Warp features given a homography\n\n Parameters\n ----------\n sources: torch.tensor (1,H,W,2)\n Keypoint vector.\n homography: torch.Tensor (3,3)\n Homography.\n\n Returns\n -------\n warped_sources: torch.tensor (1,H,W,2)\n Warped feature vector.\n '
(_, H, W, _) = sources.shape
warped_sources = sources.clone().squeeze()
warped_sources = warped_sources.view((- 1), 2)
warped_sources = torch.addmm(homography[(:, 2)], warped_sources, homography[(:, :2)].t())
warped_sources.mul_((1 / warped_sources[(:, 2)].unsqueeze(1)))
warped_sources = warped_sources[(:, :2)].contiguous().view(1, H, W, 2)
return warped_sources<|docstring|>Warp features given a homography
Parameters
----------
sources: torch.tensor (1,H,W,2)
Keypoint vector.
homography: torch.Tensor (3,3)
Homography.
Returns
-------
warped_sources: torch.tensor (1,H,W,2)
Warped feature vector.<|endoftext|>
|
bf8a4280d9387f2c9d923f8acee0f219b2369a5180e7fe18d0b45e10963212c0
|
def add_noise(img, mode='gaussian', percent=0.02):
"Add image noise\n\n Parameters\n ----------\n image : np.array\n Input image\n mode: str\n Type of noise, from ['gaussian','salt','pepper','s&p']\n percent: float\n Percentage image points to add noise to.\n Returns\n -------\n image : np.array\n Image plus noise.\n "
original_dtype = img.dtype
if (mode == 'gaussian'):
mean = 0
var = 0.1
sigma = (var * 0.5)
if (img.ndim == 2):
(h, w) = img.shape
gauss = np.random.normal(mean, sigma, (h, w))
else:
(h, w, c) = img.shape
gauss = np.random.normal(mean, sigma, (h, w, c))
if (img.dtype not in [np.float32, np.float64]):
gauss = (gauss * np.iinfo(img.dtype).max)
img = np.clip((img.astype(np.float) + gauss), 0, np.iinfo(img.dtype).max)
else:
img = np.clip((img.astype(np.float) + gauss), 0, 1)
elif (mode == 'salt'):
print(img.dtype)
s_vs_p = 1
num_salt = np.ceil(((percent * img.size) * s_vs_p))
coords = tuple([np.random.randint(0, (i - 1), int(num_salt)) for i in img.shape])
if (img.dtype in [np.float32, np.float64]):
img[coords] = 1
else:
img[coords] = np.iinfo(img.dtype).max
print(img.dtype)
elif (mode == 'pepper'):
s_vs_p = 0
num_pepper = np.ceil(((percent * img.size) * (1.0 - s_vs_p)))
coords = tuple([np.random.randint(0, (i - 1), int(num_pepper)) for i in img.shape])
img[coords] = 0
elif (mode == 's&p'):
s_vs_p = 0.5
num_salt = np.ceil(((percent * img.size) * s_vs_p))
coords = tuple([np.random.randint(0, (i - 1), int(num_salt)) for i in img.shape])
if (img.dtype in [np.float32, np.float64]):
img[coords] = 1
else:
img[coords] = np.iinfo(img.dtype).max
num_pepper = np.ceil(((percent * img.size) * (1.0 - s_vs_p)))
coords = tuple([np.random.randint(0, (i - 1), int(num_pepper)) for i in img.shape])
img[coords] = 0
else:
raise ValueError('not support mode for {}'.format(mode))
noisy = img.astype(original_dtype)
return noisy
|
Add image noise
Parameters
----------
image : np.array
Input image
mode: str
Type of noise, from ['gaussian','salt','pepper','s&p']
percent: float
Percentage image points to add noise to.
Returns
-------
image : np.array
Image plus noise.
|
kp2d/datasets/augmentations.py
|
add_noise
|
gleefe1995/kp2d
| 149
|
python
|
def add_noise(img, mode='gaussian', percent=0.02):
"Add image noise\n\n Parameters\n ----------\n image : np.array\n Input image\n mode: str\n Type of noise, from ['gaussian','salt','pepper','s&p']\n percent: float\n Percentage image points to add noise to.\n Returns\n -------\n image : np.array\n Image plus noise.\n "
original_dtype = img.dtype
if (mode == 'gaussian'):
mean = 0
var = 0.1
sigma = (var * 0.5)
if (img.ndim == 2):
(h, w) = img.shape
gauss = np.random.normal(mean, sigma, (h, w))
else:
(h, w, c) = img.shape
gauss = np.random.normal(mean, sigma, (h, w, c))
if (img.dtype not in [np.float32, np.float64]):
gauss = (gauss * np.iinfo(img.dtype).max)
img = np.clip((img.astype(np.float) + gauss), 0, np.iinfo(img.dtype).max)
else:
img = np.clip((img.astype(np.float) + gauss), 0, 1)
elif (mode == 'salt'):
print(img.dtype)
s_vs_p = 1
num_salt = np.ceil(((percent * img.size) * s_vs_p))
coords = tuple([np.random.randint(0, (i - 1), int(num_salt)) for i in img.shape])
if (img.dtype in [np.float32, np.float64]):
img[coords] = 1
else:
img[coords] = np.iinfo(img.dtype).max
print(img.dtype)
elif (mode == 'pepper'):
s_vs_p = 0
num_pepper = np.ceil(((percent * img.size) * (1.0 - s_vs_p)))
coords = tuple([np.random.randint(0, (i - 1), int(num_pepper)) for i in img.shape])
img[coords] = 0
elif (mode == 's&p'):
s_vs_p = 0.5
num_salt = np.ceil(((percent * img.size) * s_vs_p))
coords = tuple([np.random.randint(0, (i - 1), int(num_salt)) for i in img.shape])
if (img.dtype in [np.float32, np.float64]):
img[coords] = 1
else:
img[coords] = np.iinfo(img.dtype).max
num_pepper = np.ceil(((percent * img.size) * (1.0 - s_vs_p)))
coords = tuple([np.random.randint(0, (i - 1), int(num_pepper)) for i in img.shape])
img[coords] = 0
else:
raise ValueError('not support mode for {}'.format(mode))
noisy = img.astype(original_dtype)
return noisy
|
def add_noise(img, mode='gaussian', percent=0.02):
"Add image noise\n\n Parameters\n ----------\n image : np.array\n Input image\n mode: str\n Type of noise, from ['gaussian','salt','pepper','s&p']\n percent: float\n Percentage image points to add noise to.\n Returns\n -------\n image : np.array\n Image plus noise.\n "
original_dtype = img.dtype
if (mode == 'gaussian'):
mean = 0
var = 0.1
sigma = (var * 0.5)
if (img.ndim == 2):
(h, w) = img.shape
gauss = np.random.normal(mean, sigma, (h, w))
else:
(h, w, c) = img.shape
gauss = np.random.normal(mean, sigma, (h, w, c))
if (img.dtype not in [np.float32, np.float64]):
gauss = (gauss * np.iinfo(img.dtype).max)
img = np.clip((img.astype(np.float) + gauss), 0, np.iinfo(img.dtype).max)
else:
img = np.clip((img.astype(np.float) + gauss), 0, 1)
elif (mode == 'salt'):
print(img.dtype)
s_vs_p = 1
num_salt = np.ceil(((percent * img.size) * s_vs_p))
coords = tuple([np.random.randint(0, (i - 1), int(num_salt)) for i in img.shape])
if (img.dtype in [np.float32, np.float64]):
img[coords] = 1
else:
img[coords] = np.iinfo(img.dtype).max
print(img.dtype)
elif (mode == 'pepper'):
s_vs_p = 0
num_pepper = np.ceil(((percent * img.size) * (1.0 - s_vs_p)))
coords = tuple([np.random.randint(0, (i - 1), int(num_pepper)) for i in img.shape])
img[coords] = 0
elif (mode == 's&p'):
s_vs_p = 0.5
num_salt = np.ceil(((percent * img.size) * s_vs_p))
coords = tuple([np.random.randint(0, (i - 1), int(num_salt)) for i in img.shape])
if (img.dtype in [np.float32, np.float64]):
img[coords] = 1
else:
img[coords] = np.iinfo(img.dtype).max
num_pepper = np.ceil(((percent * img.size) * (1.0 - s_vs_p)))
coords = tuple([np.random.randint(0, (i - 1), int(num_pepper)) for i in img.shape])
img[coords] = 0
else:
raise ValueError('not support mode for {}'.format(mode))
noisy = img.astype(original_dtype)
return noisy<|docstring|>Add image noise
Parameters
----------
image : np.array
Input image
mode: str
Type of noise, from ['gaussian','salt','pepper','s&p']
percent: float
Percentage image points to add noise to.
Returns
-------
image : np.array
Image plus noise.<|endoftext|>
|
27e8b15b1ff1dc226c735d87f643c0e283e6ba8278e5edf8a31b96924b92d730
|
def non_spatial_augmentation(img_warp_ori, jitter_paramters, color_order=[0, 1, 2], to_gray=False):
' Apply non-spatial augmentation to an image (jittering, color swap, convert to gray scale, Gaussian blur).'
(brightness, contrast, saturation, hue) = jitter_paramters
color_augmentation = transforms.ColorJitter()
augment_image = color_augmentation.get_params(brightness=[max(0, (1 - brightness)), (1 + brightness)], contrast=[max(0, (1 - contrast)), (1 + contrast)], saturation=[max(0, (1 - saturation)), (1 + saturation)], hue=[(- hue), hue])
B = img_warp_ori.shape[0]
img_warp = []
kernel_sizes = [0, 1, 3, 5]
for b in range(B):
img_warp_sub = img_warp_ori[b].cpu()
img_warp_sub = torchvision.transforms.functional.to_pil_image(img_warp_sub)
img_warp_sub_np = np.array(img_warp_sub)
img_warp_sub_np = img_warp_sub_np[(:, :, color_order)]
if (np.random.rand() > 0.5):
img_warp_sub_np = add_noise(img_warp_sub_np)
rand_index = np.random.randint(4)
kernel_size = kernel_sizes[rand_index]
if (kernel_size > 0):
img_warp_sub_np = cv2.GaussianBlur(img_warp_sub_np, (kernel_size, kernel_size), sigmaX=0)
if to_gray:
img_warp_sub_np = cv2.cvtColor(img_warp_sub_np, cv2.COLOR_RGB2GRAY)
img_warp_sub_np = cv2.cvtColor(img_warp_sub_np, cv2.COLOR_GRAY2RGB)
img_warp_sub = Image.fromarray(img_warp_sub_np)
img_warp_sub = color_augmentation(img_warp_sub)
img_warp_sub = torchvision.transforms.functional.to_tensor(img_warp_sub).to(img_warp_ori.device)
img_warp.append(img_warp_sub)
img_warp = torch.stack(img_warp, dim=0)
return img_warp
|
Apply non-spatial augmentation to an image (jittering, color swap, convert to gray scale, Gaussian blur).
|
kp2d/datasets/augmentations.py
|
non_spatial_augmentation
|
gleefe1995/kp2d
| 149
|
python
|
def non_spatial_augmentation(img_warp_ori, jitter_paramters, color_order=[0, 1, 2], to_gray=False):
' '
(brightness, contrast, saturation, hue) = jitter_paramters
color_augmentation = transforms.ColorJitter()
augment_image = color_augmentation.get_params(brightness=[max(0, (1 - brightness)), (1 + brightness)], contrast=[max(0, (1 - contrast)), (1 + contrast)], saturation=[max(0, (1 - saturation)), (1 + saturation)], hue=[(- hue), hue])
B = img_warp_ori.shape[0]
img_warp = []
kernel_sizes = [0, 1, 3, 5]
for b in range(B):
img_warp_sub = img_warp_ori[b].cpu()
img_warp_sub = torchvision.transforms.functional.to_pil_image(img_warp_sub)
img_warp_sub_np = np.array(img_warp_sub)
img_warp_sub_np = img_warp_sub_np[(:, :, color_order)]
if (np.random.rand() > 0.5):
img_warp_sub_np = add_noise(img_warp_sub_np)
rand_index = np.random.randint(4)
kernel_size = kernel_sizes[rand_index]
if (kernel_size > 0):
img_warp_sub_np = cv2.GaussianBlur(img_warp_sub_np, (kernel_size, kernel_size), sigmaX=0)
if to_gray:
img_warp_sub_np = cv2.cvtColor(img_warp_sub_np, cv2.COLOR_RGB2GRAY)
img_warp_sub_np = cv2.cvtColor(img_warp_sub_np, cv2.COLOR_GRAY2RGB)
img_warp_sub = Image.fromarray(img_warp_sub_np)
img_warp_sub = color_augmentation(img_warp_sub)
img_warp_sub = torchvision.transforms.functional.to_tensor(img_warp_sub).to(img_warp_ori.device)
img_warp.append(img_warp_sub)
img_warp = torch.stack(img_warp, dim=0)
return img_warp
|
def non_spatial_augmentation(img_warp_ori, jitter_paramters, color_order=[0, 1, 2], to_gray=False):
' '
(brightness, contrast, saturation, hue) = jitter_paramters
color_augmentation = transforms.ColorJitter()
augment_image = color_augmentation.get_params(brightness=[max(0, (1 - brightness)), (1 + brightness)], contrast=[max(0, (1 - contrast)), (1 + contrast)], saturation=[max(0, (1 - saturation)), (1 + saturation)], hue=[(- hue), hue])
B = img_warp_ori.shape[0]
img_warp = []
kernel_sizes = [0, 1, 3, 5]
for b in range(B):
img_warp_sub = img_warp_ori[b].cpu()
img_warp_sub = torchvision.transforms.functional.to_pil_image(img_warp_sub)
img_warp_sub_np = np.array(img_warp_sub)
img_warp_sub_np = img_warp_sub_np[(:, :, color_order)]
if (np.random.rand() > 0.5):
img_warp_sub_np = add_noise(img_warp_sub_np)
rand_index = np.random.randint(4)
kernel_size = kernel_sizes[rand_index]
if (kernel_size > 0):
img_warp_sub_np = cv2.GaussianBlur(img_warp_sub_np, (kernel_size, kernel_size), sigmaX=0)
if to_gray:
img_warp_sub_np = cv2.cvtColor(img_warp_sub_np, cv2.COLOR_RGB2GRAY)
img_warp_sub_np = cv2.cvtColor(img_warp_sub_np, cv2.COLOR_GRAY2RGB)
img_warp_sub = Image.fromarray(img_warp_sub_np)
img_warp_sub = color_augmentation(img_warp_sub)
img_warp_sub = torchvision.transforms.functional.to_tensor(img_warp_sub).to(img_warp_ori.device)
img_warp.append(img_warp_sub)
img_warp = torch.stack(img_warp, dim=0)
return img_warp<|docstring|>Apply non-spatial augmentation to an image (jittering, color swap, convert to gray scale, Gaussian blur).<|endoftext|>
|
eebe7c2eac6e49d189dfcb341e5042e731c278c81213fbbd547a69247cfba22e
|
def ha_augment_sample(data, jitter_paramters=[0.5, 0.5, 0.2, 0.05], patch_ratio=0.7, scaling_amplitude=0.2, max_angle=(pi / 4)):
'Apply Homography Adaptation image augmentation.'
target_img = data['image'].unsqueeze(0)
(_, _, H, W) = target_img.shape
device = target_img.device
homography = sample_homography([H, W], patch_ratio=patch_ratio, scaling_amplitude=scaling_amplitude, max_angle=max_angle)
homography = torch.from_numpy(homography).float().to(device)
source_grid = image_grid(1, H, W, dtype=target_img.dtype, device=device, ones=False, normalized=True).clone().permute(0, 2, 3, 1)
source_warped = warp_homography(source_grid, homography)
source_img = torch.nn.functional.grid_sample(target_img, source_warped, align_corners=True)
color_order = [0, 1, 2]
if (np.random.rand() > 0.5):
random.shuffle(color_order)
to_gray = False
if (np.random.rand() > 0.5):
to_gray = True
target_img = non_spatial_augmentation(target_img, jitter_paramters=jitter_paramters, color_order=color_order, to_gray=to_gray)
source_img = non_spatial_augmentation(source_img, jitter_paramters=jitter_paramters, color_order=color_order, to_gray=to_gray)
data['image'] = target_img.squeeze()
data['image_aug'] = source_img.squeeze()
data['homography'] = homography
return data
|
Apply Homography Adaptation image augmentation.
|
kp2d/datasets/augmentations.py
|
ha_augment_sample
|
gleefe1995/kp2d
| 149
|
python
|
def ha_augment_sample(data, jitter_paramters=[0.5, 0.5, 0.2, 0.05], patch_ratio=0.7, scaling_amplitude=0.2, max_angle=(pi / 4)):
target_img = data['image'].unsqueeze(0)
(_, _, H, W) = target_img.shape
device = target_img.device
homography = sample_homography([H, W], patch_ratio=patch_ratio, scaling_amplitude=scaling_amplitude, max_angle=max_angle)
homography = torch.from_numpy(homography).float().to(device)
source_grid = image_grid(1, H, W, dtype=target_img.dtype, device=device, ones=False, normalized=True).clone().permute(0, 2, 3, 1)
source_warped = warp_homography(source_grid, homography)
source_img = torch.nn.functional.grid_sample(target_img, source_warped, align_corners=True)
color_order = [0, 1, 2]
if (np.random.rand() > 0.5):
random.shuffle(color_order)
to_gray = False
if (np.random.rand() > 0.5):
to_gray = True
target_img = non_spatial_augmentation(target_img, jitter_paramters=jitter_paramters, color_order=color_order, to_gray=to_gray)
source_img = non_spatial_augmentation(source_img, jitter_paramters=jitter_paramters, color_order=color_order, to_gray=to_gray)
data['image'] = target_img.squeeze()
data['image_aug'] = source_img.squeeze()
data['homography'] = homography
return data
|
def ha_augment_sample(data, jitter_paramters=[0.5, 0.5, 0.2, 0.05], patch_ratio=0.7, scaling_amplitude=0.2, max_angle=(pi / 4)):
target_img = data['image'].unsqueeze(0)
(_, _, H, W) = target_img.shape
device = target_img.device
homography = sample_homography([H, W], patch_ratio=patch_ratio, scaling_amplitude=scaling_amplitude, max_angle=max_angle)
homography = torch.from_numpy(homography).float().to(device)
source_grid = image_grid(1, H, W, dtype=target_img.dtype, device=device, ones=False, normalized=True).clone().permute(0, 2, 3, 1)
source_warped = warp_homography(source_grid, homography)
source_img = torch.nn.functional.grid_sample(target_img, source_warped, align_corners=True)
color_order = [0, 1, 2]
if (np.random.rand() > 0.5):
random.shuffle(color_order)
to_gray = False
if (np.random.rand() > 0.5):
to_gray = True
target_img = non_spatial_augmentation(target_img, jitter_paramters=jitter_paramters, color_order=color_order, to_gray=to_gray)
source_img = non_spatial_augmentation(source_img, jitter_paramters=jitter_paramters, color_order=color_order, to_gray=to_gray)
data['image'] = target_img.squeeze()
data['image_aug'] = source_img.squeeze()
data['homography'] = homography
return data<|docstring|>Apply Homography Adaptation image augmentation.<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.