uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
68ad011c8cc05cdab10b23a8 | train | function | def _str_datetime_to_datetime_obj(datetime_str, date_format=DEFAULT_DATE_FORMAT):
return datetime.strptime(datetime_str, date_format)
| def _str_datetime_to_datetime_obj(datetime_str, date_format=DEFAULT_DATE_FORMAT):
| return datetime.strptime(datetime_str, date_format)
| days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d)
def _str_datetime_to_datetime_obj(datetime_str, date_format=DEFAULT_DATE_FORMAT):
| 64 | 64 | 27 | 17 | 47 | tducret/allocine-python | allocine/__init__.py | Python | _str_datetime_to_datetime_obj | _str_datetime_to_datetime_obj | 627 | 628 | 627 | 627 | f1993d7eff1f8837878224d5f634465d9b564395 | bigcode/the-stack | train |
c290c33f30946b4301b160a0 | train | function | def _cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
| def _cleanhtml(raw_html):
| cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
| .seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d)
def _str_datetime_to_datetime_obj(datetime_str, date_format=DEFAULT_DATE_FORMAT):
return datetime.strptime(datetime_str, date_format)
def _cleanhtml(raw_html):
| 64 | 64 | 35 | 7 | 57 | tducret/allocine-python | allocine/__init__.py | Python | _cleanhtml | _cleanhtml | 631 | 634 | 631 | 631 | e85a2814f89ed3ca074e9d31805a7201b0834c85 | bigcode/the-stack | train |
dfcf24201ef2cf3a3abde876 | train | class | @dataclass
class MovieVersion(Movie):
language: str
screen_format: str
@property
def version(self):
version = 'VF' if self.language == 'Français' else 'VOST'
if self.screen_format != 'Numérique':
version += f' {self.screen_format}'
return version
def get_movie(s... | @dataclass
class MovieVersion(Movie):
| language: str
screen_format: str
@property
def version(self):
version = 'VF' if self.language == 'Français' else 'VOST'
if self.screen_format != 'Numérique':
version += f' {self.screen_format}'
return version
def get_movie(self):
return Movie(
... | .movie_id}] ({self.duration_str})'
def __eq__(self, other):
return (self.movie_id) == (other.movie_id)
def __hash__(self):
""" This function allows us
to do a set(list_of_Movie_objects) """
return hash(self.movie_id)
@dataclass
class MovieVersion(Movie):
| 72 | 72 | 240 | 8 | 64 | tducret/allocine-python | allocine/__init__.py | Python | MovieVersion | MovieVersion | 95 | 132 | 95 | 96 | 2ef895a836bdf21dd5f8cca9f35c005da02376fc | bigcode/the-stack | train |
9309f85af3f6e81276ceab82 | train | function | def _clean_synopsis(raw_synopsis):
if raw_synopsis is None:
return None
synopsis = _cleanhtml(raw_synopsis) # Remove HTML tags (ex: <span>)
synopsis = synopsis.replace('\xa0', ' ')
return unicodedata.normalize("NFKD", synopsis)
| def _clean_synopsis(raw_synopsis):
| if raw_synopsis is None:
return None
synopsis = _cleanhtml(raw_synopsis) # Remove HTML tags (ex: <span>)
synopsis = synopsis.replace('\xa0', ' ')
return unicodedata.normalize("NFKD", synopsis)
| (datetime_str, date_format=DEFAULT_DATE_FORMAT):
return datetime.strptime(datetime_str, date_format)
def _cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
def _clean_synopsis(raw_synopsis):
| 64 | 64 | 66 | 9 | 54 | tducret/allocine-python | allocine/__init__.py | Python | _clean_synopsis | _clean_synopsis | 637 | 643 | 637 | 637 | b369a2ef0f3274cf7b82028584203cf9a0547fb3 | bigcode/the-stack | train |
0deea9277177826f414bc7d1 | train | function | def short_day_str(date: date) -> str:
return day_str(date)[:3]
| def short_day_str(date: date) -> str:
| return day_str(date)[:3]
| ', 'Octobre', 'Novembre', 'Décembre'
]
return MONTHS[month_number-1]
def to_french_short_weekday(weekday: int) -> str:
return to_french_weekday(weekday)[:3]
def short_day_str(date: date) -> str:
| 64 | 64 | 20 | 11 | 53 | tducret/allocine-python | allocine/__init__.py | Python | short_day_str | short_day_str | 203 | 204 | 203 | 203 | 939a4e9daa501e8e9b0cd4e402ceac6bcd8f7eec | bigcode/the-stack | train |
853c36436bfe8aa9f21fd877 | train | function | def to_french_weekday(weekday: int) -> str:
DAYS = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
return DAYS[weekday]
| def to_french_weekday(weekday: int) -> str:
| DAYS = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
return DAYS[weekday]
| chedule):
movie: MovieVersion
def __str__(self):
return f'{self.date_str} : {self.movie}'
def day_str(date: date) -> str:
return to_french_weekday(date.weekday())
def to_french_weekday(weekday: int) -> str:
| 64 | 64 | 51 | 14 | 50 | tducret/allocine-python | allocine/__init__.py | Python | to_french_weekday | to_french_weekday | 186 | 188 | 186 | 186 | 775bbd597e86dfe4badf6d3ad3d8b5d171554bce | bigcode/the-stack | train |
bacaee6423c27b25c4339836 | train | function | def get_available_dates(showtimes: List[Showtime]):
dates = [s.date for s in showtimes]
return sorted(list(set(dates)))
| def get_available_dates(showtimes: List[Showtime]):
| dates = [s.date for s in showtimes]
return sorted(list(set(dates)))
| return (self.theater_id) == (other.theater_id)
def __hash__(self):
""" This function allows us to do a set(list_of_Theaters_objects) """
return hash(self.theater_id)
# == Utils ==
def get_available_dates(showtimes: List[Showtime]):
| 64 | 64 | 32 | 12 | 52 | tducret/allocine-python | allocine/__init__.py | Python | get_available_dates | get_available_dates | 277 | 279 | 277 | 277 | e7a323db7d6e9285f4c82fb855b1023c63913037 | bigcode/the-stack | train |
15e023851765adceaf4d9073 | train | class | @dataclass
class Movie:
movie_id: int
title: str
original_title: str
rating: Optional[float]
duration: Optional[timedelta]
genres: str
countries: List[str]
directors: str
actors: str
synopsis: str
year: int
@property
def duration_str(self):
if self.duration i... | @dataclass
class Movie:
| movie_id: int
title: str
original_title: str
rating: Optional[float]
duration: Optional[timedelta]
genres: str
countries: List[str]
directors: str
actors: str
synopsis: str
year: int
@property
def duration_str(self):
if self.duration is not None:
... |
import logging
import re
from typing import List, Optional
import unicodedata
import backoff
import jmespath
import requests
from allocine import nationalities
__author__ = """Thibault Ducret"""
__email__ = 'hello@tducret.com'
__version__ = '0.0.12'
DEFAULT_DATE_FORMAT = '%Y-%m-%dT%H:%M:%S'
BASE_URL = 'http://api.... | 133 | 133 | 446 | 6 | 126 | tducret/allocine-python | allocine/__init__.py | Python | Movie | Movie | 31 | 92 | 31 | 32 | e6266343722fb97f7e5b2d1598fa40a68c15ea64 | bigcode/the-stack | train |
4a9d01933cc015b02098fc07 | train | class | class SingletonMeta(type):
_instance = None
def __call__(self, *args, **kwargs):
if self._instance is None:
self._instance = super().__call__(*args, **kwargs)
return self._instance
| class SingletonMeta(type):
| _instance = None
def __call__(self, *args, **kwargs):
if self._instance is None:
self._instance = super().__call__(*args, **kwargs)
return self._instance
| (movie_id)
if movie_info is None:
movie_info = self.__client.get_movie_info_by_id(movie_id).get('movie')
self.__movie_store[movie_id] = movie_info
return movie_info
# === Client to execute requests with Allociné APIs ===
class SingletonMeta(type):
| 64 | 64 | 52 | 5 | 58 | tducret/allocine-python | allocine/__init__.py | Python | SingletonMeta | SingletonMeta | 556 | 562 | 556 | 556 | 623ababc06455ff64f3d73f9e8558db65d4831e5 | bigcode/the-stack | train |
d6ed41ac2772e7fa5a4b7cc7 | train | function | def group_showtimes_per_schedule(showtimes: List[Showtime]):
showtimes_per_date = {}
available_dates = get_available_dates(showtimes=showtimes)
for available_date in available_dates:
showtimes_per_date[available_date] = get_showtimes_of_a_day(showtimes=showtimes, date=available_date)
grouped_sh... | def group_showtimes_per_schedule(showtimes: List[Showtime]):
| showtimes_per_date = {}
available_dates = get_available_dates(showtimes=showtimes)
for available_date in available_dates:
showtimes_per_date[available_date] = get_showtimes_of_a_day(showtimes=showtimes, date=available_date)
grouped_showtimes = {}
for available_date in available_dates:
... | Theaters_objects) """
return hash(self.theater_id)
# == Utils ==
def get_available_dates(showtimes: List[Showtime]):
dates = [s.date for s in showtimes]
return sorted(list(set(dates)))
def group_showtimes_per_schedule(showtimes: List[Showtime]):
| 63 | 64 | 152 | 14 | 49 | tducret/allocine-python | allocine/__init__.py | Python | group_showtimes_per_schedule | group_showtimes_per_schedule | 282 | 295 | 282 | 282 | 7278d9a73dc548aba294a108e12a8803518a49af | bigcode/the-stack | train |
fa4f6c4e6e11687e9cd51481 | train | function | def _strip_accents(s):
# https://stackoverflow.com/a/518232/8748757
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
| def _strip_accents(s):
# https://stackoverflow.com/a/518232/8748757
| return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
| _cleanhtml(raw_synopsis) # Remove HTML tags (ex: <span>)
synopsis = synopsis.replace('\xa0', ' ')
return unicodedata.normalize("NFKD", synopsis)
def _strip_accents(s):
# https://stackoverflow.com/a/518232/8748757
| 64 | 64 | 52 | 22 | 42 | tducret/allocine-python | allocine/__init__.py | Python | _strip_accents | _strip_accents | 646 | 649 | 646 | 647 | ca6111089cc1385ed9dc6cdbc67b1d602763e9e2 | bigcode/the-stack | train |
964ddd4ba6cb71b27dd2e351 | train | class | @dataclass
class Schedule:
date_time: datetime
@property
def date(self) -> date:
return self.date_time.date()
@property
def hour(self) -> datetime.time:
return self.date_time.time()
@property
def hour_str(self) -> str:
return self.date_time.strftime('%H:%M')
@... | @dataclass
class Schedule:
| date_time: datetime
@property
def date(self) -> date:
return self.date_time.date()
@property
def hour(self) -> datetime.time:
return self.date_time.time()
@property
def hour_str(self) -> str:
return self.date_time.strftime('%H:%M')
@property
def hour_short... | ):
return (self.movie_id, self.version) == (other.movie_id, other.version)
def __hash__(self):
""" This function allows us
to do a set(list_of_MovieVersion_objects) """
return hash((self.movie_id, self.version))
@dataclass
class Schedule:
| 64 | 64 | 170 | 6 | 58 | tducret/allocine-python | allocine/__init__.py | Python | Schedule | Schedule | 135 | 165 | 135 | 136 | c8feb6f9a815d2d7beb8fa498a68e8aa8d594903 | bigcode/the-stack | train |
200cc2b4b393b3885c3f925a | train | function | def build_weekly_schedule_str(schedule_list: List[Schedule]) -> str:
check_schedules_within_week(schedule_list)
_hours_hashmap = {} # ex: {16h: [Lun, Mar], 17h: [Lun], 17h30: [Lun]}
_grouped_date_hashmap = {} # ex: {[Lun]: [16h, 17h30], [Lun, Mar]: [17h]}
for s in schedule_list:
if _hours_h... | def build_weekly_schedule_str(schedule_list: List[Schedule]) -> str:
| check_schedules_within_week(schedule_list)
_hours_hashmap = {} # ex: {16h: [Lun, Mar], 17h: [Lun], 17h30: [Lun]}
_grouped_date_hashmap = {} # ex: {[Lun]: [16h, 17h30], [Lun, Mar]: [17h]}
for s in schedule_list:
if _hours_hashmap.get(s.hour) is None:
_hours_hashmap[s.hour] = []
... |
ex: {'key': [time(hour=12), time(hour=9)]} => timedelta(hour=9)
"""
weights = [__get_time_weight(t) for t in d[1]]
return min(weights)
def __get_time_weight(t: time) -> timedelta:
""" Return a timedelta taking into account night time.
Basically, it allows to sort a list of times 18h>2... | 186 | 186 | 623 | 16 | 169 | tducret/allocine-python | allocine/__init__.py | Python | build_weekly_schedule_str | build_weekly_schedule_str | 369 | 430 | 369 | 369 | 3202e94bb343f7072e636b1ba3261c8f763835aa | bigcode/the-stack | train |
0a12dc00d16a70014ccfb207 | train | class | class Allocine:
def __init__(self, base_url=BASE_URL):
self.__client = Client(base_url=base_url)
self.__movie_store = {} # Dict to store the movie info (and avoid useless requests)
def get_theater(self, theater_id: str):
ret = self.__client.get_showtimelist_by_theater_id(theater_id=the... | class Allocine:
| def __init__(self, base_url=BASE_URL):
self.__client = Client(base_url=base_url)
self.__movie_store = {} # Dict to store the movie info (and avoid useless requests)
def get_theater(self, theater_id: str):
ret = self.__client.get_showtimelist_by_theater_id(theater_id=theater_id)
... | day:
for hour, grouped_dates in hours_hashmap.items():
hour_str = get_hour_short_str(hour)
grouped_dates_str = create_weekdays_str(grouped_dates)
if grouped_dates_str:
weekly_schedule += f'{hour_str} ({grouped_dates_str}), '
else: # Available ever... | 256 | 256 | 1,075 | 4 | 251 | tducret/allocine-python | allocine/__init__.py | Python | Allocine | Allocine | 439 | 552 | 439 | 439 | d4c7c1198bd0938c44043a418e2e5de149ee9da8 | bigcode/the-stack | train |
01d105ae9b4d651935a7be77 | train | class | class Client(metaclass=SingletonMeta):
""" Client to process the requests with allocine APIs.
This is a singleton to avoid the creation of a new session for every theater.
"""
def __init__(self, base_url):
self.base_url = base_url
headers = {
'User-Agent': 'Mozilla/5.... | class Client(metaclass=SingletonMeta):
| """ Client to process the requests with allocine APIs.
This is a singleton to avoid the creation of a new session for every theater.
"""
def __init__(self, base_url):
self.base_url = base_url
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; \
... | showtimes
def get_movie_info(self, movie_id: int):
movie_info = self.__movie_store.get(movie_id)
if movie_info is None:
movie_info = self.__client.get_movie_info_by_id(movie_id).get('movie')
self.__movie_store[movie_id] = movie_info
return movie_info
# === Client ... | 152 | 152 | 507 | 9 | 142 | tducret/allocine-python | allocine/__init__.py | Python | Client | Client | 569 | 615 | 569 | 569 | 3f0d28253ed54ea1e78191a56d05dc96bd3acc62 | bigcode/the-stack | train |
43edaf71d6da524382653aab | train | function | def create_weekdays_str(dates: List[date]) -> str:
"""
Returns a compact string from a list of dates.
Examples:
- [0,1] -> 'Lun, Mar'
- [0,1,2,3,4] -> 'sf Sam, Dim'
- [0,1,2,3,4,5,6] -> '' # Everyday is empty string
- [0,2] -> 'Mer, Lun' # And not 'L... | def create_weekdays_str(dates: List[date]) -> str:
| """
Returns a compact string from a list of dates.
Examples:
- [0,1] -> 'Lun, Mar'
- [0,1,2,3,4] -> 'sf Sam, Dim'
- [0,1,2,3,4,5,6] -> '' # Everyday is empty string
- [0,2] -> 'Mer, Lun' # And not 'Lun, Mer' because we sort chrologically
"""
... | _date.weekday() == MONDAY and max_date.weekday() >= WEDNESDAY) \
or (min_date.weekday() == TUESDAY):
raise ValueError(
'Schedule list should not start before wednesday or end after tuesday')
return True
def create_weekdays_str(dates: List[date]) -> str:
| 73 | 73 | 246 | 15 | 57 | tducret/allocine-python | allocine/__init__.py | Python | create_weekdays_str | create_weekdays_str | 327 | 346 | 327 | 327 | 6a9ce942b4a898afe8fbd7a60d1166efc3f91e11 | bigcode/the-stack | train |
d35010e1a6a9ec48ffaa1137 | train | function | def __get_time_weight_in_list(d: dict) -> timedelta:
""" Returns the minimum time weight from the time list contained in the dict values
ex: {'key': [time(hour=12), time(hour=9)]} => timedelta(hour=9)
"""
weights = [__get_time_weight(t) for t in d[1]]
return min(weights)
| def __get_time_weight_in_list(d: dict) -> timedelta:
| """ Returns the minimum time weight from the time list contained in the dict values
ex: {'key': [time(hour=12), time(hour=9)]} => timedelta(hour=9)
"""
weights = [__get_time_weight(t) for t in d[1]]
return min(weights)
| d in week_days])
else:
missing_days = list(set(week_days).symmetric_difference(FULL_WEEK))
return 'sf {}'.format(', '.join([to_french_short_weekday(d) for d in missing_days]))
def __get_time_weight_in_list(d: dict) -> timedelta:
| 63 | 64 | 79 | 14 | 49 | tducret/allocine-python | allocine/__init__.py | Python | __get_time_weight_in_list | __get_time_weight_in_list | 349 | 354 | 349 | 349 | a8f5ecf717fa6a62f12db7c41e3258af47efd133 | bigcode/the-stack | train |
d5aa552cfadb47433adb6ad8 | train | class | @dataclass
class Theater:
theater_id: str
name: str
showtimes: List[Showtime]
address: str
zipcode: str
city: str
@property
def address_str(self):
address_str = f'{self.address}, ' if self.address else ''
address_str += f'{self.zipcode} {self.city}'
return addres... | @dataclass
class Theater:
| theater_id: str
name: str
showtimes: List[Showtime]
address: str
zipcode: str
city: str
@property
def address_str(self):
address_str = f'{self.address}, ' if self.address else ''
address_str += f'{self.zipcode} {self.city}'
return address_str
def get_showtim... | ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
return DAYS[weekday]
def get_french_month(month_number: int) -> str:
MONTHS = [
'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'
]
return MO... | 167 | 167 | 558 | 6 | 161 | tducret/allocine-python | allocine/__init__.py | Python | Theater | Theater | 207 | 273 | 207 | 208 | 6b8a4ed273e7a860107bff4a256f13b8e39911f8 | bigcode/the-stack | train |
a87edec3c98a5fda5a4cce71 | train | function | def _strfdelta(tdelta, fmt):
""" Format a timedelta object """
# Thanks to https://stackoverflow.com/questions/8906926
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d)
| def _strfdelta(tdelta, fmt):
| """ Format a timedelta object """
# Thanks to https://stackoverflow.com/questions/8906926
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d)
| (url=url)
def get_movie_info_by_id(self, movie_id: int):
url = (
f'{self.base_url}/movie?partner={PARTNER_KEY}&format=json&code={movie_id}'
)
return self._get(url=url)
def _strfdelta(tdelta, fmt):
| 64 | 64 | 82 | 10 | 54 | tducret/allocine-python | allocine/__init__.py | Python | _strfdelta | _strfdelta | 618 | 624 | 618 | 618 | 2334b09e2d408c7a7eb6067e1f0ece02d684b3c7 | bigcode/the-stack | train |
dc4cdea77d6db8b9c7bf6c0a | train | class | class Error503(Exception):
pass
| class Error503(Exception):
| pass
| requests with Allociné APIs ===
class SingletonMeta(type):
_instance = None
def __call__(self, *args, **kwargs):
if self._instance is None:
self._instance = super().__call__(*args, **kwargs)
return self._instance
class Error503(Exception):
| 64 | 64 | 8 | 5 | 58 | tducret/allocine-python | allocine/__init__.py | Python | Error503 | Error503 | 565 | 566 | 565 | 565 | af5b62421e0e2c1f6330ea6216ba1eb9e9fe4a80 | bigcode/the-stack | train |
5d038a44dbbdca86c07dab24 | train | function | def day_str(date: date) -> str:
return to_french_weekday(date.weekday())
| def day_str(date: date) -> str:
| return to_french_weekday(date.weekday())
| return hour.strftime('%-Hh%M').replace('h00', 'h')
@dataclass
class Showtime(Schedule):
movie: MovieVersion
def __str__(self):
return f'{self.date_str} : {self.movie}'
def day_str(date: date) -> str:
| 63 | 64 | 21 | 10 | 53 | tducret/allocine-python | allocine/__init__.py | Python | day_str | day_str | 182 | 183 | 182 | 182 | 5ccbca58aeae90e1251bad5e6f250e0e751f572f | bigcode/the-stack | train |
b7adf9284972a50f98fc9c4e | train | class | class PowerSpectrum(MultiPhaseMedium,BlobFactory): # pragma: no cover
def __init__(self, data=None, suffix='fluctuations', **kwargs):
"""
Initialize analysis object.
Parameters
----------
data : dict, str
Either a dictionary containing the entire history or the p... | class PowerSpectrum(MultiPhaseMedium,BlobFactory): # pragma: no cover
| def __init__(self, data=None, suffix='fluctuations', **kwargs):
"""
Initialize analysis object.
Parameters
----------
data : dict, str
Either a dictionary containing the entire history or the prefix
of the files containing the history/parameters.
... | import numpy as np
from ..util import labels
import matplotlib.pyplot as pl
from .Global21cm import Global21cm
from ..util.Misc import split_by_sign
from scipy.interpolate import interp1d
from ..physics.Constants import nu_0_mhz
from matplotlib.ticker import ScalarFormatter
from ..analysis.BlobFactory import BlobFactor... | 111 | 256 | 3,058 | 17 | 94 | mirochaj/ares | ares/analysis/PowerSpectrum.py | Python | PowerSpectrum | PowerSpectrum | 13 | 453 | 13 | 13 | c0638a240050fd01eecb214978aa879da20639dc | bigcode/the-stack | train |
33879946ed0195752980e9a5 | train | class | class Migration(migrations.Migration):
dependencies = [
('foodbot', '0005_auto_20170603_1715'),
]
operations = [
migrations.AlterField(
model_name='userinfo',
name='state',
field=models.IntegerField(default=0, null=True),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('foodbot', '0005_auto_20170603_1715'),
]
operations = [
migrations.AlterField(
model_name='userinfo',
name='state',
field=models.IntegerField(default=0, null=True),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-03 17:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 66 | 7 | 46 | surajpaib/HungerHero | foodbot/migrations/0006_auto_20170603_1716.py | Python | Migration | Migration | 8 | 20 | 8 | 9 | 03411316ae5a47bfd00a53c329119faa9a09d87a | bigcode/the-stack | train |
7882e5de29cb37c4992bb0c7 | train | class | class OCPDeployment:
def __init__(self):
"""
Constructor for OCPDeployment class
"""
self.pull_secret = {}
self.metadata = {}
self.deployment_platform = config.ENV_DATA['platform'].lower()
self.deployment_type = config.ENV_DATA['deployment_type'].lower()
... | class OCPDeployment:
| def __init__(self):
"""
Constructor for OCPDeployment class
"""
self.pull_secret = {}
self.metadata = {}
self.deployment_platform = config.ENV_DATA['platform'].lower()
self.deployment_type = config.ENV_DATA['deployment_type'].lower()
self.installer = s... | """
This module provides base class for OCP deployment.
"""
import logging
import os
import json
import pytest
import yaml
from ocs_ci.framework import config
from ocs_ci.ocs import constants
from ocs_ci.ocs.openshift_ops import OCP
from ocs_ci.utility import utils, templating, system
logger = logging.getLogger(__n... | 83 | 256 | 1,183 | 5 | 78 | gabriellasroman/ocs-ci | ocs_ci/deployment/ocp.py | Python | OCPDeployment | OCPDeployment | 20 | 182 | 20 | 20 | 411268f396779ebf2e47470d0dc4865e19098f92 | bigcode/the-stack | train |
0f8f256d7171524700da9e29 | train | function | def get_deps_info():
if not settings.EXCEPTION_HANDLING and settings.LINK_AS_CXX:
_deps_info['__cxa_begin_catch'] = ['__cxa_is_pointer_type']
_deps_info['__cxa_find_matching_catch'] = ['__cxa_can_catch']
_deps_info['__cxa_find_matching_catch_1'] = ['__cxa_can_catch']
_deps_info['__cxa_find_matching_ca... | def get_deps_info():
| if not settings.EXCEPTION_HANDLING and settings.LINK_AS_CXX:
_deps_info['__cxa_begin_catch'] = ['__cxa_is_pointer_type']
_deps_info['__cxa_find_matching_catch'] = ['__cxa_can_catch']
_deps_info['__cxa_find_matching_catch_1'] = ['__cxa_can_catch']
_deps_info['__cxa_find_matching_catch_2'] = ['__cxa_can... | 's
# dependency.
'setjmp': ['malloc', 'free', 'saveSetjmp', 'setThrew'],
'setprotoent': ['malloc'],
'syslog': ['malloc', 'ntohs', 'htons'],
'vsyslog': ['malloc', 'ntohs', 'htons'],
'timegm': ['malloc'],
'tzset': ['malloc'],
'uuid_compare': ['memcmp'],
'uuid_copy': ['memcpy'],
'wgpuBufferGetMappedRan... | 154 | 154 | 515 | 6 | 148 | xReveres/emscripten | tools/deps_info.py | Python | get_deps_info | get_deps_info | 196 | 220 | 196 | 196 | 3327dd421b92815604066bc8b07ec35714ad5094 | bigcode/the-stack | train |
037678ce7f2e5fcdf4e98649 | train | class | class Timer():
def __init__(self):
self._t0 = time.clock()
def elapsed(self):
return time.clock() - self._t0
def update(self):
self._t0 = time.clock()
| class Timer():
| def __init__(self):
self._t0 = time.clock()
def elapsed(self):
return time.clock() - self._t0
def update(self):
self._t0 = time.clock()
| if n == 0:
return self.fid
elif n == 1:
return self.name
else:
raise IndexError
r = TmpFile(fid, tfilename)
yield r
fid.close()
if not debug:
os.remove(tfilename)
class Timer():
| 64 | 64 | 49 | 3 | 61 | stpua/siconos | io/swig/io/mechanics_run.py | Python | Timer | Timer | 161 | 170 | 161 | 162 | b2345c91b2b1295c90fd9e5dda54d68e88f2c6b0 | bigcode/the-stack | train |
8e6acf601c1ec614991dfcb9 | train | function | def set_backend(b):
global backend
backend = b
setup_default_classes()
| def set_backend(b):
| global backend
backend = b
setup_default_classes()
| iconosConvexHull, SiconosContactor, SiconosContactorSet, \
SiconosMesh, SiconosHeightMap
# It is necessary to select a back-end, although currently only Bullet
# is supported for general objects.
backend = 'bullet'
def set_backend(b):
| 64 | 64 | 19 | 5 | 59 | stpua/siconos | io/swig/io/mechanics_run.py | Python | set_backend | set_backend | 46 | 49 | 46 | 46 | 2cfc723c68e5212b15da45863da383c6172eee81 | bigcode/the-stack | train |
d1fc03000879ec34ec10e9a3 | train | function | def quaternion_multiply(q1, q0):
w0, x0, y0, z0 = q0
w1, x1, y1, z1 = q1
return np.array([-x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
-x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
x1 * y0 - y1 * x0 + z1 * w0 + w1 * z... | def quaternion_multiply(q1, q0):
| w0, x0, y0, z0 = q0
w1, x1, y1, z1 = q1
return np.array([-x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
-x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0], dtype=np.float64)
| =[cos(angle / 2.), axis[0] * n, axis[1] * n, axis[2] * n]
else:
assert(len(orientation)==4)
# a given quaternion
ori=orientation
return ori
def quaternion_multiply(q1, q0):
| 64 | 64 | 152 | 10 | 53 | stpua/siconos | io/swig/io/mechanics_run.py | Python | quaternion_multiply | quaternion_multiply | 321 | 327 | 321 | 321 | 4e4eff1206a5bc6780c91c0c852d6062ebcd921f | bigcode/the-stack | train |
6bcdc8d91390e377a30c07b4 | train | class | class Quaternion():
def __init__(self, *args):
import vtk
self._vtkmath = vtk.vtkMath()
self._data = vtk.vtkQuaternion[float](*args)
def __mul__(self, q):
r = Quaternion()
self._vtkmath.MultiplyQuaternion(self._data, q._data, r._data)
return r
def __getitem... | class Quaternion():
| def __init__(self, *args):
import vtk
self._vtkmath = vtk.vtkMath()
self._data = vtk.vtkQuaternion[float](*args)
def __mul__(self, q):
r = Quaternion()
self._vtkmath.MultiplyQuaternion(self._data, q._data, r._data)
return r
def __getitem__(self, i):
... | ())
def file_of_str(filename, string):
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write(string)
class ... | 71 | 71 | 237 | 3 | 68 | stpua/siconos | io/swig/io/mechanics_run.py | Python | Quaternion | Quaternion | 268 | 297 | 268 | 269 | d2bccb0072d56fc3ede2615b043c8ecaf98e9f0c | bigcode/the-stack | train |
390b68bf9060bc6daecc43bd | train | function | def phi(q0, q1, q2, q3):
"""
Euler angle phi from quaternion.
"""
return atan2(2*(q0*q1+q2*q3), 1-2*(q1*q1+q2*q2))
| def phi(q0, q1, q2, q3):
| """
Euler angle phi from quaternion.
"""
return atan2(2*(q0*q1+q2*q3), 1-2*(q1*q1+q2*q2))
| 0 + y1 * w0 + z1 * x0 + w1 * y0,
x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0], dtype=np.float64)
def phi(q0, q1, q2, q3):
| 64 | 64 | 57 | 14 | 50 | stpua/siconos | io/swig/io/mechanics_run.py | Python | phi | phi | 331 | 335 | 331 | 331 | 0dd15abdbdf785b0efde6f27fed0796c579f93a8 | bigcode/the-stack | train |
5b654a4ecf5775e251426161 | train | function | def theta(q0, q1, q2, q3):
"""
Euler angle theta from quaternion.
"""
return asin(2*(q0*q2-q3*q1))
| def theta(q0, q1, q2, q3):
| """
Euler angle theta from quaternion.
"""
return asin(2*(q0*q2-q3*q1))
| , q2, q3):
"""
Euler angle phi from quaternion.
"""
return atan2(2*(q0*q1+q2*q3), 1-2*(q1*q1+q2*q2))
def theta(q0, q1, q2, q3):
| 64 | 64 | 40 | 14 | 50 | stpua/siconos | io/swig/io/mechanics_run.py | Python | theta | theta | 338 | 342 | 338 | 338 | 1d5e8d15daf4d343c3d9097136a62985233e42ce | bigcode/the-stack | train |
c7dd7cfbdfc89e94cca2c537 | train | function | @contextmanager
def tmpfile(suffix='', prefix='siconos_io', contents=None,
debug=False):
"""
A context manager for a named temporary file.
"""
(_, tfilename) = tempfile.mkstemp(suffix=suffix, prefix=prefix)
fid = open(tfilename, 'w')
if contents is not None:
fid.write(content... | @contextmanager
def tmpfile(suffix='', prefix='siconos_io', contents=None,
debug=False):
| """
A context manager for a named temporary file.
"""
(_, tfilename) = tempfile.mkstemp(suffix=suffix, prefix=prefix)
fid = open(tfilename, 'w')
if contents is not None:
fid.write(contents)
fid.flush()
class TmpFile:
def __init__(self, fid, name):
self.f... | getargvalues(stack()[1][0])[-3:]
posargs = args.pop(posname, [])
args.update(args.pop(kwname, []))
return args, posargs
@contextmanager
def tmpfile(suffix='', prefix='siconos_io', contents=None,
debug=False):
| 64 | 64 | 183 | 24 | 39 | stpua/siconos | io/swig/io/mechanics_run.py | Python | tmpfile | tmpfile | 127 | 158 | 127 | 129 | 9c4da38b61e2c57e69d56f8afbcad80fac6b5421 | bigcode/the-stack | train |
39eadd85b11c0a3d6fba1767 | train | function | def upgrade_io_format(filename):
with MechanicsHdf5(filename, mode='a') as io:
for instance_name in io.instances():
for contactor_instance_name in io.instances()[instance_name]:
contactor = io.instances()[instance_name][
contactor_instance_name]
... | def upgrade_io_format(filename):
| with MechanicsHdf5(filename, mode='a') as io:
for instance_name in io.instances():
for contactor_instance_name in io.instances()[instance_name]:
contactor = io.instances()[instance_name][
contactor_instance_name]
if 'name' in contactor.attrs:
... | =(None, nbcolumns),
chunks=[None,(4000,nbcolumns)][comp],
compression=[None,'gzip'][comp],
compression_opts=[None,9][comp])
#
# misc fixes
#
# fix ctr.'name' in old hdf5 files
#
def upgrade_io_format(filename):
| 64 | 64 | 111 | 6 | 58 | stpua/siconos | io/swig/io/mechanics_run.py | Python | upgrade_io_format | upgrade_io_format | 235 | 248 | 235 | 236 | c614a3e8762087ac64a718d27a8a16ef61bb78b2 | bigcode/the-stack | train |
3953b5b816c3606461032603 | train | function | def setup_default_classes():
global default_manager_class
global default_simulation_class
global default_body_class
global use_bullet
default_simulation_class = TimeStepping
default_body_class = BodyDS
if backend == 'bullet':
def m(options):
if options is None:
... | def setup_default_classes():
| global default_manager_class
global default_simulation_class
global default_body_class
global use_bullet
default_simulation_class = TimeStepping
default_body_class = BodyDS
if backend == 'bullet':
def m(options):
if options is None:
options = SiconosBullet... |
# OCC imports
try:
from siconos.mechanics import occ
have_occ = True
except:
have_occ = False
### Configuration
default_manager_class = None
default_simulation_class = None
default_body_class = None
use_bullet = False
def setup_default_classes():
| 64 | 64 | 152 | 5 | 58 | stpua/siconos | io/swig/io/mechanics_run.py | Python | setup_default_classes | setup_default_classes | 77 | 95 | 77 | 77 | 124c31c8f17ab511638ba53d3d8c2e0e28b97a87 | bigcode/the-stack | train |
19da1a230846ffa0e5614de8 | train | function | def group(h, name, must_exist=True):
try:
return h[name]
except KeyError:
if must_exist:
return h.create_group(name)
else:
try:
return h.create_group(name)
except ValueError:
# could not create group, return None
... | def group(h, name, must_exist=True):
| try:
return h[name]
except KeyError:
if must_exist:
return h.create_group(name)
else:
try:
return h.create_group(name)
except ValueError:
# could not create group, return None
# (file is probably in read-... | (obj):
"""returns an unique object identifier"""
return obj.__hash__()
def apply_gravity(body):
g = constants.g
weight = [0, 0, - body.scalarMass() * g]
body.setFExtPtr(weight)
def group(h, name, must_exist=True):
| 64 | 64 | 78 | 10 | 54 | stpua/siconos | io/swig/io/mechanics_run.py | Python | group | group | 204 | 216 | 204 | 204 | 8e12109ac1c2fd3f8253f668556aa068634632f6 | bigcode/the-stack | train |
ec4a26cf910656e217af811e | train | class | class ShapeCollection():
"""
Instantiation of added contact shapes
"""
def __init__(self, io, collision_margin=0.04):
self._io = io
self._shapes = dict()
self._tri = dict()
self._primitive = {'Sphere': SiconosSphere,
'Box': SiconosBox,
... | class ShapeCollection():
| """
Instantiation of added contact shapes
"""
def __init__(self, io, collision_margin=0.04):
self._io = io
self._shapes = dict()
self._tri = dict()
self._primitive = {'Sphere': SiconosSphere,
'Box': SiconosBox,
'Cylin... | p[1]
apoints[2, i] = p[2]
if scale is not None:
apoints *= scale
aindices = np.empty(num_triangles*3, dtype=np.int)
for i in range(0, num_triangles):
c = polydata.GetCell(i)
aindices[i*3 + 0] = c.GetPointIds().GetId(0)
aindices[i*3 ... | 256 | 256 | 2,245 | 4 | 251 | stpua/siconos | io/swig/io/mechanics_run.py | Python | ShapeCollection | ShapeCollection | 411 | 681 | 411 | 412 | 54213bf1abc869fb4ca2f1ae4258687a2d64514d | bigcode/the-stack | train |
fab2dcec6bdf57ece4d1965f | train | function | def log(fun, with_timer=False):
if with_timer:
t = Timer()
def logged(*args):
t.update()
print('{0} ...'.format(fun.__name__), end='')
fun(*args)
print('..... {0} s'.format(t.elapsed()))
return logged
else:
def silent(*args):
... | def log(fun, with_timer=False):
| if with_timer:
t = Timer()
def logged(*args):
t.update()
print('{0} ...'.format(fun.__name__), end='')
fun(*args)
print('..... {0} s'.format(t.elapsed()))
return logged
else:
def silent(*args):
fun(*args)
return... | = time.clock()
def elapsed(self):
return time.clock() - self._t0
def update(self):
self._t0 = time.clock()
def warn(msg):
sys.stderr.write('{0}: {1}'.format(sys.argv[0], msg))
def log(fun, with_timer=False):
| 64 | 64 | 82 | 8 | 56 | stpua/siconos | io/swig/io/mechanics_run.py | Python | log | log | 177 | 190 | 177 | 177 | 65c94f6a4c0c2e75b4362c00a709cbac2c59dbf5 | bigcode/the-stack | train |
5f5ff8d0caec7e4ca4fb571c | train | function | def str_of_file(filename):
with open(filename, 'r') as f:
return str(f.read())
| def str_of_file(filename):
| with open(filename, 'r') as f:
return str(f.read())
| contactor_instance_name]
if 'name' in contactor.attrs:
warn("""
contactor {0} attribute 'name': renamed in 'shape_name'
""")
contactor.attrs['shape_name'] = contactor['name']
del contactor['name']
def str... | 64 | 64 | 23 | 6 | 58 | stpua/siconos | io/swig/io/mechanics_run.py | Python | str_of_file | str_of_file | 251 | 253 | 251 | 251 | 42ab65a2f5afc1492157d0a7e2aa670f6ce52633 | bigcode/the-stack | train |
eff4a888e5caf626a1c7b5ff | train | function | def warn(msg):
sys.stderr.write('{0}: {1}'.format(sys.argv[0], msg))
| def warn(msg):
| sys.stderr.write('{0}: {1}'.format(sys.argv[0], msg))
| if not debug:
os.remove(tfilename)
class Timer():
def __init__(self):
self._t0 = time.clock()
def elapsed(self):
return time.clock() - self._t0
def update(self):
self._t0 = time.clock()
def warn(msg):
| 64 | 64 | 22 | 4 | 60 | stpua/siconos | io/swig/io/mechanics_run.py | Python | warn | warn | 173 | 174 | 173 | 173 | 71d7bb5d725fe68104570177059100439d9f46e8 | bigcode/the-stack | train |
b4f44bf20404b20de6b6af77 | train | function | def file_of_str(filename, string):
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write(string)
| def file_of_str(filename, string):
| if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write(string)
| 'name': renamed in 'shape_name'
""")
contactor.attrs['shape_name'] = contactor['name']
del contactor['name']
def str_of_file(filename):
with open(filename, 'r') as f:
return str(f.read())
def file_of_str(filename, string):
| 64 | 64 | 67 | 8 | 56 | stpua/siconos | io/swig/io/mechanics_run.py | Python | file_of_str | file_of_str | 256 | 265 | 256 | 256 | 861e58be4d7c60128cc1e72d44e09da787b5b4f2 | bigcode/the-stack | train |
a521f84f31e8ff35738e5297 | train | function | def apply_gravity(body):
g = constants.g
weight = [0, 0, - body.scalarMass() * g]
body.setFExtPtr(weight)
| def apply_gravity(body):
| g = constants.g
weight = [0, 0, - body.scalarMass() * g]
body.setFExtPtr(weight)
| (*args)
print('..... {0} s'.format(t.elapsed()))
return logged
else:
def silent(*args):
fun(*args)
return silent
def object_id(obj):
"""returns an unique object identifier"""
return obj.__hash__()
def apply_gravity(body):
| 63 | 64 | 37 | 6 | 58 | stpua/siconos | io/swig/io/mechanics_run.py | Python | apply_gravity | apply_gravity | 198 | 201 | 198 | 198 | 8b05050a09a271d8ac9b84c6baeaefa371201593 | bigcode/the-stack | train |
5289db84a835f6c13158843d | train | function | def psi(q0, q1, q2, q3):
"""
Euler angle psi from quaternion.
"""
return atan2(2*(q0*q3+q1*q2), 1-2*(q2*q2+q3*q3))
| def psi(q0, q1, q2, q3):
| """
Euler angle psi from quaternion.
"""
return atan2(2*(q0*q3+q1*q2), 1-2*(q2*q2+q3*q3))
| q1*q1+q2*q2))
def theta(q0, q1, q2, q3):
"""
Euler angle theta from quaternion.
"""
return asin(2*(q0*q2-q3*q1))
def psi(q0, q1, q2, q3):
| 64 | 64 | 57 | 14 | 50 | stpua/siconos | io/swig/io/mechanics_run.py | Python | psi | psi | 345 | 349 | 345 | 345 | 83dda983e389da437fcebd9dcd8038df2bee8ec4 | bigcode/the-stack | train |
f2dd2798416b723717825178 | train | function | def arguments():
"""Returns tuple containing dictionary of calling function's
named arguments and a list of calling function's unnamed
positional arguments.
"""
from inspect import getargvalues, stack
posname, kwname, args = getargvalues(stack()[1][0])[-3:]
posargs = args.pop(posname, [])
... | def arguments():
| """Returns tuple containing dictionary of calling function's
named arguments and a list of calling function's unnamed
positional arguments.
"""
from inspect import getargvalues, stack
posname, kwname, args = getargvalues(stack()[1][0])[-3:]
posargs = args.pop(posname, [])
args.update(arg... | 'PrismaticJointR': (0, 1),
'CylindricalJointR': (1, 1),
'FixedJointR': (0, 0),
}
### Utility functions
def floatv(v):
return [float(x) for x in v]
def arguments():
| 64 | 64 | 91 | 3 | 61 | stpua/siconos | io/swig/io/mechanics_run.py | Python | arguments | arguments | 115 | 124 | 115 | 115 | 220b4ffed9c92921a4ade0310799472b7cf303cf | bigcode/the-stack | train |
62ef131a24ef577aea29c641 | train | function | def data(h, name, nbcolumns, use_compression=False):
try:
return h[name]
except KeyError:
comp = use_compression and nbcolumns > 0
return h.create_dataset(name, (0, nbcolumns),
maxshape=(None, nbcolumns),
chunks=[None,(4000,... | def data(h, name, nbcolumns, use_compression=False):
| try:
return h[name]
except KeyError:
comp = use_compression and nbcolumns > 0
return h.create_dataset(name, (0, nbcolumns),
maxshape=(None, nbcolumns),
chunks=[None,(4000,nbcolumns)][comp],
co... | return h.create_group(name)
else:
try:
return h.create_group(name)
except ValueError:
# could not create group, return None
# (file is probably in read-only mode)
return None
def data(h, name, nbcolumns, use_comp... | 64 | 64 | 94 | 14 | 49 | stpua/siconos | io/swig/io/mechanics_run.py | Python | data | data | 218 | 227 | 218 | 218 | 8ecd7a84df72c383bdd1454e7e146d2a23130a27 | bigcode/the-stack | train |
21992040a5a902ac26bdcb34 | train | function | def floatv(v):
return [float(x) for x in v]
| def floatv(v):
| return [float(x) for x in v]
| 0),
'PivotJointR': (1, 1),
'PrismaticJointR': (0, 1),
'CylindricalJointR': (1, 1),
'FixedJointR': (0, 0),
}
### Utility functions
def floatv(v):
| 64 | 64 | 16 | 5 | 58 | stpua/siconos | io/swig/io/mechanics_run.py | Python | floatv | floatv | 111 | 112 | 111 | 111 | 194599fd56bb1655aea70a8196dc51c1462e24d3 | bigcode/the-stack | train |
c57fb11cda96a0df61bd13a0 | train | function | def quaternion_get(orientation):
"""
Get quaternion from orientation
"""
if len(orientation) == 2:
# axis + angle
axis=orientation[0]
assert len(axis) == 3
angle=orientation[1]
assert type(angle) is float
n=sin(angle / 2.) / np.lina... | def quaternion_get(orientation):
| """
Get quaternion from orientation
"""
if len(orientation) == 2:
# axis + angle
axis=orientation[0]
assert len(axis) == 3
angle=orientation[1]
assert type(angle) is float
n=sin(angle / 2.) / np.linalg.norm(axis)
ori=[c... | [rv[1], rv[2], rv[3]]
def axisAngle(self):
r = [0, 0, 0]
a = self._data.GetRotationAngleAndAxis(r)
return r, a
#
# fix orientation -> rotation ?
#
def quaternion_get(orientation):
| 64 | 64 | 134 | 6 | 58 | stpua/siconos | io/swig/io/mechanics_run.py | Python | quaternion_get | quaternion_get | 302 | 319 | 302 | 302 | c6db1e87339e08cea44ae4a40902b7b05682571f | bigcode/the-stack | train |
ab715fb3cb00db4b90208431 | train | function | def object_id(obj):
"""returns an unique object identifier"""
return obj.__hash__()
| def object_id(obj):
| """returns an unique object identifier"""
return obj.__hash__()
| ):
t.update()
print('{0} ...'.format(fun.__name__), end='')
fun(*args)
print('..... {0} s'.format(t.elapsed()))
return logged
else:
def silent(*args):
fun(*args)
return silent
def object_id(obj):
| 64 | 64 | 19 | 5 | 58 | stpua/siconos | io/swig/io/mechanics_run.py | Python | object_id | object_id | 193 | 195 | 193 | 193 | c9343a392c2630a9eff4168e447455e069458cae | bigcode/the-stack | train |
4e1055cb90ea1f3ae670fa13 | train | class | class MechanicsHdf5Runner(siconos.io.mechanics_hdf5.MechanicsHdf5):
"""a Hdf5 context manager reads at instantiation the translations and
orientations of collision objects from hdf5 file
It provides functions to output translations and orientations in
the same file during simulation (output i... | class MechanicsHdf5Runner(siconos.io.mechanics_hdf5.MechanicsHdf5):
| """a Hdf5 context manager reads at instantiation the translations and
orientations of collision objects from hdf5 file
It provides functions to output translations and orientations in
the same file during simulation (output is done by default in
pos.dat)
with:
time : fl... | [shape_name] = box
box.setInsideMargin(
self.shape(shape_name).attrs.get('insideMargin',
min(attrs)*0.02))
box.setOutsideMargin(
self.shape(shape_name).attrs.get('outsideMargi... | 256 | 256 | 12,257 | 21 | 235 | stpua/siconos | io/swig/io/mechanics_run.py | Python | MechanicsHdf5Runner | MechanicsHdf5Runner | 684 | 2,088 | 684 | 685 | 33bbf01b67a670a579abefaf64a1a34c6b186b0f | bigcode/the-stack | train |
71ea7d5d24ab3ddea5f14563 | train | function | def load_siconos_mesh(shape_filename, scale=None):
"""
loads a vtk .vtp file and returns a SiconosMesh shape
WARNING triangles cells assumed!
"""
import vtk
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName(shape_filename)
reader.Update()
polydata = reader.GetOutput()
poin... | def load_siconos_mesh(shape_filename, scale=None):
| """
loads a vtk .vtp file and returns a SiconosMesh shape
WARNING triangles cells assumed!
"""
import vtk
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName(shape_filename)
reader.Update()
polydata = reader.GetOutput()
points = polydata.GetPoints().GetData()
num_points ... | """
Euler angle theta from quaternion.
"""
return asin(2*(q0*q2-q3*q1))
def psi(q0, q1, q2, q3):
"""
Euler angle psi from quaternion.
"""
return atan2(2*(q0*q3+q1*q2), 1-2*(q2*q2+q3*q3))
# vectorized versions
phiv = np.vectorize(phi)
thetav = np.vectorize(theta)
psiv = np.vectorize(psi)
... | 133 | 133 | 446 | 12 | 121 | stpua/siconos | io/swig/io/mechanics_run.py | Python | load_siconos_mesh | load_siconos_mesh | 360 | 409 | 360 | 360 | d62b64bff7d265c2bfd2a30c1f7ba03c531c7384 | bigcode/the-stack | train |
0380f2ce75af13340dbbbeaf | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_comments_with_semicolon():
s = """--test ;
select 1;
"""
with StringIO(s) as f:
itr = split_statements(f, remove_comments=False)
assert next(itr) == (
"--test ;\n"
"select 1;... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_comments_with_semicolon():
| s = """--test ;
select 1;
"""
with StringIO(s) as f:
itr = split_statements(f, remove_comments=False)
assert next(itr) == (
"--test ;\n"
"select 1;", False
)
with pytest.raises(StopIteration):
next(itr)
| "select /*another test comments*/ 1; -- test comment 2", False)
assert next(itr) == ("-- test comment 3\nselect 2;", False)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_comments_with_semicolon():
| 64 | 64 | 97 | 26 | 38 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_comments_with_semicolon | test_comments_with_semicolon | 460 | 472 | 460 | 461 | 69557debea87d303897887d53842ebec8418c5be | bigcode/the-stack | train |
e334e38cbbbb253ff9c68f76 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_quotes():
s = "select 'hello', 1; -- test comment\nselect 23,'hello"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == (
"select 'hello', 1; -- test comment", False)
... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_quotes():
| s = "select 'hello', 1; -- test comment\nselect 23,'hello"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == (
"select 'hello', 1; -- test comment", False)
assert next(itr) == ("select 23,'hello", False)
with pytest.raises(StopIteration):
... | :
itr = split_statements(f)
assert next(itr) == ("select /* test\n"
" continued comments 1\n"
" continued comments 2\n"
" */ 1; -- test comment", False)
assert next(itr) == ("select 23;", False)
... | 201 | 201 | 673 | 23 | 178 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_quotes | test_quotes | 176 | 245 | 176 | 177 | 39236a7a762bf8f0e1f1459b6d96698f360ead75 | bigcode/the-stack | train |
22d1b4d2f2d44d075ae17894 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_delimiter():
"""Copy of test_sql_with_commands but with an unconventional sql_delimiter.
This test should not only verify that a random delimiter splits SQL commands correctly, but
also that semi colon get... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_delimiter():
| """Copy of test_sql_with_commands but with an unconventional sql_delimiter.
This test should not only verify that a random delimiter splits SQL commands correctly, but
also that semi colon gets added for the split statements instead of the reserved custom keywords.
Since this is a generator function t... | 1 'Snowflake\\'s 1';
SELECT 2 'Snowflake\\'s 2'
"""
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == ("SELECT 1 'Snowflake\\'s 1';", False)
assert next(itr) == ("SELECT 2 'Snowflake\\'s 2'", False)
@pytest.mark.skipif(split_statements is None, reason="No split_statements... | 111 | 111 | 372 | 25 | 86 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_sql_delimiter | test_sql_delimiter | 543 | 574 | 543 | 544 | 572338716abad1fbfa0b1ba4017311df97a32ae1 | bigcode/the-stack | train |
63daca8fc366ed3a1f9447ac | train | function | @pytest.mark.skipif(split_statements is None or SQLDelimiter is None,
reason="No split_statements or SQLDelimiter is available")
@pytest.mark.parametrize('sql, delimiter, split_stmnts', [
("select 1 as a__b __ select 1", '__', ['select 1 as a__b ;', 'select 1']),
("select 1 as a__b/", '/', [... | @pytest.mark.skipif(split_statements is None or SQLDelimiter is None,
reason="No split_statements or SQLDelimiter is available")
@pytest.mark.parametrize('sql, delimiter, split_stmnts', [
("select 1 as a__b __ select 1", '__', ['select 1 as a__b ;', 'select 1']),
("select 1 as a__b/", '/', [... | """This tests various smaller sql splitting pitfalls."""
with StringIO(sql) as sqlio:
statements = list([s[0] for s in split_statements(sqlio, delimiter=SQLDelimiter(delimiter))])
assert statements == split_stmnts
| @pytest.mark.skipif(split_statements is None or SQLDelimiter is None,
reason="No split_statements or SQLDelimiter is available")
@pytest.mark.parametrize('sql, delimiter, split_stmnts', [
("select 1 as a__b __ select 1", '__', ['select 1 as a__b ;', 'select 1']),
("select 1 as a__b/", '/', [... | 237 | 87 | 292 | 237 | 0 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_sql_splitting_various | test_sql_splitting_various | 589 | 605 | 589 | 601 | 22dd18316a0b729cd57322fbc1c82e783fc7af68 | bigcode/the-stack | train |
7bab9dfd00a132bae7c02e63 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiline_double_dollar_experssion_with_removed_comments():
s = """CREATE FUNCTION mean(a FLOAT, b FLOAT)
RETURNS FLOAT LANGUAGE JAVASCRIPT AS $$
var c = a + b;
return(c / 2);
$$;"""
with StringIO(s) as f:
... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiline_double_dollar_experssion_with_removed_comments():
| s = """CREATE FUNCTION mean(a FLOAT, b FLOAT)
RETURNS FLOAT LANGUAGE JAVASCRIPT AS $$
var c = a + b;
return(c / 2);
$$;"""
with StringIO(s) as f:
itr = split_statements(f, remove_comments=True)
assert next(itr) == (
"CREATE FUNCTION mean(a FLOAT, b FLOAT)\n"
" RE... | (f, remove_comments=True)
assert next(itr) == (
"INSERT INTO foo VALUES (\n\n10);", False
)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiline_double_dollar_experssion_with_removed_comments():
| 64 | 64 | 156 | 34 | 30 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_multiline_double_dollar_experssion_with_removed_comments | test_multiline_double_dollar_experssion_with_removed_comments | 516 | 528 | 516 | 517 | f7ad313710507d70f3b7fb397b6a574c88f0019c | bigcode/the-stack | train |
0f5d4efb30c1f91822723914 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_splitting_tokenization():
"""This tests that sql_delimiter is token sensitive."""
raw_sql = "select 123 as asd"
for c in set(raw_sql.replace(' ', '')):
sql = raw_sql + ' ' + c + ' ' + raw_sql
... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_splitting_tokenization():
| """This tests that sql_delimiter is token sensitive."""
raw_sql = "select 123 as asd"
for c in set(raw_sql.replace(' ', '')):
sql = raw_sql + ' ' + c + ' ' + raw_sql
with StringIO(sql) as sqlio:
s = split_statements(sqlio, delimiter=SQLDelimiter(c))
assert next(s)[0] ... | ("drop view if exists aaa ;", False)
assert next(itr) == ("show tables", False)
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_splitting_tokenization():
| 64 | 64 | 131 | 28 | 36 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_sql_splitting_tokenization | test_sql_splitting_tokenization | 577 | 586 | 577 | 578 | 662bc8ffc8d4461c458ae245bd772bce3327202e | bigcode/the-stack | train |
f5c30a24ca24a2fd201b646f | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_backslash_quote_escape():
s = """
SELECT 1 'Snowflake\\'s 1';
SELECT 2 'Snowflake\\'s 2'
"""
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == ("SELECT 1 'Snowflake\\'s 1';", Fals... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_backslash_quote_escape():
| s = """
SELECT 1 'Snowflake\\'s 1';
SELECT 2 'Snowflake\\'s 2'
"""
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == ("SELECT 1 'Snowflake\\'s 1';", False)
assert next(itr) == ("SELECT 2 'Snowflake\\'s 2'", False)
| " RETURNS FLOAT LANGUAGE JAVASCRIPT AS $$\n"
" var c = a + b;\n return(c / 2);\n $$;", False)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_backslash_quote_escape():
| 64 | 64 | 117 | 26 | 38 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_backslash_quote_escape | test_backslash_quote_escape | 531 | 540 | 531 | 532 | d9a17deb0ae1ea7b02f9c9519a566c76ff96e0e5 | bigcode/the-stack | train |
49d4c6eeba0f060ec7a6d2d8 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_simple_sql():
with StringIO("show tables") as f:
itr = split_statements(f)
assert next(itr) == ('show tables', False)
with pytest.raises(StopIteration):
next(itr)
with StringIO(... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_simple_sql():
| with StringIO("show tables") as f:
itr = split_statements(f)
assert next(itr) == ('show tables', False)
with pytest.raises(StopIteration):
next(itr)
with StringIO("show tables;") as f:
itr = split_statements(f)
assert next(itr) == ('show tables;', False)
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2020 Snowflake Computing Inc. All right reserved.
#
from io import StringIO
import pytest
try:
from snowflake.connector.util_text import split_statements
except ImportError:
split_statements = None
try:
from snowflake.connector.util_te... | 117 | 142 | 475 | 24 | 92 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_simple_sql | test_simple_sql | 22 | 73 | 22 | 23 | 43575eaf5c56263cb331bd0fe0b562ae2998c8ea | bigcode/the-stack | train |
1f90651d07821c87a8ca41d8 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_quotes_in_comments():
s = "select 'hello'; -- test comment 'hello2' in comment\n/* comment 'quote'*/ select true\n"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == (
... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_quotes_in_comments():
| s = "select 'hello'; -- test comment 'hello2' in comment\n/* comment 'quote'*/ select true\n"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == (
"select 'hello'; -- test comment 'hello2' in comment", False)
assert next(itr) == (
"/* comment 'qu... | ''\n', 1;", False)
assert next(itr) == ("select \"23,'','hello\"", False)
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_quotes_in_comments():
| 64 | 64 | 130 | 25 | 39 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_quotes_in_comments | test_quotes_in_comments | 248 | 258 | 248 | 249 | dafb65a51e002bdf45f4ca91696cdc9c56a6efdb | bigcode/the-stack | train |
504788cdb6eda35b5ef7b5dd | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_backslash():
"""Tests backslash in a literal.
Notes:
The backslash is escaped in a Python string literal. Double backslashes in a string literal represents a
single backslash.
"""
s = "sele... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_backslash():
| """Tests backslash in a literal.
Notes:
The backslash is escaped in a Python string literal. Double backslashes in a string literal represents a
single backslash.
"""
s = "select 'hello\\\\', 1; -- test comment\nselect 23,'\nhello"
with StringIO(s) as f:
itr = split_stateme... | test comment 'hello2' in comment", False)
assert next(itr) == (
"/* comment 'quote'*/ select true", False)
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_backslash():
| 69 | 69 | 231 | 24 | 45 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_backslash | test_backslash | 261 | 283 | 261 | 262 | 136a932c6f20fc373cb0f084a1527197e2848186 | bigcode/the-stack | train |
68473a89a3cf4f2c88ff2b9d | train | function | def test_space_before_put():
with StringIO("""
-- sample data uploads
PUT file:///tmp/data.txt @%ab;
SELECT 1; /* 134 */ select /* 567*/ 345;>
GET @%bcd file:///tmp/aaa.txt;
""") as f:
itr = split_statements(f)
assert next(itr) == ("""-- sample data uploads
PUT file:///tmp/data.txt @%ab;""",... | def test_space_before_put():
| with StringIO("""
-- sample data uploads
PUT file:///tmp/data.txt @%ab;
SELECT 1; /* 134 */ select /* 567*/ 345;>
GET @%bcd file:///tmp/aaa.txt;
""") as f:
itr = split_statements(f)
assert next(itr) == ("""-- sample data uploads
PUT file:///tmp/data.txt @%ab;""", True)
assert next(it... | assert next(itr) == ("copy into a;", False)
assert next(itr) == ("select * from a;", False)
assert next(itr) == ("drop table if exists a;", False)
with pytest.raises(StopIteration):
next(itr)
def test_space_before_put():
| 64 | 64 | 179 | 6 | 58 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_space_before_put | test_space_before_put | 414 | 428 | 414 | 414 | f62f9b336ee5b35ed84898e190e9603dcee3bc29 | bigcode/the-stack | train |
508a149f55d960836a548b25 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_with_commands():
with StringIO("""create or replace view aaa
as select * from
LINEITEM limit 1000;
!spool $outfile
show views like 'AAA';
!spool off
drop view if exists aaa;
show tables""") as f:
it... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_with_commands():
| with StringIO("""create or replace view aaa
as select * from
LINEITEM limit 1000;
!spool $outfile
show views like 'AAA';
!spool off
drop view if exists aaa;
show tables""") as f:
itr = split_statements(f)
assert next(itr) == ("""create or replace view aaa
as select * from
LINEITEM li... | .gz';", False)
assert next(itr) == ("list @~;", False)
# last raises StopIteration
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_with_commands():
| 64 | 64 | 213 | 25 | 39 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_sql_with_commands | test_sql_with_commands | 367 | 388 | 367 | 368 | a9f383d72883d42e50f5ec169a56a0dc9767f602 | bigcode/the-stack | train |
a147a7db78e3e1a1398edc27 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiple_comments():
s = """--- test comment 1
select /*another test comments*/ 1; -- test comment 2
-- test comment 3
select 2;
"""
with StringIO(s) as f:
itr = split_statements(f, remove_comments=False)
... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiple_comments():
| s = """--- test comment 1
select /*another test comments*/ 1; -- test comment 2
-- test comment 3
select 2;
"""
with StringIO(s) as f:
itr = split_statements(f, remove_comments=False)
assert next(itr) == (
"--- test comment 1\n"
"select /*another test comments*/ 1; -- tes... | ;""", False)
assert next(itr) == ("""-- tail comment1
-- tail comment2""", None)
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiple_comments():
| 64 | 64 | 136 | 24 | 40 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_multiple_comments | test_multiple_comments | 445 | 457 | 445 | 446 | 3b85185dc41e73e05b03cd0a8e92a926fcd54b45 | bigcode/the-stack | train |
426a074aeb017c04a1e78d3c | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_file_with_slash_star():
s = "put file:///tmp/* @%tmp;\nls @%tmp;"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == ("put file:///tmp/* @%tmp;", True)
assert next(itr) ==... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_file_with_slash_star():
| s = "put file:///tmp/* @%tmp;\nls @%tmp;"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == ("put file:///tmp/* @%tmp;", True)
assert next(itr) == ("ls @%tmp;", False)
with pytest.raises(StopIteration):
next(itr)
with StringIO(s) as f:
... | .skipif(split_statements is None, reason="No split_statements is available")
def test_backslash():
"""Tests backslash in a literal.
Notes:
The backslash is escaped in a Python string literal. Double backslashes in a string literal represents a
single backslash.
"""
s = "select 'hello\\\... | 256 | 256 | 856 | 27 | 229 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_file_with_slash_star | test_file_with_slash_star | 286 | 364 | 286 | 287 | 9a97a653c3a1afc0818a8207d638b3c16073aa13 | bigcode/the-stack | train |
55e53fac2190bfa55e3ac2bc | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_empty_statement():
with StringIO("""select 1;
-- tail comment1
-- tail comment2
""") as f:
itr = split_statements(f)
assert next(itr) == ("""select 1;""", False)
assert next(itr) == ("""-- tail ... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_empty_statement():
| with StringIO("""select 1;
-- tail comment1
-- tail comment2
""") as f:
itr = split_statements(f)
assert next(itr) == ("""select 1;""", False)
assert next(itr) == ("""-- tail comment1
-- tail comment2""", None)
with pytest.raises(StopIteration):
next(itr)
| False)
assert next(itr) == ("""GET @%bcd file:///tmp/aaa.txt;""", True)
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_empty_statement():
| 64 | 64 | 108 | 24 | 40 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_empty_statement | test_empty_statement | 431 | 442 | 431 | 432 | a5731b61b7b3bada8721e2f26f1f205c8cc86b9c | bigcode/the-stack | train |
bd6bc1102107309420dac371 | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_comment_in_values():
"""SNOW-51297: SnowSQL -o remove_comments=True breaks the query."""
# no space before a comment
s = """INSERT INTO foo
VALUES (/*TIMEOUT*/ 10);"""
with StringIO(s) as f:
itr = s... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_comment_in_values():
| """SNOW-51297: SnowSQL -o remove_comments=True breaks the query."""
# no space before a comment
s = """INSERT INTO foo
VALUES (/*TIMEOUT*/ 10);"""
with StringIO(s) as f:
itr = split_statements(f, remove_comments=True)
assert next(itr) == (
"INSERT INTO foo\nVALUES ( 10);", Fa... | icolon():
s = """--test ;
select 1;
"""
with StringIO(s) as f:
itr = split_statements(f, remove_comments=False)
assert next(itr) == (
"--test ;\n"
"select 1;", False
)
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_state... | 98 | 98 | 328 | 25 | 73 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_comment_in_values | test_comment_in_values | 475 | 513 | 475 | 476 | 10c6a8f63e5e998d073059643a19b16f17c2f58b | bigcode/the-stack | train |
c9e613d04f812924f4c63c4f | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiple_line_sql():
s = "select /* test */ 1; -- test comment\nselect 23;"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == (
('select /* test */ 1; -- test comment... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_multiple_line_sql():
| s = "select /* test */ 1; -- test comment\nselect 23;"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == (
('select /* test */ 1; -- test comment', False))
assert next(itr) == ('select 23;', False)
with pytest.raises(StopIteration):
nex... | itr)
s = "select 1; -- test"
with StringIO(s) as f:
itr = split_statements(f)
assert next(itr) == ('select 1; -- test', False)
with pytest.raises(StopIteration):
next(itr)
with StringIO(s) as f:
itr = split_statements(f, remove_comments=True)
assert next(... | 256 | 256 | 956 | 25 | 231 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_multiple_line_sql | test_multiple_line_sql | 76 | 173 | 76 | 77 | 9c771ef93f9cab08b304d07f997b5b3cc039e50e | bigcode/the-stack | train |
a7ccfbe8680a3a4efe3db66f | train | function | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_example1():
with StringIO("""
create or replace table a(aa int, bb string);
truncate a;
rm @%a;
put file://a.txt @%a;
copy into a;
select * from a;
drop table if exists a;""") as f:
itr = split_statements(f... | @pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_example1():
| with StringIO("""
create or replace table a(aa int, bb string);
truncate a;
rm @%a;
put file://a.txt @%a;
copy into a;
select * from a;
drop table if exists a;""") as f:
itr = split_statements(f)
assert next(itr) == (
"create or replace table a(aa int, bb string);", False)
assert... | next(itr) == ("drop view if exists aaa;", False)
assert next(itr) == ("show tables", False)
with pytest.raises(StopIteration):
next(itr)
@pytest.mark.skipif(split_statements is None, reason="No split_statements is available")
def test_sql_example1():
| 65 | 65 | 217 | 25 | 40 | groodt/snowflake-connector-python | test/unit/test_split_statement.py | Python | test_sql_example1 | test_sql_example1 | 391 | 411 | 391 | 392 | 94517117d5adf565ee02ec930add6bb3138981bb | bigcode/the-stack | train |
86cd90148f63d9a9e08e9b71 | train | function | def get(minimum, maximum, range_max=RANGE_MAX):
if minimum < 2:
raise ValueError("dataset: minimum should be greater than or equal to 2")
if range_max > RANGE_MAX:
raise ValueError("dataset: range_max should be less than or equal to %d" % RANGE_MAX)
if maximum > range_max:
raise Valu... | def get(minimum, maximum, range_max=RANGE_MAX):
| if minimum < 2:
raise ValueError("dataset: minimum should be greater than or equal to 2")
if range_max > RANGE_MAX:
raise ValueError("dataset: range_max should be less than or equal to %d" % RANGE_MAX)
if maximum > range_max:
raise ValueError("dataset: maximum shoudl be less than or ... |
DATASETS_DIR = "./data/"
DATASET_SIZE = 1000
RANGE_MAX = 982451653
from random import shuffle
from time import time
from math import sqrt
from math import floor
def get(minimum, maximum, range_max=RANGE_MAX):
| 59 | 64 | 177 | 14 | 44 | aM3z/primality-testing | software/dataset.py | Python | get | get | 12 | 25 | 12 | 12 | 3eea8716e3de72dffee1858c1fbf5ae6484ffe81 | bigcode/the-stack | train |
06efb307041fb5b20198712f | train | function | def trial_division(n):
if n < 2:
raise Exception("every integer n greater than or equal to 2 has a prime factor")
if n % 1 != 0:
raise Exception("n must be an integer")
k = floor(sqrt(n))
for i in range(2, k + 1):
if (n / i) % 1 == 0:
return False
return True
| def trial_division(n):
| if n < 2:
raise Exception("every integer n greater than or equal to 2 has a prime factor")
if n % 1 != 0:
raise Exception("n must be an integer")
k = floor(sqrt(n))
for i in range(2, k + 1):
if (n / i) % 1 == 0:
return False
return True
|
with open(DATASETS_DIR + "%d_%d_%d.csv" % (int(time()), minimum, maximum), "w") as f:
for n in int_list:
f.write("%d, %d\n" % (n, trial_division(n)))
def trial_division(n):
| 63 | 64 | 95 | 6 | 57 | aM3z/primality-testing | software/dataset.py | Python | trial_division | trial_division | 28 | 40 | 28 | 28 | 86109f0cba214da95cd327481aaf65e409be8e28 | bigcode/the-stack | train |
c63c6f42909edb492527f858 | train | function | def _generate_cmap(name, lutsize):
"""Generates the requested cmap from it's name *name*. The lut size is
*lutsize*."""
spec = datad[name]
# Generate the colormap object.
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)
if 'red' in spec:
ret... | def _generate_cmap(name, lutsize):
| """Generates the requested cmap from it's name *name*. The lut size is
*lutsize*."""
spec = datad[name]
# Generate the colormap object.
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)
if 'red' in spec:
return colors.LinearSegmentedColormap(... | & Collis, S.M.
# https://github.com/ARM-DOE/pyart
import warnings
import matplotlib as mpl
import matplotlib.colors as colors
from .cm import _reverse_cmap_spec
from ._cm_colorblind import datad
def _generate_cmap(name, lutsize):
| 64 | 64 | 109 | 10 | 53 | aliny2003/pycwr | pycwr/draw/colormap/cm_colorblind.py | Python | _generate_cmap | _generate_cmap | 29 | 40 | 29 | 29 | 4bdf38abc4a366af3eb96a279cf4a46c6f662cf7 | bigcode/the-stack | train |
0013b0a276e19c76054cab47 | train | function | def quote(s):
return '"' + s + '"'
| def quote(s):
| return '"' + s + '"'
| ())):
comma = '' if i == len(ports) - 1 else ','
print(
' .%s(%s)%s' % (portk, portv, comma),
file=string_buffer)
print(' );', file=string_buffer)
def quote(s):
| 64 | 64 | 12 | 4 | 60 | betrusted-io/prjxray | prjxray/verilog.py | Python | quote | quote | 60 | 61 | 60 | 60 | 81859935d5ca82bf16651a656ef63415f0691f9b | bigcode/the-stack | train |
d44f299c7ce0e3fefbcafe48 | train | function | def instance(mod, name, ports, params={}, sort=True, string_buffer=sys.stdout):
# TODO: make this print nicer
tosort = sorted if sort else lambda x: x
print(' %s' % mod, file=string_buffer)
if len(params):
print(' #(', file=string_buffer)
for i, (paramk, paramv) in enumerate(to... | def instance(mod, name, ports, params={}, sort=True, string_buffer=sys.stdout):
# TODO: make this print nicer
| tosort = sorted if sort else lambda x: x
print(' %s' % mod, file=string_buffer)
if len(params):
print(' #(', file=string_buffer)
for i, (paramk, paramv) in enumerate(tosort(params.items())):
comma = '' if i == len(params) - 1 else ','
print(
... | dout_shr[DOUT_N-1];
roi roi (
.clk(clk),
.din(din),
.dout(dout)
);
endmodule
''' % (DIN_N, DOUT_N))
def instance(mod, name, ports, params={}, sort=True, string_buffer=sys.stdout):
# TODO: make this print nicer
| 72 | 72 | 242 | 27 | 45 | betrusted-io/prjxray | prjxray/verilog.py | Python | instance | instance | 39 | 57 | 39 | 40 | 5fc5be1e18cfdf2d4fb981938b7e94c3174fd840 | bigcode/the-stack | train |
5c653dd2ef884c97e6b3179f | train | function | def parse_bitstr(s):
n, postfix = s.split("'")
n = int(n)
assert postfix[0] == 'b'
bitstr = postfix[1:]
assert len(bitstr) == n
return [int(x) for x in bitstr]
| def parse_bitstr(s):
| n, postfix = s.split("'")
n = int(n)
assert postfix[0] == 'b'
bitstr = postfix[1:]
assert len(bitstr) == n
return [int(x) for x in bitstr]
| else:
value = int(s)
return value
def parsei(s):
if s == "1'b0":
return 0
elif s == "1'b1":
return 1
else:
assert 0, 'FIXME'
def parse_bitstr(s):
| 64 | 64 | 60 | 6 | 58 | betrusted-io/prjxray | prjxray/verilog.py | Python | parse_bitstr | parse_bitstr | 109 | 115 | 109 | 109 | c6199833b8d0cf9cd17d537ed114bf6385106dcb | bigcode/the-stack | train |
55f8a4b2707522e4bb74e206 | train | function | def parsei(s):
if s == "1'b0":
return 0
elif s == "1'b1":
return 1
else:
assert 0, 'FIXME'
| def parsei(s):
| if s == "1'b0":
return 0
elif s == "1'b1":
return 1
else:
assert 0, 'FIXME'
| 16)
else:
raise ValueError('Don\'t know how to interpret input %s' % (s))
# Truncate to `width` bits
value &= 2**width - 1
else:
value = int(s)
return value
def parsei(s):
| 64 | 64 | 45 | 5 | 58 | betrusted-io/prjxray | prjxray/verilog.py | Python | parsei | parsei | 100 | 106 | 100 | 100 | cb5b80fa0e5139f527e99512955842edf276e118 | bigcode/the-stack | train |
2bf4d8ac90d5b3731c208d6f | train | function | def to_int(s):
value = 0
match = re.search(r'^(\d+)\'([sS]*)([bBoOdDhH])(.*)', str(s))
if match:
width = int(match.group(1))
signed = match.group(2)
radix = match.group(3)
value = match.group(4)
# Convert to int type
if re.match(r'[bB]', radix):
... | def to_int(s):
| value = 0
match = re.search(r'^(\d+)\'([sS]*)([bBoOdDhH])(.*)', str(s))
if match:
width = int(match.group(1))
signed = match.group(2)
radix = match.group(3)
value = match.group(4)
# Convert to int type
if re.match(r'[bB]', radix):
value = int(va... | , comma),
file=string_buffer)
print(' );', file=string_buffer)
def quote(s):
return '"' + s + '"'
def unquote(s):
assert s[0] == '"' and s[-1] == '"'
return s[1:-1]
def to_int(s):
| 66 | 66 | 220 | 5 | 61 | betrusted-io/prjxray | prjxray/verilog.py | Python | to_int | to_int | 69 | 97 | 69 | 69 | e96b7abe52f4ad5d9d73167e359ba97ba7ea23bf | bigcode/the-stack | train |
3648455485f7d28e34c7670b | train | function | def vrandbit():
if random.randint(0, 1):
return "1'b1"
else:
return "1'b0"
| def vrandbit():
| if random.randint(0, 1):
return "1'b1"
else:
return "1'b0"
| parse_bitstr(s):
n, postfix = s.split("'")
n = int(n)
assert postfix[0] == 'b'
bitstr = postfix[1:]
assert len(bitstr) == n
return [int(x) for x in bitstr]
def vrandbit():
| 64 | 64 | 32 | 5 | 59 | betrusted-io/prjxray | prjxray/verilog.py | Python | vrandbit | vrandbit | 118 | 122 | 118 | 118 | 64b9abe9b9fdb17aa6be24d347a72716ef20dcbe | bigcode/the-stack | train |
ed5d08c1d3061dca02522c52 | train | function | def vrandbits(n):
ret = "%u'b" % n
for _i in range(n):
ret += str(random.randint(0, 1))
return ret
| def vrandbits(n):
| ret = "%u'b" % n
for _i in range(n):
ret += str(random.randint(0, 1))
return ret
| = postfix[1:]
assert len(bitstr) == n
return [int(x) for x in bitstr]
def vrandbit():
if random.randint(0, 1):
return "1'b1"
else:
return "1'b0"
def vrandbits(n):
| 64 | 64 | 40 | 6 | 58 | betrusted-io/prjxray | prjxray/verilog.py | Python | vrandbits | vrandbits | 125 | 129 | 125 | 125 | fe70dca11ca7d9b32e6b9a9b2755be0e935eab4d | bigcode/the-stack | train |
4cf40db732154633712c4771 | train | function | def top_harness(DIN_N, DOUT_N, f=sys.stdout):
f.write(
'''
module top(input clk, stb, di, output do);
localparam integer DIN_N = %d;
localparam integer DOUT_N = %d;
reg [DIN_N-1:0] din;
wire [DOUT_N-1:0] dout;
reg [DIN_N-1:0] din_shr;
reg [DOUT_N-1:0] dout_shr;
always @(posedg... | def top_harness(DIN_N, DOUT_N, f=sys.stdout):
| f.write(
'''
module top(input clk, stb, di, output do);
localparam integer DIN_N = %d;
localparam integer DOUT_N = %d;
reg [DIN_N-1:0] din;
wire [DOUT_N-1:0] dout;
reg [DIN_N-1:0] din_shr;
reg [DOUT_N-1:0] dout_shr;
always @(posedge clk) begin
din_shr <= {din_shr, di};... | import sys
import random
import re
def top_harness(DIN_N, DOUT_N, f=sys.stdout):
| 25 | 67 | 226 | 16 | 8 | betrusted-io/prjxray | prjxray/verilog.py | Python | top_harness | top_harness | 6 | 36 | 6 | 6 | c5357c562927f33b48c039104a0b4ac9b092d714 | bigcode/the-stack | train |
31144dac090916e217b867d5 | train | function | def unquote(s):
assert s[0] == '"' and s[-1] == '"'
return s[1:-1]
| def unquote(s):
| assert s[0] == '"' and s[-1] == '"'
return s[1:-1]
| - 1 else ','
print(
' .%s(%s)%s' % (portk, portv, comma),
file=string_buffer)
print(' );', file=string_buffer)
def quote(s):
return '"' + s + '"'
def unquote(s):
| 64 | 64 | 29 | 5 | 58 | betrusted-io/prjxray | prjxray/verilog.py | Python | unquote | unquote | 64 | 66 | 64 | 64 | 0e5a174de2913e2520b4d37d524bea861ab91dba | bigcode/the-stack | train |
6ab5214bc6103818fde66374 | train | class | class TB(object):
def __init__(self, dut):
self.dut = dut
self.log = logging.getLogger("cocotb.tb")
self.log.setLevel(logging.DEBUG)
cocotb.fork(Clock(dut.a_clk, 8, units="ns").start())
cocotb.fork(Clock(dut.b_clk, 10, units="ns").start())
self.axi_master = []
... | class TB(object):
| def __init__(self, dut):
self.dut = dut
self.log = logging.getLogger("cocotb.tb")
self.log.setLevel(logging.DEBUG)
cocotb.fork(Clock(dut.a_clk, 8, units="ns").start())
cocotb.fork(Clock(dut.b_clk, 10, units="ns").start())
self.axi_master = []
self.axi_mast... | CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import itertools
import logging
import os
import random
import cocotb_test.simulator
import pytest
import cocotb
from coc... | 121 | 121 | 405 | 4 | 116 | my-yangj/corundum | fpga/lib/axi/tb/axi_dp_ram/test_axi_dp_ram.py | Python | TB | TB | 41 | 82 | 41 | 41 | 7c7d8455507f7489a936627f44fefc9607bec599 | bigcode/the-stack | train |
b6d1b3423cacaa0d8486c76c | train | function | async def run_test_write(dut, port=0, data_in=None, idle_inserter=None, backpressure_inserter=None, size=None):
tb = TB(dut)
axi_master = tb.axi_master[port]
byte_width = axi_master.write_if.byte_width
max_burst_size = axi_master.write_if.max_burst_size
if size is None:
size = max_burst_s... | async def run_test_write(dut, port=0, data_in=None, idle_inserter=None, backpressure_inserter=None, size=None):
| tb = TB(dut)
axi_master = tb.axi_master[port]
byte_width = axi_master.write_if.byte_width
max_burst_size = axi_master.write_if.max_burst_size
if size is None:
size = max_burst_size
await tb.cycle_reset()
tb.set_idle_generator(idle_inserter)
tb.set_backpressure_generator(backp... | .dut.a_clk)
self.dut.a_rst <= 0
await RisingEdge(self.dut.b_clk)
self.dut.b_rst <= 0
await RisingEdge(self.dut.a_clk)
await RisingEdge(self.dut.a_clk)
async def run_test_write(dut, port=0, data_in=None, idle_inserter=None, backpressure_inserter=None, size=None):
| 87 | 87 | 293 | 32 | 55 | my-yangj/corundum | fpga/lib/axi/tb/axi_dp_ram/test_axi_dp_ram.py | Python | run_test_write | run_test_write | 85 | 116 | 85 | 86 | f8cf847522ca38b8d6fdb289bffea631295f65b3 | bigcode/the-stack | train |
abbb71719876e4f47431f2ca | train | function | def cycle_pause():
return itertools.cycle([1, 1, 1, 0])
| def cycle_pause():
| return itertools.cycle([1, 1, 1, 0])
| (tb.axi_master[k % len(tb.axi_master)], k*0x1000, 0x1000, count=16)))
while workers:
await workers.pop(0).join()
await RisingEdge(dut.a_clk)
await RisingEdge(dut.a_clk)
def cycle_pause():
| 64 | 64 | 21 | 4 | 60 | my-yangj/corundum | fpga/lib/axi/tb/axi_dp_ram/test_axi_dp_ram.py | Python | cycle_pause | cycle_pause | 215 | 216 | 215 | 215 | be79a8ff7b1c668120b1f362fc03b8a60ce00ba7 | bigcode/the-stack | train |
a694dba296ff760df80f0582 | train | function | @pytest.mark.parametrize("data_width", [8, 16, 32])
def test_axi_dp_ram(request, data_width):
dut = "axi_dp_ram"
module = os.path.splitext(os.path.basename(__file__))[0]
toplevel = dut
verilog_sources = [
os.path.join(rtl_dir, f"{dut}.v"),
os.path.join(rtl_dir, "axi_ram_wr_rd_if.v"),
... | @pytest.mark.parametrize("data_width", [8, 16, 32])
def test_axi_dp_ram(request, data_width):
| dut = "axi_dp_ram"
module = os.path.splitext(os.path.basename(__file__))[0]
toplevel = dut
verilog_sources = [
os.path.join(rtl_dir, f"{dut}.v"),
os.path.join(rtl_dir, "axi_ram_wr_rd_if.v"),
os.path.join(rtl_dir, "axi_ram_wr_if.v"),
os.path.join(rtl_dir, "axi_ram_rd_if.v... | , cycle_pause])
factory.generate_tests()
factory = TestFactory(run_stress_test)
factory.generate_tests()
# cocotb-test
tests_dir = os.path.abspath(os.path.dirname(__file__))
rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl'))
@pytest.mark.parametrize("data_width", [8, 16, 32])
def test... | 88 | 89 | 297 | 26 | 62 | my-yangj/corundum | fpga/lib/axi/tb/axi_dp_ram/test_axi_dp_ram.py | Python | test_axi_dp_ram | test_axi_dp_ram | 249 | 283 | 249 | 250 | 79961bcd4e066a4dfcbe1d51b812d8b7958db593 | bigcode/the-stack | train |
69f3b05daa07897b6f89ea8b | train | function | async def run_test_read(dut, port=0, data_in=None, idle_inserter=None, backpressure_inserter=None, size=None):
tb = TB(dut)
axi_master = tb.axi_master[port]
byte_width = axi_master.write_if.byte_width
max_burst_size = axi_master.write_if.max_burst_size
if size is None:
size = max_burst_si... | async def run_test_read(dut, port=0, data_in=None, idle_inserter=None, backpressure_inserter=None, size=None):
| tb = TB(dut)
axi_master = tb.axi_master[port]
byte_width = axi_master.write_if.byte_width
max_burst_size = axi_master.write_if.max_burst_size
if size is None:
size = max_burst_size
await tb.cycle_reset()
tb.set_idle_generator(idle_inserter)
tb.set_backpressure_generator(backp... | data = await axi_master.read(addr-1, length+2)
assert data.data == b'\xaa'+test_data+b'\xaa'
await RisingEdge(dut.a_clk)
await RisingEdge(dut.a_clk)
async def run_test_read(dut, port=0, data_in=None, idle_inserter=None, backpressure_inserter=None, size=None):
| 79 | 79 | 264 | 32 | 47 | my-yangj/corundum | fpga/lib/axi/tb/axi_dp_ram/test_axi_dp_ram.py | Python | run_test_read | run_test_read | 119 | 148 | 119 | 120 | 79a0942dbbdd798571ea139013b18901d41d4fa4 | bigcode/the-stack | train |
da303c41956faee354dfb141 | train | function | async def run_stress_test(dut, idle_inserter=None, backpressure_inserter=None):
tb = TB(dut)
await tb.cycle_reset()
tb.set_idle_generator(idle_inserter)
tb.set_backpressure_generator(backpressure_inserter)
async def worker(master, offset, aperture, count=16):
for k in range(count):
... | async def run_stress_test(dut, idle_inserter=None, backpressure_inserter=None):
| tb = TB(dut)
await tb.cycle_reset()
tb.set_idle_generator(idle_inserter)
tb.set_backpressure_generator(backpressure_inserter)
async def worker(master, offset, aperture, count=16):
for k in range(count):
length = random.randint(1, min(512, aperture))
addr = offset+r... | _master[1].wait()
for k in range(10):
tb.axi_master[0].get_read_data()
tb.axi_master[1].get_read_data()
await RisingEdge(dut.a_clk)
await RisingEdge(dut.a_clk)
async def run_stress_test(dut, idle_inserter=None, backpressure_inserter=None):
| 78 | 78 | 261 | 22 | 56 | my-yangj/corundum | fpga/lib/axi/tb/axi_dp_ram/test_axi_dp_ram.py | Python | run_stress_test | run_stress_test | 179 | 212 | 179 | 180 | 8d8328976ebeaef75256eab38dee6fa0962e5c3f | bigcode/the-stack | train |
ac2e320a8ab422b64371e06c | train | function | async def run_test_arb(dut, data_in=None, idle_inserter=None, backpressure_inserter=None):
tb = TB(dut)
byte_width = tb.axi_master[0].write_if.byte_width
await tb.cycle_reset()
tb.set_idle_generator(idle_inserter)
tb.set_backpressure_generator(backpressure_inserter)
for k in range(10):
... | async def run_test_arb(dut, data_in=None, idle_inserter=None, backpressure_inserter=None):
| tb = TB(dut)
byte_width = tb.axi_master[0].write_if.byte_width
await tb.cycle_reset()
tb.set_idle_generator(idle_inserter)
tb.set_backpressure_generator(backpressure_inserter)
for k in range(10):
tb.axi_master[0].init_write(k*256, b'\x11\x22\x33\x44')
tb.axi_master[0].init_re... | .write(addr, test_data)
data = await axi_master.read(addr, length, size=size)
assert data.data == test_data
await RisingEdge(dut.a_clk)
await RisingEdge(dut.a_clk)
async def run_test_arb(dut, data_in=None, idle_inserter=None, backpressure_inserter=None):
| 72 | 72 | 243 | 26 | 46 | my-yangj/corundum | fpga/lib/axi/tb/axi_dp_ram/test_axi_dp_ram.py | Python | run_test_arb | run_test_arb | 151 | 176 | 151 | 152 | c7dffd1b26571b6631827b44e5c4a1e096bd173b | bigcode/the-stack | train |
87e68a20cd32e2f90e1bdb8a | train | function | def draw_unlit_line(ren, x1, y1, z1, x2, y2, z2, color=[0,0,0], width=1):
line = vtk.vtkLineSource()
line.SetPoint1(x1,y1,z1)
line.SetPoint2(x2,y2,z2)
# Create line mapper and actor
linem = vtk.vtkPolyDataMapper()
linem.SetInputConnection(line.GetOutputPort())
linea = vtk.vtkActor()
lin... | def draw_unlit_line(ren, x1, y1, z1, x2, y2, z2, color=[0,0,0], width=1):
| line = vtk.vtkLineSource()
line.SetPoint1(x1,y1,z1)
line.SetPoint2(x2,y2,z2)
# Create line mapper and actor
linem = vtk.vtkPolyDataMapper()
linem.SetInputConnection(line.GetOutputPort())
linea = vtk.vtkActor()
linea.SetMapper(linem)
linea.GetProperty().SetLineWidth(width)
linea.... | CylinderRadius(0.75*axes.GetCylinderRadius())
axes.SetConeRadius(1.5 * axes.GetConeRadius())
axes.SetSphereRadius(1.5 * axes.GetSphereRadius())
return axes
def draw_unlit_line(ren, x1, y1, z1, x2, y2, z2, color=[0,0,0], width=1):
| 84 | 84 | 282 | 38 | 45 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | draw_unlit_line | draw_unlit_line | 59 | 87 | 59 | 59 | 68d5573eeea3a258e006828f366c6575af6f04ef | bigcode/the-stack | train |
ecae09489b1db7d20d15fa74 | train | function | def vtk2imshow(renWin, ax, ss=1):
# Render
renWin.OffScreenRenderingOn()
renWin.SetSize(int(1000*ss), int(1000*ss))
renWin.Render()
# Filter renWin
image_filter = vtk.vtkWindowToImageFilter()
image_filter.SetInput(renWin)
image_filter.SetScale(1)
image_filter.SetInputBufferTypeToRGB... | def vtk2imshow(renWin, ax, ss=1):
# Render
| renWin.OffScreenRenderingOn()
renWin.SetSize(int(1000*ss), int(1000*ss))
renWin.Render()
# Filter renWin
image_filter = vtk.vtkWindowToImageFilter()
image_filter.SetInput(renWin)
image_filter.SetScale(1)
image_filter.SetInputBufferTypeToRGB()
image_filter.ReadFrontBufferOff()
im... | iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
return ren, renWin, iren
# Plots a vtk renderWindow and in a matplotlib axis with imshow
def vtk2imshow(renWin, ax, ss=1):
# Render
| 64 | 64 | 179 | 18 | 45 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | vtk2imshow | vtk2imshow | 24 | 44 | 24 | 25 | 902737380dfce552c3be42e27e74568f413e28ac | bigcode/the-stack | train |
e9e2eb42f80e0250c7b46dd4 | train | function | def draw_outer_box(ren, x, y, z, invert=False):
if invert:
color = [0.7, 0.7, 0.7]
else:
color = [0, 0, 0]
width = 0.15*np.min([x,y,z])
# Bottom layer
draw_unlit_line(ren,-x/2,-y/2,-z/2, +x/2,-y/2,-z/2, color=color, width=width)
draw_unlit_line(ren,+x/2,-y/2,-z/2, +... | def draw_outer_box(ren, x, y, z, invert=False):
| if invert:
color = [0.7, 0.7, 0.7]
else:
color = [0, 0, 0]
width = 0.15*np.min([x,y,z])
# Bottom layer
draw_unlit_line(ren,-x/2,-y/2,-z/2, +x/2,-y/2,-z/2, color=color, width=width)
draw_unlit_line(ren,+x/2,-y/2,-z/2, +x/2,+y/2,-z/2, color=color, width=width)
dra... | zz, -x/2+dx+zz,-y/2+zz,-z/2+zz, color=[1,0,0], width=width)
draw_unlit_line(ren,-x/2+zz,-y/2+zz,-z/2+zz, -x/2+zz,-y/2+dx+zz,-z/2+zz, color=[0,1,0], width=width)
draw_unlit_line(ren,-x/2+zz,-y/2+zz,-z/2+zz, -x/2+zz,-y/2+zz,-z/2+dx+zz, color=[0,0,1], width=width)
def draw_outer_box(ren, x, y, z, invert=False):
| 169 | 169 | 564 | 16 | 153 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | draw_outer_box | draw_outer_box | 97 | 121 | 97 | 97 | 2df350f5aeaaf993c0a0e4be42857395c22005da | bigcode/the-stack | train |
657c8ae57d488f5654664aa3 | train | function | def draw_double_arrow(ren, pos, direction):
for i in range(2):
arrow = vtk.vtkArrowSource()
arrow.SetTipResolution(50)
arrow.SetShaftResolution(50)
arrowm = vtk.vtkPolyDataMapper()
arrowm.SetInputConnection(arrow.GetOutputPort())
arrowa = vtk.vtkActor()
arrow... | def draw_double_arrow(ren, pos, direction):
| for i in range(2):
arrow = vtk.vtkArrowSource()
arrow.SetTipResolution(50)
arrow.SetShaftResolution(50)
arrowm = vtk.vtkPolyDataMapper()
arrowm.SetInputConnection(arrow.GetOutputPort())
arrowa = vtk.vtkActor()
arrowa.SetMapper(arrowm)
arrowa.GetProper... | dotm = vtk.vtkPolyDataMapper()
dotm.SetInputConnection(dot.GetOutputPort())
dota = vtk.vtkActor()
dota.SetMapper(dotm)
dota.GetProperty().SetColor([0,0,0])
ren.AddActor(dota)
def draw_double_arrow(ren, pos, direction):
| 69 | 69 | 231 | 11 | 58 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | draw_double_arrow | draw_double_arrow | 133 | 155 | 133 | 133 | 49ae16fca4a27c03d4047938cfb609f8ffa9dd1e | bigcode/the-stack | train |
a8110c64c61a232b3d400edf | train | function | def draw_axes(ren, x, y, z):
dx = x/10
zz = 0#np.min([x, y, z])/100
width = 0.2*np.min([x,y,z])
draw_unlit_line(ren,-x/2+zz,-y/2+zz,-z/2+zz, -x/2+dx+zz,-y/2+zz,-z/2+zz, color=[1,0,0], width=width)
draw_unlit_line(ren,-x/2+zz,-y/2+zz,-z/2+zz, -x/2+zz,-y/2+dx+zz,-z/2+zz, color=[0,1,0], width=width)
... | def draw_axes(ren, x, y, z):
| dx = x/10
zz = 0#np.min([x, y, z])/100
width = 0.2*np.min([x,y,z])
draw_unlit_line(ren,-x/2+zz,-y/2+zz,-z/2+zz, -x/2+dx+zz,-y/2+zz,-z/2+zz, color=[1,0,0], width=width)
draw_unlit_line(ren,-x/2+zz,-y/2+zz,-z/2+zz, -x/2+zz,-y/2+dx+zz,-z/2+zz, color=[0,1,0], width=width)
draw_unlit_line(ren,-x/2+zz... | InputConnection(tubef.GetOutputPort())
tubea = vtk.vtkActor()
tubea.SetMapper(tubem)
tubea.GetProperty().SetColor(color)
tubea.GetProperty().SetLighting(0)
ren.AddActor(tubea)
def draw_axes(ren, x, y, z):
| 68 | 68 | 227 | 12 | 56 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | draw_axes | draw_axes | 89 | 95 | 89 | 89 | d17bc7fc8db7b42608620ff31a1d5c4f9b61a9d7 | bigcode/the-stack | train |
e186549e8457a3d9fe3889e8 | train | function | def draw_origin_dot(ren):
dot = vtk.vtkSphereSource()
dot.SetRadius(.1)
dotm = vtk.vtkPolyDataMapper()
dotm.SetInputConnection(dot.GetOutputPort())
dota = vtk.vtkActor()
dota.SetMapper(dotm)
dota.GetProperty().SetColor([0,0,0])
ren.AddActor(dota)
| def draw_origin_dot(ren):
| dot = vtk.vtkSphereSource()
dot.SetRadius(.1)
dotm = vtk.vtkPolyDataMapper()
dotm.SetInputConnection(dot.GetOutputPort())
dota = vtk.vtkActor()
dota.SetMapper(dotm)
dota.GetProperty().SetColor([0,0,0])
ren.AddActor(dota)
| 2,+y/2,+z/2, color=color, width=width)
draw_unlit_line(ren,+x/2,+y/2,-z/2, +x/2,+y/2,+z/2, color=color, width=width)
def draw_origin_dot(ren):
| 64 | 64 | 81 | 7 | 57 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | draw_origin_dot | draw_origin_dot | 123 | 131 | 123 | 123 | c0b5f6701277c17fc22fb12fa5f1ccbe49f8428f | bigcode/the-stack | train |
35792dfba8b0c54fd2fb8579 | train | function | def make_axes():
axes = vtk.vtkAxesActor()
axes.SetShaftTypeToCylinder()
axes.SetXAxisLabelText('')
axes.SetYAxisLabelText('')
axes.SetZAxisLabelText('')
axes.SetTotalLength(1.5, 1.5, 1.5)
axes.SetCylinderRadius(0.75*axes.GetCylinderRadius())
axes.SetConeRadius(1.5 * axes.GetConeRadius()... | def make_axes():
| axes = vtk.vtkAxesActor()
axes.SetShaftTypeToCylinder()
axes.SetXAxisLabelText('')
axes.SetYAxisLabelText('')
axes.SetZAxisLabelText('')
axes.SetTotalLength(1.5, 1.5, 1.5)
axes.SetCylinderRadius(0.75*axes.GetCylinderRadius())
axes.SetConeRadius(1.5 * axes.GetConeRadius())
axes.SetSph... | cols, _ = im.GetDimensions()
sc = im.GetPointData().GetScalars()
a = numpy_support.vtk_to_numpy(sc)
a = a.reshape(rows, cols, -1)
ax.imshow(a, origin='lower')
# Make axes actor for vtk plotting
def make_axes():
| 64 | 64 | 113 | 4 | 59 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | make_axes | make_axes | 47 | 57 | 47 | 47 | 01a6f14a87beb654dd0a400b57970bc10d70db1f | bigcode/the-stack | train |
cb85f56315b628bc43a057ac | train | function | def draw_sphere_field(ren, centers, radii, plot_negative=True):
M = radii.shape[0]
N = radii.shape[1]
vertices = utilsh.fibonacci_sphere(radii.shape[-1], xyz=True)
faces = ConvexHull(vertices).simplices
# Split into positive and negative
if plot_negative:
iradiis = [radii.clip(min=0), -... | def draw_sphere_field(ren, centers, radii, plot_negative=True):
| M = radii.shape[0]
N = radii.shape[1]
vertices = utilsh.fibonacci_sphere(radii.shape[-1], xyz=True)
faces = ConvexHull(vertices).simplices
# Split into positive and negative
if plot_negative:
iradiis = [radii.clip(min=0), -radii.clip(max=0)]
else:
iradiis = [radii.clip(min=0... | Color([1,0,0])
arrowa.SetScale(np.linalg.norm(direction))
tp = utilsh.xyz2tp(*direction)
arrowa.RotateWXYZ(-90, 0, 1, 0) # Align with Z axis
arrowa.RotateWXYZ(np.rad2deg(tp[0]), 0, 1, 0)
arrowa.RotateWXYZ(np.rad2deg(tp[1]), 0, 0, 1)
arrowa.SetPosition(*pos)
if i ... | 196 | 196 | 654 | 17 | 178 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | draw_sphere_field | draw_sphere_field | 160 | 224 | 160 | 160 | 45482d496107c05e977240ae5fbc2a6010dfaf74 | bigcode/the-stack | train |
d3f6007ee9c539d3170e384c | train | function | def setup_render():
ren = vtk.vtkRenderer()
ren.UseFXAAOn() # anti-aliasing on
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
ren.SetBackground([255,255,255])
renWin.OffScreenRenderingOff()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
return ren, ... | def setup_render():
| ren = vtk.vtkRenderer()
ren.UseFXAAOn() # anti-aliasing on
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
ren.SetBackground([255,255,255])
renWin.OffScreenRenderingOff()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
return ren, renWin, iren
| # VTK utilities
import vtk
from vtk.util import numpy_support
import numpy as np
from scipy.spatial import ConvexHull
from polaris2.geomvis import utilsh
# Setup vtk render and renderwindow
def setup_render():
| 51 | 64 | 95 | 4 | 46 | talonchandler/polaris2 | polaris2/geomvis/utilvtk.py | Python | setup_render | setup_render | 10 | 21 | 10 | 10 | c3436f74ee5f80be6a3285270e99a1e08c80fd2f | bigcode/the-stack | train |
e8da5e75c7c2417d5cf004bb | train | function | def isnamedtuple(f):
"""Returns True if the argument is a namedtuple-like."""
if not (tf_inspect.isclass(f) and issubclass(f, tuple)):
return False
if not hasattr(f, '_fields'):
return False
fields = getattr(f, '_fields')
if not isinstance(fields, tuple):
return False
if not all(isinstance(f, st... | def isnamedtuple(f):
| """Returns True if the argument is a namedtuple-like."""
if not (tf_inspect.isclass(f) and issubclass(f, tuple)):
return False
if not hasattr(f, '_fields'):
return False
fields = getattr(f, '_fields')
if not isinstance(fields, tuple):
return False
if not all(isinstance(f, str) for f in fields):
... | code__')):
return False
# Some wrappers can rename the function, but changing the name of the
# code object is harder.
return (
(f.__name__ == '<lambda>') or (f.__code__.co_name == '<lambda>'))
def isnamedtuple(f):
| 63 | 64 | 99 | 6 | 57 | KosingZhu/tensorflow | tensorflow/python/autograph/pyct/inspect_utils.py | Python | isnamedtuple | isnamedtuple | 68 | 79 | 68 | 68 | 06ea938048e264d7a1be0426d0487267519a6550 | bigcode/the-stack | train |
ca2d8786d6df17b0b96dd501 | train | function | def getimmediatesource(obj):
"""A variant of inspect.getsource that ignores the __wrapped__ property."""
with _linecache_lock:
_fix_linecache_record(obj)
lines, lnum = inspect.findsource(obj)
return ''.join(inspect.getblock(lines[lnum:]))
| def getimmediatesource(obj):
| """A variant of inspect.getsource that ignores the __wrapped__ property."""
with _linecache_lock:
_fix_linecache_record(obj)
lines, lnum = inspect.findsource(obj)
return ''.join(inspect.getblock(lines[lnum:]))
| errors.
loaded_modules = tuple(sys.modules.values())
for m in loaded_modules:
if hasattr(m, '__file__') and m.__file__ == obj_file:
if obj_module is not m:
linecache.updatecache(obj_file, m.__dict__)
def getimmediatesource(obj):
| 64 | 64 | 64 | 8 | 56 | KosingZhu/tensorflow | tensorflow/python/autograph/pyct/inspect_utils.py | Python | getimmediatesource | getimmediatesource | 143 | 148 | 143 | 143 | 65f6401a19018886c215d0a5332a6ef9ca93a0f5 | bigcode/the-stack | train |
c6d3020de1aaa2136e6d7d96 | train | function | def getdefiningclass(m, owner_class):
"""Resolves the class (e.g. one of the superclasses) that defined a method."""
# Normalize bound functions to their respective unbound versions.
m = _get_unbound_function(m)
for superclass in reversed(inspect.getmro(owner_class)):
if hasattr(superclass, m.__name__):
... | def getdefiningclass(m, owner_class):
| """Resolves the class (e.g. one of the superclasses) that defined a method."""
# Normalize bound functions to their respective unbound versions.
m = _get_unbound_function(m)
for superclass in reversed(inspect.getmro(owner_class)):
if hasattr(superclass, m.__name__):
superclass_m = getattr(superclass, ... | .get_unbound_function fails in some cases.
# The failure case is for tf.keras.Model.
if hasattr(m, '__func__'):
return m.__func__
if hasattr(m, 'im_func'):
return m.im_func
return m
def getdefiningclass(m, owner_class):
| 64 | 64 | 150 | 10 | 53 | KosingZhu/tensorflow | tensorflow/python/autograph/pyct/inspect_utils.py | Python | getdefiningclass | getdefiningclass | 250 | 262 | 250 | 250 | 547ccfef6c7e389427b4c618eea4f30aeb3dc37b | bigcode/the-stack | train |
6ced0be08e18f85131a564c2 | train | function | def _get_unbound_function(m):
# TODO(mdan): Figure out why six.get_unbound_function fails in some cases.
# The failure case is for tf.keras.Model.
if hasattr(m, '__func__'):
return m.__func__
if hasattr(m, 'im_func'):
return m.im_func
return m
| def _get_unbound_function(m):
# TODO(mdan): Figure out why six.get_unbound_function fails in some cases.
# The failure case is for tf.keras.Model.
| if hasattr(m, '__func__'):
return m.__func__
if hasattr(m, 'im_func'):
return m.im_func
return m
| )
if name_in_module is not None:
return '{}.{}'.format(name, name_in_module)
return None
def _get_unbound_function(m):
# TODO(mdan): Figure out why six.get_unbound_function fails in some cases.
# The failure case is for tf.keras.Model.
| 64 | 64 | 72 | 38 | 25 | KosingZhu/tensorflow | tensorflow/python/autograph/pyct/inspect_utils.py | Python | _get_unbound_function | _get_unbound_function | 240 | 247 | 240 | 242 | 1296b4c7d167650415574a74426d93fa40e743da | bigcode/the-stack | train |
4275e33f5b81fe5964f81b45 | train | function | def _fix_linecache_record(obj):
"""Fixes potential corruption of linecache in the presence of functools.wraps.
functools.wraps modifies the target object's __module__ field, which seems
to confuse linecache in special instances, for example when the source is
loaded from a .par file (see https://google.github.... | def _fix_linecache_record(obj):
| """Fixes potential corruption of linecache in the presence of functools.wraps.
functools.wraps modifies the target object's __module__ field, which seems
to confuse linecache in special instances, for example when the source is
loaded from a .par file (see https://google.github.io/subpar/subpar.html).
This ... | Any
Returns:
Bool
"""
return (
inspect.isclass(cls)
and not (issubclass(cls.__class__, type)
and hasattr(cls.__class__, '__call__')
and cls.__class__.__call__ is not type.__call__))
def _fix_linecache_record(obj):
| 65 | 66 | 223 | 8 | 57 | KosingZhu/tensorflow | tensorflow/python/autograph/pyct/inspect_utils.py | Python | _fix_linecache_record | _fix_linecache_record | 116 | 140 | 116 | 116 | 3e469366196e78a80b33507249802c3f84243dcb | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.