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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8e0071e761c453d409f94e51 | train | function | def setup_profile():
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)
firefox_profile.set_preference("javascript.enabled", False)
firefox_profile.set_preference("permissions.default.stylesheet", 2)
#firefox_profile.set_preference(... | def setup_profile():
| firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)
firefox_profile.set_preference("javascript.enabled", False)
firefox_profile.set_preference("permissions.default.stylesheet", 2)
#firefox_profile.set_preference("permissions.default.... | ']['LOGIN_EMAIL']
LOGIN_PW = config['login']['LOGIN_PW']
CVV = config['login']['CVV']
XBOX_URL = config['url']['XBOX_URL']
PS5_URL = config['url']['PS5_URL']
TEST_URL = config['url']['TEST_URL']
def setup_profile():
| 64 | 64 | 105 | 4 | 60 | jameslivulpi/wallybot | checkout.py | Python | setup_profile | setup_profile | 22 | 32 | 22 | 22 | bd564bb5caa28741f3099b416eb83f2df0fdb908 | bigcode/the-stack | train |
d269565e4d1f689c501e55de | train | function | def review_finalize_order(driver):
delivery_type_xpath = "(//button[@data-automation-id='fulfillment-continue'])[1]"
smart_clicker(driver, delivery_type_xpath)
addr_xpath = "(//button[@data-automation-id='address-book-action-buttons-on-continue'])[1]"
smart_clicker(driver, addr_xpath)
cvv_xpath = ... | def review_finalize_order(driver):
| delivery_type_xpath = "(//button[@data-automation-id='fulfillment-continue'])[1]"
smart_clicker(driver, delivery_type_xpath)
addr_xpath = "(//button[@data-automation-id='address-book-action-buttons-on-continue'])[1]"
smart_clicker(driver, addr_xpath)
cvv_xpath = "(//input[@data-automation-id='cvv-... | 5).until(EC.visibility_of_element_located((By.XPATH, signin_pw_xpath)))
signin_pw.send_keys(LOGIN_PW)
signin_btn_xpath = "(//button[@data-automation-id='signin-submit-btn'])[1]"
smart_clicker(driver, signin_btn_xpath)
def review_finalize_order(driver):
| 64 | 64 | 194 | 6 | 58 | jameslivulpi/wallybot | checkout.py | Python | review_finalize_order | review_finalize_order | 64 | 78 | 64 | 64 | 9ca86a3edf25f2cca6f9caa3885f8e4d2eca3854 | bigcode/the-stack | train |
7fbb5590c2d88585bf645f8a | train | function | def signin(driver):
signin_xpath = "(//input[@data-automation-id='signin-email-input'])[1]"
signin_email = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, signin_xpath)))
signin_email.send_keys(LOGIN_EMAIL)
signin_pw_xpath = "(//input[@data-automation-id='signin-password-inpu... | def signin(driver):
| signin_xpath = "(//input[@data-automation-id='signin-email-input'])[1]"
signin_email = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, signin_xpath)))
signin_email.send_keys(LOGIN_EMAIL)
signin_pw_xpath = "(//input[@data-automation-id='signin-password-input'])[1]"
signin_... | = "(//*[@class='spin-button-children'])"
smart_clicker(driver,add_to_cart_xpath)
def checkout(driver):
checkout_xpath = "(//button[@data-automation-id='pac-pos-proceed-to-checkout'])[1]"
smart_clicker(driver, checkout_xpath)
def signin(driver):
| 64 | 64 | 147 | 4 | 60 | jameslivulpi/wallybot | checkout.py | Python | signin | signin | 52 | 62 | 52 | 52 | b54881166ec882866ac942a02b04a672f10742a0 | bigcode/the-stack | train |
50127a5568c7c82195cb6f69 | train | function | def add_to_cart(driver):
add_to_cart_xpath = "(//*[@class='spin-button-children'])"
smart_clicker(driver,add_to_cart_xpath)
| def add_to_cart(driver):
| add_to_cart_xpath = "(//*[@class='spin-button-children'])"
smart_clicker(driver,add_to_cart_xpath)
| smart_clicker(driver, xpath):
while True:
try:
find_element = WebDriverWait(driver, 2).until(EC.visibility_of_element_located((By.XPATH, xpath)))
find_element.click()
break
except:
driver.refresh()
continue
def add_to_cart(driver):
| 64 | 64 | 34 | 6 | 57 | jameslivulpi/wallybot | checkout.py | Python | add_to_cart | add_to_cart | 44 | 46 | 44 | 44 | ed2353f716bc883d87794c9ad4432e0cda002031 | bigcode/the-stack | train |
50b9945dbcf8ef4639200b28 | train | function | @click.command()
@click.option('--es-node', '-e', default=['localhost'], multiple=True,
help='Address of a node in a Elasticsearch cluster to use. '
'Specify multiple nodes by providing the option multiple times. '
'A port can be provided if non-standard (9200) e.g. e... | @click.command()
@click.option('--es-node', '-e', default=['localhost'], multiple=True,
help='Address of a node in a Elasticsearch cluster to use. '
'Specify multiple nodes by providing the option multiple times. '
'A port can be provided if non-standard (9200) e.g. e... | def shutdown():
gpcsup.SERVER_READY = False
def wait():
# Sleep for a few seconds to allow for race conditions between sending
# the SIGTERM and load balancers stopping sending traffic here.
log.info('Shutdown: Sleeping %(sleep_s)s seconds.',
... | @click.command()
@click.option('--es-node', '-e', default=['localhost'], multiple=True,
help='Address of a node in a Elasticsearch cluster to use. '
'Specify multiple nodes by providing the option multiple times. '
'A port can be provided if non-standard (9200) e.g. e... | 331 | 185 | 618 | 331 | 0 | braedon/gpcsup | main.py | Python | server | server | 37 | 96 | 37 | 62 | 80a8bd4a9652e3a24900d4293f1ca67739a3bd20 | bigcode/the-stack | train |
a76919760af7875f82072c43 | train | function | @click.command()
@click.option('--twitter-consumer-key', required=True,
help='Twitter consumer API key.')
@click.option('--twitter-consumer-secret', required=True,
help='Twitter consumer API secret key.')
@click.option('--twitter-token-key', required=True,
help='Twitter access ... | @click.command()
@click.option('--twitter-consumer-key', required=True,
help='Twitter consumer API key.')
@click.option('--twitter-consumer-secret', required=True,
help='Twitter consumer API secret key.')
@click.option('--twitter-token-key', required=True,
help='Twitter access ... | configure_logging(json=options['json'], verbose=options['verbose'])
es_client = Elasticsearch(options['es_node'], verify_certs=False)
es_dao = GpcSupDao(es_client, options['es_scan_result_index'])
with nice_shutdown():
run_twitter_worker(es_dao, **options)
| @click.command()
@click.option('--twitter-consumer-key', required=True,
help='Twitter consumer API key.')
@click.option('--twitter-consumer-secret', required=True,
help='Twitter consumer API secret key.')
@click.option('--twitter-token-key', required=True,
help='Twitter access ... | 274 | 102 | 340 | 274 | 0 | braedon/gpcsup | main.py | Python | twitter_worker | twitter_worker | 99 | 130 | 99 | 123 | e6ce590909fd9fb925ec5ad893853408493181f9 | bigcode/the-stack | train |
7f5bcbd95705835bb8d0ab23 | train | function | @click.group(context_settings=CONTEXT_SETTINGS)
def main():
pass
| @click.group(context_settings=CONTEXT_SETTINGS)
def main():
| pass
| 'help_option_names': ['-h', '--help']
}
log = logging.getLogger(__name__)
# Use an unbounded pool to track gevent greenlets so we can
# wait for them to finish on shutdown.
gevent_pool = Pool()
@click.group(context_settings=CONTEXT_SETTINGS)
def main():
| 64 | 64 | 15 | 12 | 52 | braedon/gpcsup | main.py | Python | main | main | 32 | 34 | 32 | 33 | a04a3c8505c941ee8f674c42490923057191a641 | bigcode/the-stack | train |
4fee983e6dedce3ff58f7389 | train | class | class StateVariable(models.Model):
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
current_object_state = models.ForeignKey(CurrentObjectState, on_delete=PROTECT,
verbose_name=ugettext_lazy("Object State"))
state_variable_def ... | class StateVariable(models.Model):
| workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
current_object_state = models.ForeignKey(CurrentObjectState, on_delete=PROTECT,
verbose_name=ugettext_lazy("Object State"))
state_variable_def = models.ForeignKey(StateVariableDe... | object_id,
object_state=object_state, **params)
TransitionLog.objects.create(
workflow=object_state.workflow,
current_object_state=object_state,
user_id=user.id if user else None,
transition=transition,
success=True)
return object_state
class StateVariable(mod... | 64 | 64 | 109 | 6 | 57 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | StateVariable | StateVariable | 633 | 640 | 633 | 633 | 2ebb94cb2eca6b031a8713685aea1379f9f1c1f9 | bigcode/the-stack | train |
ae3e7fd8151b7ec7a058f267 | train | class | class Condition(models.Model):
CONDITION_TYPES = [
("function", "Function Call"),
("and", "Boolean AND"),
("or", "Boolean OR"),
("not", "Boolean NOT"),
]
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
... | class Condition(models.Model):
| CONDITION_TYPES = [
("function", "Function Call"),
("and", "Boolean AND"),
("or", "Boolean OR"),
("not", "Boolean NOT"),
]
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
condition_type = models.Cha... | , user, object_id, object_state_id),
kwargs={"automatic": automatic})
thr.start()
return thr
else:
return _execute_transition(transition=self, user=user, object_id=object_id,
object_state_id=object_state_id, automatic=automatic)
def clone(... | 235 | 235 | 786 | 5 | 229 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | Condition | Condition | 301 | 380 | 301 | 301 | d5e903ff56e148da416757ae275dde337a1212a9 | bigcode/the-stack | train |
3f7be934428ae0d9ae73d5ab | train | function | def _execute_transition(*, transition, user, object_id, object_state_id, automatic=False, last_transition=None,
recursion_count=0):
if recursion_count > 10:
raise RecursionError("too many chained automatic transitions")
if transition.is_available(user=user, object_id=object_id, object_state_id=o... | def _execute_transition(*, transition, user, object_id, object_state_id, automatic=False, last_transition=None,
recursion_count=0):
| if recursion_count > 10:
raise RecursionError("too many chained automatic transitions")
if transition.is_available(user=user, object_id=object_id, object_state_id=object_state_id, automatic=automatic,
last_transition=last_transition):
# #print("transition {} available on {}".format(t... | _condition(user=user, object_id=object_id, object_state
=object_state, transition=transition)
# print("condition_checks: {}".format(condition_checks))
return condition_checks
else:
return False
def _execute_transition(*, transition, user, object_id, object_state_id, automatic=Fal... | 76 | 76 | 254 | 30 | 45 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | _execute_transition | _execute_transition | 570 | 588 | 570 | 571 | 4c6c21391949c19dec818d5b77780d50725dc26f | bigcode/the-stack | train |
821f4048bfa2cd0c1aa77b5b | train | class | class SingleWorkflowModel(models.Model):
current_state = models.ForeignKey(CurrentObjectState, on_delete=PROTECT, verbose_name=ugettext_lazy("Object State"),
related_name="%(app_label)s_%(class)s")
class Meta:
abstract = True
@property
def state(self):
return self.current_state... | class SingleWorkflowModel(models.Model):
| current_state = models.ForeignKey(CurrentObjectState, on_delete=PROTECT, verbose_name=ugettext_lazy("Object State"),
related_name="%(app_label)s_%(class)s")
class Meta:
abstract = True
@property
def state(self):
return self.current_state.state
@property
def transition_... | _name=ugettext_lazy("Object State"))
state_variable_def = models.ForeignKey(StateVariableDef, on_delete=PROTECT,
verbose_name=ugettext_lazy("Variable Definition"))
value = models.CharField(max_length=4000, verbose_name=ugettext_lazy("Value"))
class SingleWorkflowModel(models.Model):
| 63 | 64 | 193 | 7 | 56 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | SingleWorkflowModel | SingleWorkflowModel | 643 | 668 | 643 | 643 | 001ff8e0c6ebd467c4b56b965934449e678bc53b | bigcode/the-stack | train |
b885533e7c3e30b26f25f958 | train | class | class StateVariableDefManager(models.Manager):
def get_by_natural_key(self, name, workflow):
return self.get(name=name, workflow__name=workflow)
| class StateVariableDefManager(models.Manager):
| def get_by_natural_key(self, name, workflow):
return self.get(name=name, workflow__name=workflow)
| _state, old_state = clone(self, workflow=workflow, **defaults)
for variableDef in old_state.variable_definitions.all():
new_var, _ = clone(variableDef, state=new_state, workflow=workflow, **defaults)
return new_state, old_state
class StateVariableDefManager(models.Manager):
| 64 | 64 | 34 | 8 | 55 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | StateVariableDefManager | StateVariableDefManager | 197 | 200 | 197 | 198 | 0e605c8c543e219deac4b82876e752d11a0d1c02 | bigcode/the-stack | train |
ff2b5afecfb745db65850ba2 | train | class | class TransitionManager(models.Manager):
def get_by_natural_key(self, name, workflow, initial_state, final_state):
return self.get(
name=name,
workflow__name=workflow,
initial_state__name=initial_state,
final_state__name=final_state
)
| class TransitionManager(models.Manager):
| def get_by_natural_key(self, name, workflow, initial_state, final_state):
return self.get(
name=name,
workflow__name=workflow,
initial_state__name=initial_state,
final_state__name=final_state
)
| ogether = (('name', 'workflow', 'state'),)
def __unicode__(self):
return "{}: {} - {}".format(self.workflow.name, self.state.name, self.name)
def natural_key(self):
return self.name, self.state.name, self.workflow.name
class TransitionManager(models.Manager):
| 64 | 64 | 61 | 6 | 57 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | TransitionManager | TransitionManager | 220 | 228 | 220 | 221 | 244af9bfdc321847d81c87fc74dab99cc9c2cc22 | bigcode/the-stack | train |
3211a4b3da36a2482d4361a7 | train | class | class Transition(models.Model):
objects = TransitionManager()
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
name = models.CharField(max_length=50, verbose_name=ugettext_lazy("Name"))
label = models.CharField(max_length=50, verb... | class Transition(models.Model):
| objects = TransitionManager()
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
name = models.CharField(max_length=50, verbose_name=ugettext_lazy("Name"))
label = models.CharField(max_length=50, verbose_name=ugettext_lazy("Label"),... | name=workflow)
class StateVariableDef(models.Model):
objects = StateVariableDefManager()
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"))
state = models.ForeignKey(State, on_delete=PROTECT, verbose_name=ugettext_lazy("State"),
related_name="variable... | 222 | 222 | 742 | 5 | 217 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | Transition | Transition | 231 | 298 | 231 | 231 | 2718b1fbd8d303ea525c47dfee2227c9aab861fb | bigcode/the-stack | train |
bdefcad8bb2fac91827a73d9 | train | class | class StateVariableDef(models.Model):
objects = StateVariableDefManager()
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"))
state = models.ForeignKey(State, on_delete=PROTECT, verbose_name=ugettext_lazy("State"),
related_name="variable_definitions")
... | class StateVariableDef(models.Model):
| objects = StateVariableDefManager()
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"))
state = models.ForeignKey(State, on_delete=PROTECT, verbose_name=ugettext_lazy("State"),
related_name="variable_definitions")
name = models.CharField(max_length=1... | clone(variableDef, state=new_state, workflow=workflow, **defaults)
return new_state, old_state
class StateVariableDefManager(models.Manager):
def get_by_natural_key(self, name, workflow):
return self.get(name=name, workflow__name=workflow)
class StateVariableDef(models.Model):
| 64 | 64 | 152 | 7 | 57 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | StateVariableDef | StateVariableDef | 203 | 217 | 203 | 203 | dd9fb1fea01fb18dc6c7f231665fd216c6aceadc | bigcode/the-stack | train |
baa2b5f87d2a7060234227ad | train | class | class MultiWorkflowModel(models.Model):
current_states = models.ManyToManyField(CurrentObjectState,
verbose_name=ugettext_lazy("Object States"), related_name="%(app_label)s_%(class)s")
class Meta:
abstract = True
def state(self, workflow: Workflow):
return self.current_states.get(w... | class MultiWorkflowModel(models.Model):
| current_states = models.ManyToManyField(CurrentObjectState,
verbose_name=ugettext_lazy("Object States"), related_name="%(app_label)s_%(class)s")
class Meta:
abstract = True
def state(self, workflow: Workflow):
return self.current_states.get(workflow=workflow).state
def transit... | _transition(self, transition: Transition, user: User, asynchonous=False, automatic=False):
return transition.execute(
user,
self.current_state.object_id,
object_state_id=self.current_state,
asynchonous=asynchonous,
automatic=automatic
)
class M... | 68 | 68 | 228 | 7 | 61 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | MultiWorkflowModel | MultiWorkflowModel | 671 | 696 | 671 | 671 | c424ffb4f100fb08e0f9f8bf303cbea60658eda3 | bigcode/the-stack | train |
8fbf7b47c01edffa7b193eb5 | train | class | class Function(models.Model):
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
function_name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Function"))
function_module = models.CharField(max_length=400, verbose_name=uge... | class Function(models.Model):
| workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
function_name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Function"))
function_module = models.CharField(max_length=400, verbose_name=ugettext_lazy("Module"))
cond... | , **defaults)
for condition in old_condition.child_conditions.all():
new_child, old_child = condition.clone(workflow=workflow, parent_condition=new_condition)
for function in old_condition.function_set.all():
new_function, old_function = function.clone(workflow=workflow, conditio... | 74 | 74 | 249 | 5 | 68 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | Function | Function | 383 | 406 | 383 | 383 | 583c02b2c2440f9cf8122d9ec9fddca19a8bc1b8 | bigcode/the-stack | train |
ba2d8e50d99746007d18d0e4 | train | class | class TransitionLog(models.Model):
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
user_id = models.IntegerField(blank=True, null=True, verbose_name=ugettext_lazy("User Id"))
current_object_state = models.ForeignKey(CurrentObjectState... | class TransitionLog(models.Model):
| workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
user_id = models.IntegerField(blank=True, null=True, verbose_name=ugettext_lazy("User Id"))
current_object_state = models.ForeignKey(CurrentObjectState, on_delete=PROTECT,
verbos... | (id=obj_id)
if obj.workflow.parent_workflow == self.workflow:
obj.parent_object_state = self
obj.save()
return True
return False
def all_subobjects_closed(self):
for child_obj in self.child_object_states.all():
if not child_obj.state.is_final_... | 78 | 78 | 261 | 6 | 71 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | TransitionLog | TransitionLog | 510 | 530 | 510 | 510 | 5e718a272eb899c185cfedc98537c966950b9cd9 | bigcode/the-stack | train |
7a0872f0788a710e4edcbc93 | train | class | class WorkflowManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
| class WorkflowManager(models.Manager):
| def get_by_natural_key(self, name):
return self.get(name=name)
| new_object = old_object
new_object.id = None
for key, value in defaults.items():
setattr(new_object, key, value)
new_object.save()
old_object = old_object._meta.model.objects.get(id=id)
return new_object, old_object
class WorkflowManager(models.Manager):
| 64 | 64 | 24 | 6 | 57 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | WorkflowManager | WorkflowManager | 31 | 33 | 31 | 31 | f46de9a528a5c1394a028a3a844071176f2069ff | bigcode/the-stack | train |
1e990fcb5c7afd378f50e187 | train | function | def _is_transition_available(transition, user, object_id, object_state_id=None, automatic=False,
last_transition=None):
# #print("checking if {} available on obj id {}".format(transition.name, object_id))
if transition.is_initial:
return transition.workflow.is_initial_transition_available(user=u... | def _is_transition_available(transition, user, object_id, object_state_id=None, automatic=False,
last_transition=None):
# #print("checking if {} available on obj id {}".format(transition.name, object_id))
| if transition.is_initial:
return transition.workflow.is_initial_transition_available(user=user, object_id=object_id,
object_state_id=object_state_id,
automatic=automatic)
object_state = None
if object_state_id is not None:
object_state = CurrentObjectState.objects.get... | (max_length=4000, null=True, blank=True,
verbose_name=ugettext_lazy("Error Message"))
def save(self, **qwargs):
self.workflow = self.transition.workflow
super(TransitionLog, self).save(**qwargs)
def _is_transition_available(transition, user, object_id, object_state_id=None, automatic=False,... | 99 | 99 | 330 | 47 | 52 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | _is_transition_available | _is_transition_available | 533 | 567 | 533 | 535 | 4b30f844e8ba1444e0648518d549ec62b5cc58b2 | bigcode/the-stack | train |
69b46d00122795299c7730c1 | train | class | class Workflow(models.Model):
objects = WorkflowManager()
name = models.CharField(max_length=200, unique=True, verbose_name=ugettext_lazy("Name"))
object_type = models.CharField(max_length=200, verbose_name=ugettext_lazy("Object_Type"))
initial_prefetch = models.CharField(max_length=4000, null=True, bl... | class Workflow(models.Model):
| objects = WorkflowManager()
name = models.CharField(max_length=200, unique=True, verbose_name=ugettext_lazy("Name"))
object_type = models.CharField(max_length=200, verbose_name=ugettext_lazy("Object_Type"))
initial_prefetch = models.CharField(max_length=4000, null=True, blank=True,
verbose_name... | import json
import threading
from datetime import timedelta, datetime
from typing import TypeVar
from auprico_auth.models import User
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.db.models import SET_NULL
from django.db.models.deletion import PROTECT
from dja... | 229 | 256 | 1,092 | 5 | 224 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | Workflow | Workflow | 36 | 157 | 36 | 36 | 4af6a7bce9855a6f508993c0994e48abbf5abbd0 | bigcode/the-stack | train |
bbcd42d8052a008fd5487824 | train | class | class State(models.Model):
objects = StateManager()
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"))
name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Name"))
active = models.BooleanField(verbose_name=ugettext_lazy("Active"))
initia... | class State(models.Model):
| objects = StateManager()
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"))
name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Name"))
active = models.BooleanField(verbose_name=ugettext_lazy("Active"))
initial = models.BooleanField(def... | new_transition, old_transition = transition.clone(workflow=new_wf, state_map=state_map)
transition_map.update({old_transition.id: new_transition.id})
return new_wf, old_wf, state_map, transition_map
class StateManager(models.Manager):
def get_by_natural_key(self, name, workflow):
ret... | 86 | 86 | 287 | 5 | 81 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | State | State | 165 | 194 | 165 | 165 | e2746bf26ece6c641e884f3b5df7c90aab56ebe6 | bigcode/the-stack | train |
a9dd6fa947d981c8ce8cbfe2 | train | function | def clone(old_object: T, **defaults) -> (T, T):
id = old_object.id
new_object = old_object
new_object.id = None
for key, value in defaults.items():
setattr(new_object, key, value)
new_object.save()
old_object = old_object._meta.model.objects.get(id=id)
return new_object, old_object
| def clone(old_object: T, **defaults) -> (T, T):
| id = old_object.id
new_object = old_object
new_object.id = None
for key, value in defaults.items():
setattr(new_object, key, value)
new_object.save()
old_object = old_object._meta.model.objects.get(id=id)
return new_object, old_object
| django_now
from django.utils.translation import ugettext_lazy
# import a definition from a module at runtime
from auprico_workflow.utils import import_from, import_from_path
T = TypeVar('T', bound=models.Model)
def clone(old_object: T, **defaults) -> (T, T):
| 64 | 64 | 82 | 16 | 48 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | clone | clone | 20 | 28 | 20 | 20 | 4de6131e8e3de0c2c7588e6919ed80f06ccc5cb1 | bigcode/the-stack | train |
9cb128f1f71301a8f5993726 | train | class | class StateManager(models.Manager):
def get_by_natural_key(self, name, workflow):
return self.get(name=name, workflow__name=workflow)
| class StateManager(models.Manager):
| def get_by_natural_key(self, name, workflow):
return self.get(name=name, workflow__name=workflow)
| in old_wf.transition_set.all():
new_transition, old_transition = transition.clone(workflow=new_wf, state_map=state_map)
transition_map.update({old_transition.id: new_transition.id})
return new_wf, old_wf, state_map, transition_map
class StateManager(models.Manager):
| 64 | 64 | 32 | 6 | 57 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | StateManager | StateManager | 160 | 162 | 160 | 160 | 08406bddcde37c675cd9b7688b3199c39dafa973 | bigcode/the-stack | train |
196a2e8839b33ab8180dd0cd | train | function | @transaction.atomic
def _atomic_execution(object_id, object_state_id, transition, user):
# we first change status for consistency, exceptions in callbacks could break the process
# #print("executing transition {} on object id {}".format(transition.name, object_id))
object_state = None
if transition.init... | @transaction.atomic
def _atomic_execution(object_id, object_state_id, transition, user):
# we first change status for consistency, exceptions in callbacks could break the process
# #print("executing transition {} on object id {}".format(transition.name, object_id))
| object_state = None
if transition.initial_state is not None:
if object_state_id:
object_state = CurrentObjectState.objects.get(id=object_state_id, state__workflow=transition.workflow)
else:
object_state = CurrentObjectState.objects.filter(object_id=object_id,
... | return _execute_transition(transition=t, user=None, object_id=object_id,
object_state_id=object_state_id, automatic=True, last_transition=last_transition)
@transaction.atomic
def _atomic_execution(object_id, object_state_id, transition, user):
# we first change status for consistency, ex... | 93 | 93 | 313 | 57 | 36 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | _atomic_execution | _atomic_execution | 601 | 630 | 601 | 604 | 299321a6a8957b8b263b505768814f29763476f2 | bigcode/the-stack | train |
3af97abda653dd110447e3f4 | train | class | class FunctionParameter(models.Model):
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
function = models.ForeignKey(Function, on_delete=PROTECT, verbose_name=ugettext_lazy("Function"),
related_name="parameters")
name = models.... | class FunctionParameter(models.Model):
| workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
function = models.ForeignKey(Function, on_delete=PROTECT, verbose_name=ugettext_lazy("Function"),
related_name="parameters")
name = models.CharField(max_length=100, verbose_name=... | # old_function: Function
new_function, old_function = clone(self, workflow=workflow, **defaults)
for param in old_function.parameters.all():
new_param, old_param = param.clone(workflow=workflow, function=new_function)
return new_function, old_function
class FunctionParameter(models.... | 64 | 64 | 201 | 6 | 57 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | FunctionParameter | FunctionParameter | 409 | 426 | 409 | 409 | 32c89be444ef3b79f86903eaabc9272627f7e10f | bigcode/the-stack | train |
5256b368b06c6e1d1153a111 | train | class | class CallbackParameter(models.Model):
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
callback = models.ForeignKey(Callback, on_delete=PROTECT, verbose_name=ugettext_lazy("Callback"),
related_name="parameters")
name = models.... | class CallbackParameter(models.Model):
| workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
callback = models.ForeignKey(Callback, on_delete=PROTECT, verbose_name=ugettext_lazy("Callback"),
related_name="parameters")
name = models.CharField(max_length=100, verbose_name=... | # old_function: Function
new_callback, old_callback = clone(self, workflow=workflow, **defaults)
for param in old_callback.parameters.all():
new_param, old_param = param.clone(workflow=workflow, callback=new_callback)
return new_callback, old_callback
class CallbackParameter(models.... | 64 | 64 | 178 | 6 | 57 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | CallbackParameter | CallbackParameter | 457 | 471 | 457 | 457 | 13439531f90f4c543544b85cd16c4b5d6e156c85 | bigcode/the-stack | train |
2c06c6a5daa4360e1d129c3a | train | class | class CurrentObjectState(models.Model):
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
object_id = models.CharField(max_length=200, verbose_name=ugettext_lazy("Object Id"))
state = models.ForeignKey(State, on_delete=PROTECT, verbose_... | class CurrentObjectState(models.Model):
| workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
object_id = models.CharField(max_length=200, verbose_name=ugettext_lazy("Object Id"))
state = models.ForeignKey(State, on_delete=PROTECT, verbose_name=ugettext_lazy("State"))
updated... | gettext_lazy("Value"))
def save(self, **qwargs):
self.workflow = self.callback.workflow
super(CallbackParameter, self).save(**qwargs)
def clone(self, *, workflow: Workflow, **defaults) -> ('CallbackParameter', 'CallbackParameter'):
new_param, old_param = clone(self, workflow=workflow, ... | 89 | 89 | 297 | 7 | 81 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | CurrentObjectState | CurrentObjectState | 474 | 507 | 474 | 474 | 69477c8b27858cbc653d8abb3d5393ab21f380e4 | bigcode/the-stack | train |
53494ba28f9365b0cc3cf87b | train | class | class Callback(models.Model):
workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
function_name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Name"))
function_module = models.CharField(max_length=400, verbose_name=ugettex... | class Callback(models.Model):
| workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"),
editable=False)
function_name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Name"))
function_module = models.CharField(max_length=400, verbose_name=ugettext_lazy("Module"))
transiti... | def save(self, **qwargs):
self.workflow = self.function.workflow
super(FunctionParameter, self).save(**qwargs)
def clone(self, *, workflow: Workflow, **defaults) -> ('FunctionParameter', 'FunctionParameter'):
new_param, old_param = clone(self, workflow=workflow, **defaults)
return ... | 80 | 80 | 268 | 5 | 74 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | Callback | Callback | 429 | 454 | 429 | 429 | d0587d9ff333ec3ccba93c1608f45369c2fd53df | bigcode/the-stack | train |
d2131f4658cd2f658d58b14d | train | function | def _execute_atomatic_transitions(state, object_id, object_state_id, asynchonous=False, last_transition=None):
if not state.active:
return None
automatic_transitions = state.outgoing_transitions.filter(automatic=True)
for t in automatic_transitions:
if t.is_available(user=None, object_id=obj... | def _execute_atomatic_transitions(state, object_id, object_state_id, asynchonous=False, last_transition=None):
| if not state.active:
return None
automatic_transitions = state.outgoing_transitions.filter(automatic=True)
for t in automatic_transitions:
if t.is_available(user=None, object_id=object_id, object_state_id=object_state_id, automatic=True):
return _execute_transition(transition=t, ... | applies and start it if any
_execute_atomatic_transitions(transition.final_state, object_id, object_state_id,
last_transition=django_now())
return object_state
def _execute_atomatic_transitions(state, object_id, object_state_id, asynchonous=False, last_transition=None):
| 64 | 64 | 120 | 26 | 37 | dani0805/auprico-workflow | auprico_workflow/models.py | Python | _execute_atomatic_transitions | _execute_atomatic_transitions | 591 | 598 | 591 | 591 | 25cf9e8d0a061c94ef5ce08e80498e8e5462971b | bigcode/the-stack | train |
ac5c2ccc755853e3b5e15a96 | train | class | class ProofConstructor:
def __init__(self):
self.mode = []
self.nodes = []
self.exempt = []
def push(self, mode, nodes=None):
global proving
proving = True
self.mode.append(mode)
self.exempt.append(set())
if mode == VERIFYING:
nodes =... | class ProofConstructor:
| def __init__(self):
self.mode = []
self.nodes = []
self.exempt = []
def push(self, mode, nodes=None):
global proving
proving = True
self.mode.append(mode)
self.exempt.append(set())
if mode == VERIFYING:
nodes = nodes or []
... | res += ascii_chr(16 * nibbles[i] + nibbles[i + 1])
return res
NIBBLE_TERMINATOR = 16
RECORDING = 1
NONE = 0
VERIFYING = -1
ZERO_ENCODED = encode_int(0)
proving = False
class ProofConstructor:
| 72 | 72 | 242 | 4 | 67 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | ProofConstructor | ProofConstructor | 59 | 100 | 59 | 60 | d0aede60863284bee2450c3d287236d512c33348 | bigcode/the-stack | train |
68358d2414266bb11c61c4f7 | train | function | def without_terminator_and_flags(nibbles):
nibbles = nibbles[:]
if nibbles and nibbles[-1] == NIBBLE_TERMINATOR:
del nibbles[-1]
if len(nibbles) % 2:
del nibbles[0]
return nibbles
| def without_terminator_and_flags(nibbles):
| nibbles = nibbles[:]
if nibbles and nibbles[-1] == NIBBLE_TERMINATOR:
del nibbles[-1]
if len(nibbles) % 2:
del nibbles[0]
return nibbles
| [-1]
return nibbles
def adapt_terminator(nibbles, has_terminator):
if has_terminator:
return with_terminator(nibbles)
else:
return without_terminator(nibbles)
def without_terminator_and_flags(nibbles):
| 64 | 64 | 74 | 11 | 53 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | without_terminator_and_flags | without_terminator_and_flags | 131 | 137 | 131 | 131 | 31b69a7685481f0ab95adacad917562bdfe85433 | bigcode/the-stack | train |
0b51a8d0741e3465ac432aa5 | train | function | def bin_to_nibbles(s):
"""convert string s to nibbles (half-bytes)
>>> bin_to_nibbles("")
[]
>>> bin_to_nibbles("h")
[6, 8]
>>> bin_to_nibbles("he")
[6, 8, 6, 5]
>>> bin_to_nibbles("hello")
[6, 8, 6, 5, 6, 12, 6, 12, 6, 15]
"""
return [hti[c] for c in encode_hex(s)]
| def bin_to_nibbles(s):
| """convert string s to nibbles (half-bytes)
>>> bin_to_nibbles("")
[]
>>> bin_to_nibbles("h")
[6, 8]
>>> bin_to_nibbles("he")
[6, 8, 6, 5]
>>> bin_to_nibbles("hello")
[6, 8, 6, 5, 6, 12, 6, 12, 6, 15]
"""
return [hti[c] for c in encode_hex(s)]
| storage.kv_in_memory import KeyValueStorageInMemory
rlp_encode = encode_optimized
rlp_decode = decode_optimized
bin_to_nibbles_cache = {}
hti = {c: i for i, c in enumerate('0123456789abcdef')}
def bin_to_nibbles(s):
| 63 | 64 | 128 | 8 | 55 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | bin_to_nibbles | bin_to_nibbles | 22 | 34 | 22 | 22 | fe3f30eb2e59123796f92aa887db61be1282ce0b | bigcode/the-stack | train |
1dca125a7d048b92a5dde51e | train | function | def starts_with(full, part):
''' test whether the items in the part is
the leading items of the full
'''
if len(full) < len(part):
return False
return full[:len(part)] == part
| def starts_with(full, part):
| ''' test whether the items in the part is
the leading items of the full
'''
if len(full) < len(part):
return False
return full[:len(part)] == part
| ata)
flags = o[0]
if flags & 2:
o.append(NIBBLE_TERMINATOR)
if flags & 1 == 1:
o = o[1:]
else:
o = o[2:]
return o
def starts_with(full, part):
| 64 | 64 | 51 | 7 | 56 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | starts_with | starts_with | 181 | 187 | 181 | 181 | eb3b8fbea9759d1e7a4ca60b252e738fb602ddb6 | bigcode/the-stack | train |
531f5277cfe656692be11654 | train | function | def transient_trie_exception(*args):
raise Exception("Transient trie")
| def transient_trie_exception(*args):
| raise Exception("Transient trie")
| key_nibbles_from_key_value_node(node):
return without_terminator(unpack_to_nibbles(node[0]))
BLANK_NODE = b''
BLANK_ROOT = sha3rlp(BLANK_NODE)
DEATH_ROW_OFFSET = 2**62
def transient_trie_exception(*args):
| 64 | 64 | 15 | 8 | 55 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | transient_trie_exception | transient_trie_exception | 212 | 213 | 212 | 212 | 5107cdb6fff0496b5f3b8754c117afcecd3f4695 | bigcode/the-stack | train |
6809f299e2c5b84743cd2a4c | train | function | def with_terminator(nibbles):
nibbles = nibbles[:]
if not nibbles or nibbles[-1] != NIBBLE_TERMINATOR:
nibbles.append(NIBBLE_TERMINATOR)
return nibbles
| def with_terminator(nibbles):
| nibbles = nibbles[:]
if not nibbles or nibbles[-1] != NIBBLE_TERMINATOR:
nibbles.append(NIBBLE_TERMINATOR)
return nibbles
| ].add(node)
def add_exempt(self, node):
self.exempt[-1].add(rlp_encode(node))
def get_mode(self):
return self.mode[-1]
proof = ProofConstructor()
class InvalidSPVProof(Exception):
pass
def with_terminator(nibbles):
| 64 | 64 | 58 | 9 | 54 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | with_terminator | with_terminator | 110 | 114 | 110 | 110 | db130a17339cd905fd5e30cdb04859c759bac12f | bigcode/the-stack | train |
d90b49e1e99f835e8730f4d0 | train | class | class InvalidSPVProof(Exception):
pass
| class InvalidSPVProof(Exception):
| pass
| in self.exempt[-1]:
self.nodes[-1].add(node)
def add_exempt(self, node):
self.exempt[-1].add(rlp_encode(node))
def get_mode(self):
return self.mode[-1]
proof = ProofConstructor()
class InvalidSPVProof(Exception):
| 64 | 64 | 10 | 7 | 57 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | InvalidSPVProof | InvalidSPVProof | 106 | 107 | 106 | 106 | 96681b168be1c6b1d97d0d41b144b3cac1d0272b | bigcode/the-stack | train |
1ebb5073107e53bfc62e8138 | train | function | def unpack_to_nibbles(bindata):
"""unpack packed binary data to nibbles
:param bindata: binary packed from nibbles
:return: nibbles sequence, may have a terminator
"""
o = bin_to_nibbles(bindata)
flags = o[0]
if flags & 2:
o.append(NIBBLE_TERMINATOR)
if flags & 1 == 1:
o... | def unpack_to_nibbles(bindata):
| """unpack packed binary data to nibbles
:param bindata: binary packed from nibbles
:return: nibbles sequence, may have a terminator
"""
o = bin_to_nibbles(bindata)
flags = o[0]
if flags & 2:
o.append(NIBBLE_TERMINATOR)
if flags & 1 == 1:
o = o[1:]
else:
o = o... | 0] + nibbles
o = b''
for i in range(0, len(nibbles), 2):
o += ascii_chr(16 * nibbles[i] + nibbles[i + 1])
return o
def unpack_to_nibbles(bindata):
| 64 | 64 | 117 | 9 | 54 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | unpack_to_nibbles | unpack_to_nibbles | 164 | 178 | 164 | 164 | e6f5921ff02d24db1c5655d22a898bbbc92e5052 | bigcode/the-stack | train |
84dc75b1ae1c19c5ebee0ef2 | train | function | def key_nibbles_from_key_value_node(node):
return without_terminator(unpack_to_nibbles(node[0]))
| def key_nibbles_from_key_value_node(node):
| return without_terminator(unpack_to_nibbles(node[0]))
| NODE_TYPE_BLANK,
NODE_TYPE_LEAF,
NODE_TYPE_EXTENSION,
NODE_TYPE_BRANCH
) = tuple(range(4))
def is_key_value_type(node_type):
return node_type in [NODE_TYPE_LEAF,
NODE_TYPE_EXTENSION]
def key_nibbles_from_key_value_node(node):
| 64 | 64 | 27 | 11 | 53 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | key_nibbles_from_key_value_node | key_nibbles_from_key_value_node | 203 | 204 | 203 | 203 | 39082bfe9e2e604d7c0a2e089e73b65d54556a8f | bigcode/the-stack | train |
1b1002a2633bc7ed38e38539 | train | class | class Trie:
def __init__(self, db: BaseDB, root_hash=BLANK_ROOT, transient=False):
'''it also present a dictionary like interface
:param db key value database
:root: blank or trie node in form of [key, value] or [v0,v1..v15,v]
'''
self._db = db # Pass in a database object ... | class Trie:
| def __init__(self, db: BaseDB, root_hash=BLANK_ROOT, transient=False):
'''it also present a dictionary like interface
:param db key value database
:root: blank or trie node in form of [key, value] or [v0,v1..v15,v]
'''
self._db = db # Pass in a database object directly
... | sequence, may have a terminator
"""
o = bin_to_nibbles(bindata)
flags = o[0]
if flags & 2:
o.append(NIBBLE_TERMINATOR)
if flags & 1 == 1:
o = o[1:]
else:
o = o[2:]
return o
def starts_with(full, part):
''' test whether the items in the part is
the leading i... | 256 | 256 | 7,842 | 3 | 253 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | Trie | Trie | 216 | 1,179 | 216 | 217 | 0a09bf382316b76dedd305e11df1ee638a1d7cf0 | bigcode/the-stack | train |
cf9a762f69b3be74d4147f81 | train | function | def adapt_terminator(nibbles, has_terminator):
if has_terminator:
return with_terminator(nibbles)
else:
return without_terminator(nibbles)
| def adapt_terminator(nibbles, has_terminator):
| if has_terminator:
return with_terminator(nibbles)
else:
return without_terminator(nibbles)
| terminator(nibbles):
nibbles = nibbles[:]
if nibbles and nibbles[-1] == NIBBLE_TERMINATOR:
del nibbles[-1]
return nibbles
def adapt_terminator(nibbles, has_terminator):
| 64 | 64 | 44 | 14 | 49 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | adapt_terminator | adapt_terminator | 124 | 128 | 124 | 124 | c0714e9b22cb69859d60b980af201ca98d4a926b | bigcode/the-stack | train |
08b3659e60009d715c5f2e05 | train | function | def pack_nibbles(nibbles):
"""pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator
"""
if nibbles[-1] == NIBBLE_TERMINATOR:
flags = 2
nibbles = nibbles[:-1]
else:
flags = 0
oddlen = len(nibbles) % 2
flags |= oddlen # set lowest bit if ... | def pack_nibbles(nibbles):
| """pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator
"""
if nibbles[-1] == NIBBLE_TERMINATOR:
flags = 2
nibbles = nibbles[:-1]
else:
flags = 0
oddlen = len(nibbles) % 2
flags |= oddlen # set lowest bit if odd number of nibbles
i... | [:]
if nibbles and nibbles[-1] == NIBBLE_TERMINATOR:
del nibbles[-1]
if len(nibbles) % 2:
del nibbles[0]
return nibbles
def pack_nibbles(nibbles):
| 64 | 64 | 196 | 9 | 54 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | pack_nibbles | pack_nibbles | 140 | 161 | 140 | 140 | 506584cebd25250f020f3ab39e4a360265ff59fd | bigcode/the-stack | train |
4cd980ce01d7b17eb59d759f | train | function | def nibbles_to_bin(nibbles):
if any(x > 15 or x < 0 for x in nibbles):
raise Exception("nibbles can only be [0,..15]")
if len(nibbles) % 2:
raise Exception("nibbles must be of even numbers")
res = b''
for i in range(0, len(nibbles), 2):
res += ascii_chr(16 * nibbles[i] + nibble... | def nibbles_to_bin(nibbles):
| if any(x > 15 or x < 0 for x in nibbles):
raise Exception("nibbles can only be [0,..15]")
if len(nibbles) % 2:
raise Exception("nibbles must be of even numbers")
res = b''
for i in range(0, len(nibbles), 2):
res += ascii_chr(16 * nibbles[i] + nibbles[i + 1])
return res
| _to_nibbles("hello")
[6, 8, 6, 5, 6, 12, 6, 12, 6, 15]
"""
return [hti[c] for c in encode_hex(s)]
def nibbles_to_bin(nibbles):
| 63 | 64 | 116 | 10 | 53 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | nibbles_to_bin | nibbles_to_bin | 37 | 47 | 37 | 37 | 022bfa0c36b1bfc66bda6034de75e932222c9de8 | bigcode/the-stack | train |
868d59553fa8d0ac25650801 | train | function | def without_terminator(nibbles):
nibbles = nibbles[:]
if nibbles and nibbles[-1] == NIBBLE_TERMINATOR:
del nibbles[-1]
return nibbles
| def without_terminator(nibbles):
| nibbles = nibbles[:]
if nibbles and nibbles[-1] == NIBBLE_TERMINATOR:
del nibbles[-1]
return nibbles
| terminator(nibbles):
nibbles = nibbles[:]
if not nibbles or nibbles[-1] != NIBBLE_TERMINATOR:
nibbles.append(NIBBLE_TERMINATOR)
return nibbles
def without_terminator(nibbles):
| 64 | 64 | 53 | 9 | 54 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | without_terminator | without_terminator | 117 | 121 | 117 | 117 | 23a0592c7f3fc0d3105ce1773625bff0f5986177 | bigcode/the-stack | train |
abea7f81ef50440f39b7861e | train | function | def is_key_value_type(node_type):
return node_type in [NODE_TYPE_LEAF,
NODE_TYPE_EXTENSION]
| def is_key_value_type(node_type):
| return node_type in [NODE_TYPE_LEAF,
NODE_TYPE_EXTENSION]
|
'''
if len(full) < len(part):
return False
return full[:len(part)] == part
(
NODE_TYPE_BLANK,
NODE_TYPE_LEAF,
NODE_TYPE_EXTENSION,
NODE_TYPE_BRANCH
) = tuple(range(4))
def is_key_value_type(node_type):
| 64 | 64 | 24 | 8 | 56 | andkononykhin/plenum | state/trie/pruning_trie.py | Python | is_key_value_type | is_key_value_type | 198 | 200 | 198 | 198 | ad639722bdc71ec6d849566777355fc1d27e5323 | bigcode/the-stack | train |
e28b2069dfa37aad73f8260e | train | function | def gen_pssm_40(data):
'''
data: pssm matrix array
'''
sum = data.sum(axis = 0) #columns sum
avg = sum / data.shape[0]
return sum,avg
| def gen_pssm_40(data):
| '''
data: pssm matrix array
'''
sum = data.sum(axis = 0) #columns sum
avg = sum / data.shape[0]
return sum,avg
| 矩阵后20列-pssmp_mo
data_20.extend(data_40)
data.append(data_20)
line=pssm_file.readline()
pssm_file.close()
data_arr = np.array(data)
return data_arr
def gen_pssm_40(data):
| 64 | 64 | 51 | 8 | 55 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | gen_pssm_40 | gen_pssm_40 | 100 | 106 | 100 | 100 | db777a80ccbc186027161858fb8c28d43f9eeaf5 | bigcode/the-stack | train |
86386e2d47070d57e437fb7f | train | function | def make_vec_inputs(pssm_dir, hmm_dir, facsv_path, save_dir):
df = pd.read_csv(facsv_path)
ignore_list = []
for row in tqdm(df.itertuples()):
# print(row['key'], row['label'], row['seq'])
if len(row) == 3:
key, label, seq = row[1], None, row[2]
elif len(row) == 4:
... | def make_vec_inputs(pssm_dir, hmm_dir, facsv_path, save_dir):
| df = pd.read_csv(facsv_path)
ignore_list = []
for row in tqdm(df.itertuples()):
# print(row['key'], row['label'], row['seq'])
if len(row) == 3:
key, label, seq = row[1], None, row[2]
elif len(row) == 4:
key, label, seq = row[1], row[2], row[3]
pssm_pat... | acc_hmm_'+str(x)] = np.concatenate([ac_hmm, cc_hmm])
cur_dict['sxg_hmm_'+str(x - 1)] = gen_sxg(cur_dict['hmm'], x-1)
return cur_dict
def make_vec_inputs(pssm_dir, hmm_dir, facsv_path, save_dir):
| 73 | 73 | 245 | 18 | 54 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | make_vec_inputs | make_vec_inputs | 169 | 188 | 169 | 169 | 5ffddf1e9b9e474ddc84f6846e731d8ede0bff35 | bigcode/the-stack | train |
08ad6853c51720625b0c845b | train | function | def make_one_sample(pssm_path, hmm_path, id, seq, label):
cur_dict = {}
cur_dict['id'] = id
cur_dict['seq'] = seq
if label:
cur_dict['label'] = label
cur_dict['pssm'] = read_pssm_file(pssm_path)
cur_dict['pssm_sum'] = cur_dict['pssm'].sum(axis=0)
cur_dict['pssm_avg'] = cur_dict['pss... | def make_one_sample(pssm_path, hmm_path, id, seq, label):
| cur_dict = {}
cur_dict['id'] = id
cur_dict['seq'] = seq
if label:
cur_dict['label'] = label
cur_dict['pssm'] = read_pssm_file(pssm_path)
cur_dict['pssm_sum'] = cur_dict['pssm'].sum(axis=0)
cur_dict['pssm_avg'] = cur_dict['pssm_sum'] / cur_dict['pssm'].shape[0]
cur_dict['hmm'] =... | )/(data.shape[0]-LG)
return sum
def gen_sxg(data,x):
new_data = np.zeros((data.shape[0]-x-1,400))
for i in range(20):
for j in range(20):
new_data[:,i*20+j] = data[0:data.shape[0]-x-1,i]*data[x+1:data.shape[0],j]
sum = new_data.sum(axis = 0)
return sum
def make_one_sample(pssm_p... | 120 | 120 | 403 | 17 | 102 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | make_one_sample | make_one_sample | 141 | 167 | 141 | 141 | d5c8e3848eb496df9c9fd6b8e1276b829a0d95d1 | bigcode/the-stack | train |
98a084337ca540851b7aa96a | train | function | def gen_sxg(data,x):
new_data = np.zeros((data.shape[0]-x-1,400))
for i in range(20):
for j in range(20):
new_data[:,i*20+j] = data[0:data.shape[0]-x-1,i]*data[x+1:data.shape[0],j]
sum = new_data.sum(axis = 0)
return sum
| def gen_sxg(data,x):
| new_data = np.zeros((data.shape[0]-x-1,400))
for i in range(20):
for j in range(20):
new_data[:,i*20+j] = data[0:data.shape[0]-x-1,i]*data[x+1:data.shape[0],j]
sum = new_data.sum(axis = 0)
return sum
| :
new_data[:,count] = data[0:data.shape[0]-LG,i]*data[LG:data.shape[0],j]
count +=1
sum = new_data.sum(axis = 0)/(data.shape[0]-LG)
return sum
def gen_sxg(data,x):
| 64 | 64 | 91 | 8 | 55 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | gen_sxg | gen_sxg | 131 | 137 | 131 | 131 | 0d92fd4cf798258794623a1ff77717ec3cf50a8f | bigcode/the-stack | train |
1167bb054fb4be20fa6b64a4 | train | function | def gen_ac(data,LG,avg):
'''
data: pssm matrix array,(L,20)
LG: separate parameter
'''
data = data-avg
new_data = data[0:data.shape[0]-LG]*data[LG:data.shape[0]]
sum = new_data.sum(axis = 0)/(data.shape[0]-LG)
return sum
| def gen_ac(data,LG,avg):
| '''
data: pssm matrix array,(L,20)
LG: separate parameter
'''
data = data-avg
new_data = data[0:data.shape[0]-LG]*data[LG:data.shape[0]]
sum = new_data.sum(axis = 0)/(data.shape[0]-LG)
return sum
| return data_arr
def gen_pssm_40(data):
'''
data: pssm matrix array
'''
sum = data.sum(axis = 0) #columns sum
avg = sum / data.shape[0]
return sum,avg
def gen_ac(data,LG,avg):
| 64 | 64 | 83 | 9 | 54 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | gen_ac | gen_ac | 108 | 116 | 108 | 108 | b453732f80cd7977bdd84bf4f41e45af916fb19b | bigcode/the-stack | train |
25ced003d64f5105e37be91e | train | function | def read_hmm_file(file_path):
'''
filepath: pssm file
hmm_matrix: matrix of hmm, (L,20)
'''
with open(file_path) as hmm_file:
# 1. find hmm line
line = hmm_file.readline()
is_hmm = False
while line:
is_hmm = line.startswith('HMM A')
line = h... | def read_hmm_file(file_path):
| '''
filepath: pssm file
hmm_matrix: matrix of hmm, (L,20)
'''
with open(file_path) as hmm_file:
# 1. find hmm line
line = hmm_file.readline()
is_hmm = False
while line:
is_hmm = line.startswith('HMM A')
line = hmm_file.readline()
... | "X": [[20], -0.04, 0],
"X": [20, 20, 20, 20, -0.04, 0],
"Z": [20, 20, 20, 20, -0.04, 0]
}
def read_hmm_file(file_path):
| 71 | 71 | 239 | 8 | 63 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | read_hmm_file | read_hmm_file | 44 | 75 | 44 | 44 | 4b04435a816643cb7d00540eeaaee4b63456cded | bigcode/the-stack | train |
cffd002862031c3ea8806d14 | train | function | def get_list(pssm_dir, df, mode, hmm_dir):
'''
'''
all_filenames = sorted(os.listdir(pssm_dir))
filenames = [filename for filename in all_filenames if filename.startswith(mode)]
output_list = []
for filename in tqdm(filenames):
i = int(re.findall('(\d+)',filename)[0])-1
... | def get_list(pssm_dir, df, mode, hmm_dir):
| '''
'''
all_filenames = sorted(os.listdir(pssm_dir))
filenames = [filename for filename in all_filenames if filename.startswith(mode)]
output_list = []
for filename in tqdm(filenames):
i = int(re.findall('(\d+)',filename)[0])-1
cur_dict = {}
cur_dict['id'] =... | mm_dir, key+'.txt')
if not os.path.exists(pssm_path):
ignore_list.append(pssm_path)
continue
sample_dict = make_one_seq_sample(pssm_path, hmm_path, key, seq, label, standard)
out_list.append(sample_dict)
# save_path = os.path.join(save_dir, key+'.pkl')
# w... | 135 | 135 | 452 | 14 | 120 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | get_list | get_list | 231 | 264 | 231 | 231 | 888f2ce9adb8eb46d99cd00ddd2809b30022fd33 | bigcode/the-stack | train |
9fb9a0f3d2337351cb5e1792 | train | function | def make_one_seq_sample(pssm_path, hmm_path, id, seq, label, standard):
cur_dict = {}
cur_dict['id'] = id
cur_dict['seq'] = seq
if label:
cur_dict['label'] = label
pssm_mat = read_pssm_file(pssm_path) # n*40
hmm_mat = read_hmm_file(hmm_path) # n*20
seq_feats = np.array([amino_feats... | def make_one_seq_sample(pssm_path, hmm_path, id, seq, label, standard):
| cur_dict = {}
cur_dict['id'] = id
cur_dict['seq'] = seq
if label:
cur_dict['label'] = label
pssm_mat = read_pssm_file(pssm_path) # n*40
hmm_mat = read_hmm_file(hmm_path) # n*20
seq_feats = np.array([amino_feats[amino] for amino in seq.upper()]) # n*6
cur_dict['feats'] = np.conc... | with open(save_path, 'wb') as pkl_file:
pkl.dump(sample_dict, pkl_file)
print('not found pssm files: ', ignore_list)
return ignore_list
def make_one_seq_sample(pssm_path, hmm_path, id, seq, label, standard):
| 64 | 64 | 176 | 20 | 43 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | make_one_seq_sample | make_one_seq_sample | 191 | 206 | 191 | 191 | 93fc07212c3492d9da5048c0a1c78984ac4421db | bigcode/the-stack | train |
c6aa111a2d5ef8da58b82150 | train | function | def restore(pssm_dir, hmm_dir, save_dir):
test_df = pd.read_csv('/staff/minfanzhao/workspace/protein-pre/dataset/test.csv')
train_df = pd.read_csv('/staff/minfanzhao/workspace/protein-pre/dataset/train.csv')
train_list = get_list(pssm_dir, train_df, 'train', hmm_dir)
test_list = get_list(pssm_dir, test_... | def restore(pssm_dir, hmm_dir, save_dir):
| test_df = pd.read_csv('/staff/minfanzhao/workspace/protein-pre/dataset/test.csv')
train_df = pd.read_csv('/staff/minfanzhao/workspace/protein-pre/dataset/train.csv')
train_list = get_list(pssm_dir, train_df, 'train', hmm_dir)
test_list = get_list(pssm_dir, test_df, 'test', hmm_dir)
train_save_p... | .concatenate([ac_hmm, cc_hmm])
cur_dict['sxg_hmm_'+str(x - 1)] = gen_sxg(cur_dict['hmm'], x-1)
output_list.append(cur_dict)
return output_list
def restore(pssm_dir, hmm_dir, save_dir):
| 64 | 64 | 176 | 12 | 51 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | restore | restore | 268 | 281 | 268 | 268 | 8db38cda5963bcdd8d4d92c314b63087961ffe1b | bigcode/the-stack | train |
7cebf02e70b9d02c153089ba | train | function | def make_seq_inputs(pssm_dir, hmm_dir, facsv_path, standard=False):
df = pd.read_csv(facsv_path)
ignore_list = []
out_list = []
for row in tqdm(df.itertuples()):
if len(row) == 3: # test
key, label, seq = row[1], None, row[2]
elif len(row) == 4: # train
key, label... | def make_seq_inputs(pssm_dir, hmm_dir, facsv_path, standard=False):
| df = pd.read_csv(facsv_path)
ignore_list = []
out_list = []
for row in tqdm(df.itertuples()):
if len(row) == 3: # test
key, label, seq = row[1], None, row[2]
elif len(row) == 4: # train
key, label, seq = row[1], row[2], row[3]
pssm_path = os.path.join(pss... | cur_dict['feats'] = np.concatenate([seq_feats, pssm_mat, hmm_mat], axis=1)
if standard:
scalar = StandardScaler()
cur_dict['feats'] = scalar.fit_transform(cur_dict['feats'])
return cur_dict
def make_seq_inputs(pssm_dir, hmm_dir, facsv_path, standard=False):
| 76 | 76 | 255 | 18 | 57 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | make_seq_inputs | make_seq_inputs | 208 | 229 | 208 | 208 | 6a33f6705c6f507056f779c123b59ccc34588d43 | bigcode/the-stack | train |
a7f2ca6fe583842d2bb018f1 | train | function | def read_pssm_file(filepath):
'''
filepath: pssm file
data_20:matrix of gen_pssm,(L,40)
'''
pssm_file = open(filepath)
line=pssm_file.readline()
data = []
while line:
items=line.strip().split()
if items: #不是空列表
if items[0].isdigit(): #列表的第一个元素是数字
... | def read_pssm_file(filepath):
| '''
filepath: pssm file
data_20:matrix of gen_pssm,(L,40)
'''
pssm_file = open(filepath)
line=pssm_file.readline()
data = []
while line:
items=line.strip().split()
if items: #不是空列表
if items[0].isdigit(): #列表的第一个元素是数字
data_20 = [float(items[... | in elmts[2:-1]]
feature_list.append(elmts)
line = hmm_file.readline()
# 3. exchange columns
hmm_matrix = np.array(feature_list)
hmm_matrix = hmm_matrix[:, map_index_list]
return hmm_matrix
def read_pssm_file(filepath):
| 63 | 64 | 209 | 7 | 55 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | read_pssm_file | read_pssm_file | 79 | 98 | 79 | 79 | b9fb69fe9b1ef1d3a3f802f41439998a4f5c00fe | bigcode/the-stack | train |
85faeedab3a5b806a862037f | train | function | def gen_cc(data,LG,avg):
data = data-avg
new_data = np.zeros((data.shape[0]-LG,380))
count = 0
for i in range(20):
for j in range(20):
if i!=j:
new_data[:,count] = data[0:data.shape[0]-LG,i]*data[LG:data.shape[0],j]
count +=1
sum = new_data.su... | def gen_cc(data,LG,avg):
| data = data-avg
new_data = np.zeros((data.shape[0]-LG,380))
count = 0
for i in range(20):
for j in range(20):
if i!=j:
new_data[:,count] = data[0:data.shape[0]-LG,i]*data[LG:data.shape[0],j]
count +=1
sum = new_data.sum(axis = 0)/(data.shape[0... | parameter
'''
data = data-avg
new_data = data[0:data.shape[0]-LG]*data[LG:data.shape[0]]
sum = new_data.sum(axis = 0)/(data.shape[0]-LG)
return sum
def gen_cc(data,LG,avg):
| 64 | 64 | 115 | 9 | 54 | shijun18/Protein-Structure-Predict | converter/gen_model_input.py | Python | gen_cc | gen_cc | 118 | 129 | 118 | 118 | 66c52befc0fcb64900614a732fb61da484c5c841 | bigcode/the-stack | train |
862cddf553dd426f60547bac | train | function | def main():
pygame.init()
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity();
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
run()
| def main():
| pygame.init()
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity();
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
run()
| ', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
def main():
| 63 | 64 | 76 | 3 | 60 | hmirzaei/camera-samples | python/cube.py | Python | main | main | 118 | 128 | 118 | 118 | 097341ce183c3b7ad229c92fdba9ebe3d2a219a4 | bigcode/the-stack | train |
1ceeae8d7b156f1930657d41 | train | function | def Axes():
qobj = gluNewQuadric();
gluQuadricDrawStyle( qobj, GLU_FILL );
glPushMatrix();
glColor3f(1,0,0);
glRotatef(90,0,1,0);
gluCylinder(qobj, 0.05, 0.05, 3, 10, 16);
glPopMatrix();
glPushMatrix();
glColor3f(0,1,0);
glRotatef(-90,1,0,0);
gluCylinder(qobj, 0.05, 0.05, 3, 10, 16);
glPopMatr... | def Axes():
| qobj = gluNewQuadric();
gluQuadricDrawStyle( qobj, GLU_FILL );
glPushMatrix();
glColor3f(1,0,0);
glRotatef(90,0,1,0);
gluCylinder(qobj, 0.05, 0.05, 3, 10, 16);
glPopMatrix();
glPushMatrix();
glColor3f(0,1,0);
glRotatef(-90,1,0,0);
gluCylinder(qobj, 0.05, 0.05, 3, 10, 16);
glPopMatrix();
glP... | 5,4),
(5,7)
)
def Cube():
glColor3f(1,1,1)
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def Axes():
| 64 | 64 | 194 | 4 | 60 | hmirzaei/camera-samples | python/cube.py | Python | Axes | Axes | 45 | 64 | 45 | 45 | 4ed67ca462e9ae428d0f58a17a03dbc5b481395a | bigcode/the-stack | train |
4ae35a9bc16e1e31e4346132 | train | function | def Cube():
glColor3f(1,1,1)
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
| def Cube():
| glColor3f(1,1,1)
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
| (0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7)
)
def Cube():
| 64 | 64 | 48 | 3 | 61 | hmirzaei/camera-samples | python/cube.py | Python | Cube | Cube | 37 | 43 | 37 | 37 | 67efb4a8524f64999b6f97859b475ca46f027297 | bigcode/the-stack | train |
140f50c27582c9d5e7afcd74 | train | function | def run(server_class=HTTPServer, handler_class=S, port=8000):
logging.basicConfig(level=logging.ERROR)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
... | def run(server_class=HTTPServer, handler_class=S, port=8000):
| logging.basicConfig(level=logging.ERROR)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
| f(rpy['r'], 1, 0, 0)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
Cube()
Axes()
pygame.display.flip()
pygame.time.wait(10)
def run(server_class=HTTPServer, handler_class=S, port=8000):
| 64 | 64 | 90 | 17 | 47 | hmirzaei/camera-samples | python/cube.py | Python | run | run | 104 | 114 | 104 | 104 | 715f148bb0918a2c787ec9bbce4648376cd021d3 | bigcode/the-stack | train |
45861336029474e414d9f076 | train | class | class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
self._set_respon... | class S(BaseHTTPRequestHandler):
| def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
self._set_response()
self.wfile.write("GE... | 3f(0,1,0);
glRotatef(-90,1,0,0);
gluCylinder(qobj, 0.05, 0.05, 3, 10, 16);
glPopMatrix();
glPushMatrix();
glColor3f(0,0,1);
gluCylinder(qobj, 0.05, 0.05, 3, 10, 16);
glPopMatrix();
class S(BaseHTTPRequestHandler):
| 105 | 105 | 350 | 6 | 99 | hmirzaei/camera-samples | python/cube.py | Python | S | S | 67 | 101 | 67 | 67 | 614b22f87693c8953a616470b8a50e3a92ab07af | bigcode/the-stack | train |
231b759fc4b00e450795f190 | train | class | class TestMutationDB:
@classmethod
def setup_class(self):
BED4_file = TEST_PATH + "/data/hxb2_pol.bed"
mutation_db_file = TEST_PATH + "/data/mutation_db.tsv"
genes = parse_BED4_file(BED4_file, "hxb2_pol")
self.mutation_db = MutationDB(mutation_db_file, genes)
def test_muta... | class TestMutationDB:
@classmethod
| def setup_class(self):
BED4_file = TEST_PATH + "/data/hxb2_pol.bed"
mutation_db_file = TEST_PATH + "/data/mutation_db.tsv"
genes = parse_BED4_file(BED4_file, "hxb2_pol")
self.mutation_db = MutationDB(mutation_db_file, genes)
def test_mutations_at(self):
# Our pos is o... | See the License for the
specific language governing permissions and limitations under the License.
"""
import pytest
import os
from quasitools.mutations import MutationDB
from quasitools.parsers.genes_file_parser import parse_BED4_file
TEST_PATH = os.path.dirname(os.path.abspath(__file__))
class TestMutationDB:
... | 70 | 71 | 237 | 9 | 61 | phac-nml/quasitools | tests/test_mutation_db.py | Python | TestMutationDB | TestMutationDB | 26 | 60 | 26 | 27 | 09847af0cef579ad99d53a026943e6946d78afab | bigcode/the-stack | train |
a70909e073be557fc543d4a9 | train | function | def verifyconnection():
global save
while True:
try:
r = requests.get("http://127.0.0.1:4040/api/tunnels/command_line%20(http)").json()
count = r['metrics']['conns']['count']
if count > save:
save = count
logip()
except... | def verifyconnection():
| global save
while True:
try:
r = requests.get("http://127.0.0.1:4040/api/tunnels/command_line%20(http)").json()
count = r['metrics']['conns']['count']
if count > save:
save = count
logip()
except:
pass
... | : {}\n[ + ] IP ADDRESS: {}\n[ + ] User Agent: {}".format(
iplist.index(ip),
date, ip,
useragent)
print(info)
if args.output_file:
log.write(info)
log.close()
c += 1
def verifyconnection():
| 64 | 64 | 84 | 4 | 59 | Gabriel-Blanes/IPgrabber | ipgrab/ipgrab.py | Python | verifyconnection | verifyconnection | 60 | 72 | 60 | 60 | 0a2bc3ea7065a99f01e956b5e264cc951d6e15d0 | bigcode/the-stack | train |
f70857cb11bcb08e061397d0 | train | function | def logip():
global iplist
c = 0
r = requests.get('http://localhost:4040/api/requests/http').json()
if args.output_file:
log = open(args.output_file, "a+")
for i in r['requests']:
if r['requests'][c]['request']['headers']['X-Forwarded-For'][0] not in iplist:
ip ... | def logip():
| global iplist
c = 0
r = requests.get('http://localhost:4040/api/requests/http').json()
if args.output_file:
log = open(args.output_file, "a+")
for i in r['requests']:
if r['requests'][c]['request']['headers']['X-Forwarded-For'][0] not in iplist:
ip = r['requests'... | (BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(302)
self.send_header('Location', args.redirect_url)
self.end_headers()
def log_message(self, format, *args):
return
HTTPServer(("", int(args.port)), Redirect).serve_forever()
de... | 66 | 66 | 220 | 4 | 62 | Gabriel-Blanes/IPgrabber | ipgrab/ipgrab.py | Python | logip | logip | 35 | 57 | 35 | 35 | 70e85b3a581985b6809c37ef67493b646ca26bf7 | bigcode/the-stack | train |
e9b5de361af9a6bde64f8e3e | train | function | def redirect():
class Redirect(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(302)
self.send_header('Location', args.redirect_url)
self.end_headers()
def log_message(self, format, *args):
return
HTTPServer(("", int(args.p... | def redirect():
| class Redirect(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(302)
self.send_header('Location', args.redirect_url)
self.end_headers()
def log_message(self, format, *args):
return
HTTPServer(("", int(args.port)), Redirect).... | rok-path', type=str, default='ngrok', help="NGROK path")
parser.add_argument('-o', '--output-file', type=str, help="output file path")
args = parser.parse_args()
save = 0 # count connections
iplist = [] # IP log
def redirect():
| 64 | 64 | 68 | 3 | 60 | Gabriel-Blanes/IPgrabber | ipgrab/ipgrab.py | Python | redirect | redirect | 22 | 32 | 22 | 22 | 899f76f8dd8a15e6b04907f1e48f1cef4c3f78a0 | bigcode/the-stack | train |
c006e9bee5aae236ee7d1d30 | train | function | def startngrok():
try:
if platform.system() == "Windows":
os.system("start {} http {}".format(args.ngrok_path, args.port))
else:
os.system("{} http {} > /dev/null &".format(args.ngrok_path, args.port))
print("[ ... ] Starting ngrok [ ... ] \n")
time.s... | def startngrok():
| try:
if platform.system() == "Windows":
os.system("start {} http {}".format(args.ngrok_path, args.port))
else:
os.system("{} http {} > /dev/null &".format(args.ngrok_path, args.port))
print("[ ... ] Starting ngrok [ ... ] \n")
time.sleep(3)
r ... | 0.0.1:4040/api/tunnels/command_line%20(http)").json()
count = r['metrics']['conns']['count']
if count > save:
save = count
logip()
except:
pass
time.sleep(5)
def startngrok():
| 64 | 64 | 177 | 5 | 59 | Gabriel-Blanes/IPgrabber | ipgrab/ipgrab.py | Python | startngrok | startngrok | 75 | 91 | 75 | 75 | b19df1d08a8fdf162de6f755251590241f3f584f | bigcode/the-stack | train |
f79a915d02dd44fad9665d39 | train | function | def train(model, opt, scheduler, train_loader, dev):
scheduler.step()
model.train()
total_loss = 0
num_batches = 0
total_correct = 0
count = 0
with tqdm.tqdm(train_loader, ascii=True) as tq:
for data, label in tq:
num_examples = label.shape[0]
data, label = ... | def train(model, opt, scheduler, train_loader, dev):
| scheduler.step()
model.train()
total_loss = 0
num_batches = 0
total_correct = 0
count = 0
with tqdm.tqdm(train_loader, ascii=True) as tq:
for data, label in tq:
num_examples = label.shape[0]
data, label = data.to(dev), label.to(dev).squeeze().long()
... | ('https://s3.us-east-2.amazonaws.com/dgl.ai/dataset/modelnet40-sampled-2048.h5', local_path)
CustomDataLoader = partial(
DataLoader,
num_workers=num_workers,
batch_size=batch_size,
shuffle=True,
drop_last=True)
def train(model, opt, scheduler, train_loader, dev):
| 74 | 74 | 249 | 13 | 61 | vipermu/dgl | examples/pytorch/pointcloud/main.py | Python | train | train | 40 | 72 | 40 | 40 | 84d07b28cc390ef13edf2a8e9868daca568d07df | bigcode/the-stack | train |
397897afc14e7f14e7945c94 | train | function | def evaluate(model, test_loader, dev):
model.eval()
total_correct = 0
count = 0
with torch.no_grad():
with tqdm.tqdm(test_loader, ascii=True) as tq:
for data, label in tq:
num_examples = label.shape[0]
data, label = data.to(dev), label.to(dev).squeez... | def evaluate(model, test_loader, dev):
| model.eval()
total_correct = 0
count = 0
with torch.no_grad():
with tqdm.tqdm(test_loader, ascii=True) as tq:
for data, label in tq:
num_examples = label.shape[0]
data, label = data.to(dev), label.to(dev).squeeze().long()
logits = mod... | % loss,
'AvgLoss': '%.5f' % (total_loss / num_batches),
'Acc': '%.5f' % (correct / num_examples),
'AvgAcc': '%.5f' % (total_correct / count)})
def evaluate(model, test_loader, dev):
| 63 | 64 | 169 | 9 | 55 | vipermu/dgl | examples/pytorch/pointcloud/main.py | Python | evaluate | evaluate | 74 | 96 | 74 | 74 | 3d20f162c58fe416ac362e8380741ace09aca569 | bigcode/the-stack | train |
34a133a8d05ec16691e71e30 | train | function | def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
... | def create_connection(db_file):
| """ create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
| #!/usr/bin/env python
import sqlite3
import csv
import pandas as pd
import copy
import numpy as np
from sqlite3 import Error
def create_connection(db_file):
| 38 | 64 | 75 | 6 | 31 | MattMont/Django | Stuff/Scripts/csvParse.py | Python | create_connection | create_connection | 10 | 22 | 10 | 10 | abd89e8c6ebee9932ae1d326002ac56be1541d26 | bigcode/the-stack | train |
9f2dfe3e754739b37a27f4a0 | train | function | def insertData(homeList, conn):
curr = conn.cursor()
count = 0
for dataPoint in homeList:
addy = dataPoint[0]
est = dataPoint[1]
ni = dataPoint[2]
lt = dataPoint[3].astype(float)
ln = dataPoint[4].astype(float)
#lt = lt.Series.astype(float)
#ln = ln.Se... | def insertData(homeList, conn):
| curr = conn.cursor()
count = 0
for dataPoint in homeList:
addy = dataPoint[0]
est = dataPoint[1]
ni = dataPoint[2]
lt = dataPoint[3].astype(float)
ln = dataPoint[4].astype(float)
#lt = lt.Series.astype(float)
#ln = ln.Series.astype(float)
pri... | sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
# def create_address(conn, address):
# """
# Add address to database
# """
# sql = '''INSERT INTO address'''
def insertData(homeList, conn):
| 64 | 64 | 192 | 8 | 56 | MattMont/Django | Stuff/Scripts/csvParse.py | Python | insertData | insertData | 30 | 53 | 30 | 30 | 1b78add21d6d97ed44ba874e865d0c1839e642f4 | bigcode/the-stack | train |
70884ac4f34c335dc1c4e5e8 | train | function | def select_all_tasks(conn):
"""
Query all rows in the tasks table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM tasks")
rows = cur.fetchall()
for row in rows:
print(row)
| def select_all_tasks(conn):
| """
Query all rows in the tasks table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM tasks")
rows = cur.fetchall()
for row in rows:
print(row)
| print(type(lt))
curr.execute("INSERT INTO homevalue_homeinfo VALUES (?,?,?,?,?,?,?,?,?)", completeSet)
#conn.commit()
print("Added to database " + str(count))
count += 1
conn.commit()
print('Commited all')
def select_all_tasks(conn):
| 64 | 64 | 65 | 6 | 58 | MattMont/Django | Stuff/Scripts/csvParse.py | Python | select_all_tasks | select_all_tasks | 56 | 68 | 56 | 56 | 0a694e5084993d2d6db63cc28cf9278a9fa5fc88 | bigcode/the-stack | train |
fbb794035e52253dcb014e96 | train | function | def openCSV():
#with open('E:/revre/revreTech\EdmontonData/EdmontonHseData.csv', newline='') as csvfile:
# WINDOWS
#test = pd.read_csv('E:/revre/revreTech\EdmontonData/EdmontonHseData.csv',sep=',')
# MAC
test = pd.read_csv('~/Documents/revreTech/EdmontonData/EdmontonHseData.csv', sep=',')
# ... | def openCSV():
#with open('E:/revre/revreTech\EdmontonData/EdmontonHseData.csv', newline='') as csvfile:
# WINDOWS
#test = pd.read_csv('E:/revre/revreTech\EdmontonData/EdmontonHseData.csv',sep=',')
# MAC
| test = pd.read_csv('~/Documents/revreTech/EdmontonData/EdmontonHseData.csv', sep=',')
# get number of columns
test.columns = test.columns.str.replace('\s+','_')
masterList =[]
# Snaggin all the things
hood = test.Neighbourhood
price = test.Assessed_Value
number = test.House_Number
... | curr.execute("INSERT INTO homevalue_homeinfo VALUES (?,?,?,?,?,?,?,?,?)", completeSet)
#conn.commit()
print("Added to database " + str(count))
count += 1
conn.commit()
print('Commited all')
def select_all_tasks(conn):
"""
Query all rows in the tasks table
:param conn: the ... | 189 | 189 | 630 | 73 | 116 | MattMont/Django | Stuff/Scripts/csvParse.py | Python | openCSV | openCSV | 70 | 150 | 70 | 74 | 094fff24c6e9b833d247606132acf197e9eb4cd6 | bigcode/the-stack | train |
1da199b4f4a61fee28e0ed97 | train | function | def main():
# Windows
#database = 'E:/revre/revreTech/testSite/db.sqlite3'
# Mac
#database = '~/Documents/revreTech/db.sqlite3'
database ='../testSite/db.sqlite3'
conn = create_connection(database)
if conn == None:
print("No connection")
exit(-1)
# create a database ... | def main():
# Windows
#database = 'E:/revre/revreTech/testSite/db.sqlite3'
# Mac
#database = '~/Documents/revreTech/db.sqlite3'
| database ='../testSite/db.sqlite3'
conn = create_connection(database)
if conn == None:
print("No connection")
exit(-1)
# create a database connection
addyList, averages = openCSV()
# Connection to Database works
#conn = create_connection(database)
insertData(addyLis... | Dict[aKey][0]/aDict[aKey][1])
return masterList, nbhdavg
def main():
# Windows
#database = 'E:/revre/revreTech/testSite/db.sqlite3'
# Mac
#database = '~/Documents/revreTech/db.sqlite3'
| 64 | 64 | 118 | 42 | 21 | MattMont/Django | Stuff/Scripts/csvParse.py | Python | main | main | 153 | 173 | 153 | 158 | 29a5d9fcaf1b3204109219601ee2f3bd83b00c8e | bigcode/the-stack | train |
40616623e63c367f8bc1f2e4 | train | class | class Actor(nn.Module):
def __init__(self, env):
super(Actor, self).__init__()
self.fc1 = nn.Linear(np.array(env.single_observation_space.shape).prod(), 256)
self.fc2 = nn.Linear(256, 256)
self.fc_mu = nn.Linear(256, np.prod(env.single_action_space.shape))
def forward(self, x):
... | class Actor(nn.Module):
| def __init__(self, env):
super(Actor, self).__init__()
self.fc1 = nn.Linear(np.array(env.single_observation_space.shape).prod(), 256)
self.fc2 = nn.Linear(256, 256)
self.fc_mu = nn.Linear(256, np.prod(env.single_action_space.shape))
def forward(self, x):
x = F.relu(self.... | 256, 1)
def forward(self, x, a):
x = torch.cat([x, a], 1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
class Actor(nn.Module):
| 64 | 64 | 112 | 5 | 58 | xuanhien070594/cleanrl | cleanrl/ddpg_continuous_action.py | Python | Actor | Actor | 99 | 109 | 99 | 99 | ec264d1264dcd5779bd4a867b6015fd2132d6a96 | bigcode/the-stack | train |
c0b25d5e758cc76e29d94054 | train | function | def parse_args():
# fmt: off
parser = argparse.ArgumentParser()
parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
help="the name of this experiment")
parser.add_argument("--seed", type=int, default=1,
help="seed of the experiment")
parser.a... | def parse_args():
# fmt: off
| parser = argparse.ArgumentParser()
parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
help="the name of this experiment")
parser.add_argument("--seed", type=int, default=1,
help="seed of the experiment")
parser.add_argument("--torch-deterministi... | import argparse
import os
import random
import time
from distutils.util import strtobool
import gym
import numpy as np
import pybullet_envs # noqa
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from stable_baselines3.common.buffers import ReplayBuffer
from torch.utils.t... | 92 | 202 | 675 | 10 | 81 | xuanhien070594/cleanrl | cleanrl/ddpg_continuous_action.py | Python | parse_args | parse_args | 18 | 65 | 18 | 19 | bceead9829d6b4f311492183bb473bef658be971 | bigcode/the-stack | train |
fa15311a973f56293bd92876 | train | function | def make_env(env_id, seed, idx, capture_video, run_name):
def thunk():
env = gym.make(env_id)
env = gym.wrappers.RecordEpisodeStatistics(env)
if capture_video:
if idx == 0:
env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
env.seed(seed)
en... | def make_env(env_id, seed, idx, capture_video, run_name):
| def thunk():
env = gym.make(env_id)
env = gym.wrappers.RecordEpisodeStatistics(env)
if capture_video:
if idx == 0:
env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
env.seed(seed)
env.action_space.seed(seed)
env.observation_space.se... | .add_argument("--noise-clip", type=float, default=0.5,
help="noise clip parameter of the Target Policy Smoothing Regularization")
args = parser.parse_args()
# fmt: on
return args
def make_env(env_id, seed, idx, capture_video, run_name):
| 64 | 64 | 98 | 16 | 47 | xuanhien070594/cleanrl | cleanrl/ddpg_continuous_action.py | Python | make_env | make_env | 68 | 80 | 68 | 68 | 497c13d061f211e86f54db657278abda5bb74ee7 | bigcode/the-stack | train |
38a27b94df55e4851faaf46a | train | class | class QNetwork(nn.Module):
def __init__(self, env):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(np.array(env.single_observation_space.shape).prod() + np.prod(env.single_action_space.shape), 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 1)
def forward(se... | class QNetwork(nn.Module):
| def __init__(self, env):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(np.array(env.single_observation_space.shape).prod() + np.prod(env.single_action_space.shape), 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 1)
def forward(self, x, a):
x = torc... | 0:
env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
env.seed(seed)
env.action_space.seed(seed)
env.observation_space.seed(seed)
return env
return thunk
# ALGO LOGIC: initialize agent here:
class QNetwork(nn.Module):
| 64 | 64 | 134 | 6 | 58 | xuanhien070594/cleanrl | cleanrl/ddpg_continuous_action.py | Python | QNetwork | QNetwork | 84 | 96 | 84 | 84 | 168db25f3acb85c900687ebd945736a37bfb837b | bigcode/the-stack | train |
a5eb55294536f1ec9cdf5c07 | train | function | def euclidDistance(point1, point2):
return ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2 ) ** 0.5
| def euclidDistance(point1, point2):
| return ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2 ) ** 0.5
| ayPoints:
screen.blit(assets[2],wayPoint)
for sensorPoint in sensorPoints:
screen.blit(assets[4],(sensorPoint[0],sensorPoint[1] - assets[4].get_height()/2))
def euclidDistance(point1, point2):
| 62 | 64 | 46 | 10 | 52 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | euclidDistance | euclidDistance | 274 | 275 | 274 | 274 | 9f1b2e894351dee6f3ddb002f7eaf31cf8db011c | bigcode/the-stack | train |
62eed61b2d168d08c3022cf4 | train | function | def assessFitness(numWaypoints, time, distanceFromStart, totalDistance,speed):
#return totalDistance
return ((numWaypoints-1)**2) * 400 + totalDistance + distanceFromStart
| def assessFitness(numWaypoints, time, distanceFromStart, totalDistance,speed):
#return totalDistance
| return ((numWaypoints-1)**2) * 400 + totalDistance + distanceFromStart
| = crossover((pair[1],pair[0]))
genome = crossover(pair)
genome = mutate(genome)
nextGeneration.append(genome)
return (nextGeneration, elites)
def assessFitness(numWaypoints, time, distanceFromStart, totalDistance,speed):
#return totalDistance
| 63 | 64 | 46 | 24 | 39 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | assessFitness | assessFitness | 181 | 183 | 181 | 182 | 153d195c7cb2f561b3f1a2ac28a1210eb82ec203 | bigcode/the-stack | train |
de8f10416fe2e8c701154a25 | train | function | def gameInit():
pygame.init()
grass = pygame.image.load("../resources/images/grass.png")
road = pygame.image.load("../resources/images/road.png")
player = pygame.image.load("../resources/images/circle.png")
wayPoint = pygame.image.load("../resources/images/waypoint.png")
course = pygame.im... | def gameInit():
| pygame.init()
grass = pygame.image.load("../resources/images/grass.png")
road = pygame.image.load("../resources/images/road.png")
player = pygame.image.load("../resources/images/circle.png")
wayPoint = pygame.image.load("../resources/images/waypoint.png")
course = pygame.image.load("../reso... | 1] - assets[4].get_height()/2))
def euclidDistance(point1, point2):
return ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2 ) ** 0.5
def gameInit():
| 64 | 64 | 145 | 4 | 59 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | gameInit | gameInit | 278 | 292 | 278 | 278 | ddf9900b4bd8cd74de9f87a6126486642b935c7a | bigcode/the-stack | train |
ad5ec68ce3a694ee2f8e186a | train | function | def loadJsonCourse(fileName):
game = Game()
fileContent = open(fileName).read()
jsonData = json.loads(fileContent)
for line in jsonData["map_data"]:
game.mapData.append([int(c) for c in line.strip()])
game.wayPoints = jsonData["waypoints"]
game.startPoint = jsonData["start"]
... | def loadJsonCourse(fileName):
| game = Game()
fileContent = open(fileName).read()
jsonData = json.loads(fileContent)
for line in jsonData["map_data"]:
game.mapData.append([int(c) for c in line.strip()])
game.wayPoints = jsonData["waypoints"]
game.startPoint = jsonData["start"]
return game
| ) as file:
for line in file:
if len(start)==0:
start = [int(c) for c in line.strip().split(',')]
else:
data.append([int(c) for c in line.strip()])
return (start,data)
def loadJsonCourse(fileName):
| 64 | 64 | 85 | 7 | 57 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | loadJsonCourse | loadJsonCourse | 196 | 207 | 196 | 196 | 405d6e2929603aaa3b9ca67cd34c2801ca3ca92d | bigcode/the-stack | train |
7475a65c2439217f33c8bc30 | train | class | class Game:
wayPoints = []
wayPointIndex = 0
mapData = []
startPoint = []
def currentWaypoint(self):
return self.wayPoints[self.wayPointIndex]
| class Game:
| wayPoints = []
wayPointIndex = 0
mapData = []
startPoint = []
def currentWaypoint(self):
return self.wayPoints[self.wayPointIndex]
| import sys
import pygame
from pygame.locals import *
import time
import math
import random
import json
import numpy
import itertools
class Game:
| 32 | 64 | 44 | 3 | 28 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | Game | Game | 11 | 17 | 11 | 11 | e224958c5b42bb9770ba18caa78f0a6de4be4bb1 | bigcode/the-stack | train |
0b656f277562879b59eccabc | train | function | def main(argv):
if len(argv)==2 and argv[0] == '-f':
weightsFile = argv[1]
generation = loadWeights(weightsFile)
else:
weightsFile ='bestWeightsSig.json'
generation = createInitialPopulation(100)
(game,screen,assets) = gameInit()
allGenomes = []
... | def main(argv):
| if len(argv)==2 and argv[0] == '-f':
weightsFile = argv[1]
generation = loadWeights(weightsFile)
else:
weightsFile ='bestWeightsSig.json'
generation = createInitialPopulation(100)
(game,screen,assets) = gameInit()
allGenomes = []
for g in generatio... | Time,distance,totalDistance, car.speed)
lastFitness = fitness
lastCar = car.copy()
print(" Sensors: ",sensorVals,"L/R/Speed:",car.outputs, "Fitness:",fitness,end='\r')
print('\r\n')
return fitness
def main(argv):
| 64 | 64 | 199 | 4 | 59 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | main | main | 379 | 416 | 379 | 380 | 3dd152959ed3424529519562e3e7451ebce9512a | bigcode/the-stack | train |
c3cae95f68e158a481b8406a | train | function | def drawCourse(game,assets,screen, sensorPoints):
cellWidth = 20
cellHeight = 20
for rowIndex in range(len(game.mapData)):
for cellIndex in range(len(game.mapData[rowIndex])):
xPos = cellIndex * cellWidth
yPos = rowIndex * cellHeight
assetIndex = game... | def drawCourse(game,assets,screen, sensorPoints):
| cellWidth = 20
cellHeight = 20
for rowIndex in range(len(game.mapData)):
for cellIndex in range(len(game.mapData[rowIndex])):
xPos = cellIndex * cellWidth
yPos = rowIndex * cellHeight
assetIndex = game.mapData[rowIndex][cellIndex]
screen.blit(as... | Val = sensorDistance - sensorVal
break
sensorPoints.append(sensorPoint)
sensorVals.append(2*sensorVal/car.sensorDistance)
sensorVals.append(car.speed/car.speedMax)
return (sensorVals,sensorPoints)
def drawCourse(game,assets,screen, sensorPoints):
| 63 | 64 | 175 | 13 | 50 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | drawCourse | drawCourse | 252 | 271 | 252 | 253 | dc1338af49bf5ab36026e7a15752f9d5f24efe0b | bigcode/the-stack | train |
09714d60d2b17d68f10c4a45 | train | function | def getCarSensors(carRect, car, game):
pos = carRect.center
sensorVals = []
sensorPoints = []
for angle in car.sensors:
angle += car.angle
sensorVal = int(car.sensorDistance/2)
for sensorDistance in range(car.sensorDistance):
sensorPoint = (pos... | def getCarSensors(carRect, car, game):
| pos = carRect.center
sensorVals = []
sensorPoints = []
for angle in car.sensors:
angle += car.angle
sensorVal = int(car.sensorDistance/2)
for sensorDistance in range(car.sensorDistance):
sensorPoint = (pos[0] + math.cos(angle/57.3)* sensorDistan... | 4:
return 0
if euclidDistance(carRect.center,game.currentWaypoint()) < 40:
print("waypoint %d hit\n" % game.wayPointIndex)
return 2
return 1
def getCarSensors(carRect, car, game):
| 64 | 64 | 213 | 11 | 52 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | getCarSensors | getCarSensors | 227 | 250 | 227 | 227 | d7ee8475f9c24d94dad70ceb5e3b529e93d09776 | bigcode/the-stack | train |
f9ffdcfb08856edf2c4dddcc | train | function | def checkCarIntersect(carRect, game):
sXPos = int((carRect.left) / 20)
sYPos = int((carRect.top) / 20)
eXPos = int((carRect.right) / 20)
eYPos = int((carRect.bottom) / 20)
if sXPos < 0 or sYPos < 0 or eXPos >= len(game.mapData[0]) or eYPos >= len(game.mapData):
return -1
if g... | def checkCarIntersect(carRect, game):
| sXPos = int((carRect.left) / 20)
sYPos = int((carRect.top) / 20)
eXPos = int((carRect.right) / 20)
eYPos = int((carRect.bottom) / 20)
if sXPos < 0 or sYPos < 0 or eXPos >= len(game.mapData[0]) or eYPos >= len(game.mapData):
return -1
if game.mapData[sYPos][sXPos] + game.mapDat... | )
for line in jsonData["map_data"]:
game.mapData.append([int(c) for c in line.strip()])
game.wayPoints = jsonData["waypoints"]
game.startPoint = jsonData["start"]
return game
def checkCarIntersect(carRect, game):
| 64 | 64 | 215 | 9 | 54 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | checkCarIntersect | checkCarIntersect | 209 | 225 | 209 | 209 | 182b98be36713cda292d5426779034b71ad70021 | bigcode/the-stack | train |
80976755b2c284684b17ff42 | train | function | def storeWeights(elites, populationFile):
formatted = []
for gen in elites:
formatted.append([i.tolist() for i in gen.weights])
with open(populationFile,'w') as file:
json.dump(formatted,file)
| def storeWeights(elites, populationFile):
| formatted = []
for gen in elites:
formatted.append([i.tolist() for i in gen.weights])
with open(populationFile,'w') as file:
json.dump(formatted,file)
| Weights(populationFile):
generation = []
fileContent = open(populationFile).read()
jsonData = json.loads(fileContent)
for genome in jsonData:
weights = numpy.array(genome)
generation.append(Driver(weights))
return generation
def storeWeights(elites, populationFile):
| 64 | 64 | 51 | 9 | 54 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | storeWeights | storeWeights | 123 | 128 | 123 | 123 | 40e2e9273167d44b1e64ae03de0ad57a9eae6c92 | bigcode/the-stack | train |
23c2bc1253ed8cbd1378e5e1 | train | function | def loadWeights(populationFile):
generation = []
fileContent = open(populationFile).read()
jsonData = json.loads(fileContent)
for genome in jsonData:
weights = numpy.array(genome)
generation.append(Driver(weights))
return generation
| def loadWeights(populationFile):
| generation = []
fileContent = open(populationFile).read()
jsonData = json.loads(fileContent)
for genome in jsonData:
weights = numpy.array(genome)
generation.append(Driver(weights))
return generation
| dimension outputs
dotProducts = numpy.dot(inputs,self.weights)
# apply sigmoid to each output value and round
return dotProducts
def createInitialPopulation(populationSize):
generation = [ Driver.randInit() for i in range(populationSize)]
return generation
def loadWeights(popula... | 64 | 64 | 57 | 7 | 56 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | loadWeights | loadWeights | 113 | 121 | 113 | 113 | e5c354bde4c8a918450781ca44cb8c5282a2e5d4 | bigcode/the-stack | train |
6a45b94a4409f5311e34192f | train | function | def evolve(generation, numElites):
nextGeneration = []
sortedGen = sorted(generation,key=lambda scored: scored.fitness, reverse=True)
elites = sortedGen[:numElites]
for gen in elites:
print(gen.fitness,gen.weights)
combinations = itertools.combinations(sortedGen[:numElites],2)
... | def evolve(generation, numElites):
| nextGeneration = []
sortedGen = sorted(generation,key=lambda scored: scored.fitness, reverse=True)
elites = sortedGen[:numElites]
for gen in elites:
print(gen.fitness,gen.weights)
combinations = itertools.combinations(sortedGen[:numElites],2)
for pair in combinations:
... | axis=1)
return Driver(numpy.array(weights))
def mutate(genome):
genome.weights += (numpy.random.rand(genome.weights.shape[0],genome.weights.shape[1]) - 0.5) * .125
return genome
def evolve(generation, numElites):
| 64 | 64 | 140 | 9 | 54 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | evolve | evolve | 156 | 176 | 156 | 156 | 013e616055cad243e4af472540a1e2f3eeaf7e1b | bigcode/the-stack | train |
4ddde01d643a393b202d6ff8 | train | function | def crossover(pair):
weights = []
'''
split = int(len(pair[0].weights[0]) / 2)
for row in range(len(pair[0].weights)):
weightRow = []
for col in range(split):
weightRow.append(pair[0].weights[row][col])
for col in range(split,len(pair[0].weights[0])):
... | def crossover(pair):
| weights = []
'''
split = int(len(pair[0].weights[0]) / 2)
for row in range(len(pair[0].weights)):
weightRow = []
for col in range(split):
weightRow.append(pair[0].weights[row][col])
for col in range(split,len(pair[0].weights[0])):
weightRow.append(... | Driver(weights))
return generation
def storeWeights(elites, populationFile):
formatted = []
for gen in elites:
formatted.append([i.tolist() for i in gen.weights])
with open(populationFile,'w') as file:
json.dump(formatted,file)
def crossover(pair):
| 62 | 64 | 188 | 4 | 58 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | crossover | crossover | 132 | 149 | 132 | 132 | 315d969ead4febfe6ea95bd4fc2998a2457c6000 | bigcode/the-stack | train |
43ea9e9d6b1912c61507802d | train | function | def createInitialPopulation(populationSize):
generation = [ Driver.randInit() for i in range(populationSize)]
return generation
| def createInitialPopulation(populationSize):
| generation = [ Driver.randInit() for i in range(populationSize)]
return generation
| outputs
def thinkReg(self,inputs):
inputs.insert(0,1)
# dot product, returns an array of dimension outputs
dotProducts = numpy.dot(inputs,self.weights)
# apply sigmoid to each output value and round
return dotProducts
def createInitialPopulation(populationSize):
| 64 | 64 | 28 | 8 | 55 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | createInitialPopulation | createInitialPopulation | 109 | 111 | 109 | 109 | e1996c401284a5cdd65f173fd2f66573236334e6 | bigcode/the-stack | train |
c3bd6cf62743b730e18043a5 | train | function | def mutate(genome):
genome.weights += (numpy.random.rand(genome.weights.shape[0],genome.weights.shape[1]) - 0.5) * .125
return genome
| def mutate(genome):
| genome.weights += (numpy.random.rand(genome.weights.shape[0],genome.weights.shape[1]) - 0.5) * .125
return genome
| [1].weights[split:]),axis=0)
# weights = numpy.concatenate((numpy.hsplit(pair[0].weights,2)[0],numpy.hsplit(pair[1].weights,2)[1]), axis=1)
return Driver(numpy.array(weights))
def mutate(genome):
| 63 | 64 | 41 | 5 | 58 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | mutate | mutate | 152 | 154 | 152 | 152 | 95a41d669353b917da6d1c5ccdf464576a4d00b1 | bigcode/the-stack | train |
f28d7187abbbd064a5a158c7 | train | class | class Driver:
id = 0
fitness = 0
# this is the weight vector for the "neural net" it has a weight for each input neuron to each output
weights = []
def __init__(self,weights):
self.weights = weights
'''
This function generates a NN with random weight values between -1 and +... | class Driver:
| id = 0
fitness = 0
# this is the weight vector for the "neural net" it has a weight for each input neuron to each output
weights = []
def __init__(self,weights):
self.weights = weights
'''
This function generates a NN with random weight values between -1 and +1 for the input... | (self.outputs[1],1),-1) * self.acceleration
if self.speed < 0:
self.speed = 0
if self.speed > self.speedMax:
self.speed = self.speedMax
moveX = math.cos(self.angle/57.3) * self.speed
moveY = math.sin(self.angle/57.3) * self.speed
... | 101 | 101 | 338 | 3 | 97 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | Driver | Driver | 68 | 107 | 68 | 68 | 1646e052655367e33cb49a0556d42aa3e7d36ceb | bigcode/the-stack | train |
07b03e231581bcdd2a77ae4b | train | class | class Car:
xPos = 0
yPos = 0
angle = 0
speed = 0
acceleration = 15
width = 20
height = 20
sensorDistance = 80
speedMax = 30
sensors = [-45,0,45]
inputs = [0,0,0,0]
outputs = [0,0,0,0]
angleRate = 15
def __init__(self,xPos,yPos,angle,speed):
... | class Car:
| xPos = 0
yPos = 0
angle = 0
speed = 0
acceleration = 15
width = 20
height = 20
sensorDistance = 80
speedMax = 30
sensors = [-45,0,45]
inputs = [0,0,0,0]
outputs = [0,0,0,0]
angleRate = 15
def __init__(self,xPos,yPos,angle,speed):
self.xPos ... | import sys
import pygame
from pygame.locals import *
import time
import math
import random
import json
import numpy
import itertools
class Game:
wayPoints = []
wayPointIndex = 0
mapData = []
startPoint = []
def currentWaypoint(self):
return self.wayPoints[self.wayPointIndex]... | 76 | 115 | 384 | 3 | 73 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | Car | Car | 19 | 65 | 19 | 19 | d92deb3ab1249019c6e535a58b6c8ccc588dde79 | bigcode/the-stack | train |
b079102f345a2d33b57e4889 | train | function | def gameMain(driver, game, screen, assets):
player = assets[3]
car = Car(game.startPoint[0], game.startPoint[1], 0,0)
lastCar = car.copy()
game.wayPointIndex = 0
stoppedTime = 0
elapsedTime = 0
distance = 0
totalDistance = 0
lastDistance = 0
fitness = 0
l... | def gameMain(driver, game, screen, assets):
| player = assets[3]
car = Car(game.startPoint[0], game.startPoint[1], 0,0)
lastCar = car.copy()
game.wayPointIndex = 0
stoppedTime = 0
elapsedTime = 0
distance = 0
totalDistance = 0
lastDistance = 0
fitness = 0
lastFitness = -1
running = 1
while runni... | 0.5
def gameInit():
pygame.init()
grass = pygame.image.load("../resources/images/grass.png")
road = pygame.image.load("../resources/images/road.png")
player = pygame.image.load("../resources/images/circle.png")
wayPoint = pygame.image.load("../resources/images/waypoint.png")
course =... | 162 | 163 | 544 | 12 | 150 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | gameMain | gameMain | 296 | 377 | 296 | 297 | 77d5439253bfa02ab5b8553852b34536e04efd3b | bigcode/the-stack | train |
4f5cce40a92ddaf69741e578 | train | function | def loadCourse(fileName):
start = []
data = []
with open(fileName) as file:
for line in file:
if len(start)==0:
start = [int(c) for c in line.strip().split(',')]
else:
data.append([int(c) for c in line.strip()])
return (start,data)... | def loadCourse(fileName):
| start = []
data = []
with open(fileName) as file:
for line in file:
if len(start)==0:
start = [int(c) for c in line.strip().split(',')]
else:
data.append([int(c) for c in line.strip()])
return (start,data)
| (genome)
return (nextGeneration, elites)
def assessFitness(numWaypoints, time, distanceFromStart, totalDistance,speed):
#return totalDistance
return ((numWaypoints-1)**2) * 400 + totalDistance + distanceFromStart
def loadCourse(fileName):
| 64 | 64 | 76 | 6 | 57 | michstmatt/EvolutionaryDriver | driving/Sig/drive.py | Python | loadCourse | loadCourse | 185 | 194 | 185 | 185 | 2d6aa116e960f4608db898733901fab4547a4b03 | bigcode/the-stack | train |
1902664a01e31cf9d706db70 | train | function | def DarknetBlock(x, filters, blocks):
x = DarknetConv(x, filters, 3, strides=2)
for _ in range(blocks):
x = DarknetResidual(x, filters)
return x
| def DarknetBlock(x, filters, blocks):
| x = DarknetConv(x, filters, 3, strides=2)
for _ in range(blocks):
x = DarknetResidual(x, filters)
return x
| netResidual(x, filters):
prev = x
x = DarknetConv(x, filters // 2, 1)
x = DarknetConv(x, filters, 3)
x = Add()([prev, x])
return x
def DarknetBlock(x, filters, blocks):
| 64 | 64 | 49 | 10 | 53 | yichenj/facegate | models/yolov3/yolov3/models.py | Python | DarknetBlock | DarknetBlock | 64 | 68 | 64 | 64 | ddce83a2ccade0a46e285f7c51b6b80788f0dd25 | bigcode/the-stack | train |
f71192e4d251b7317282a4c3 | train | function | def YoloV3(size=None, channels=3, anchors=yolo_anchors,
masks=yolo_anchor_masks, classes=80, training=False):
x = inputs = Input([size, size, channels], name='input')
x_36, x_61, x = Darknet(name='yolo_darknet')(x)
x = YoloConv(512, name='yolo_conv_0')(x)
output_0 = YoloOutput(512, len(mask... | def YoloV3(size=None, channels=3, anchors=yolo_anchors,
masks=yolo_anchor_masks, classes=80, training=False):
| x = inputs = Input([size, size, channels], name='input')
x_36, x_61, x = Darknet(name='yolo_darknet')(x)
x = YoloConv(512, name='yolo_conv_0')(x)
output_0 = YoloOutput(512, len(masks[0]), classes, name='yolo_output_0')(x)
x = YoloConv(256, name='yolo_conv_1')((x, x_61))
output_1 = YoloOutput(... | 1, 4)),
scores=tf.reshape(
scores, (tf.shape(scores)[0], -1, tf.shape(scores)[-1])),
max_output_size_per_class=FLAGS.yolo_max_boxes,
max_total_size=FLAGS.yolo_max_boxes,
iou_threshold=FLAGS.yolo_iou_threshold,
score_threshold=FLAGS.yolo_score_threshold
)
ret... | 125 | 125 | 419 | 32 | 92 | yichenj/facegate | models/yolov3/yolov3/models.py | Python | YoloV3 | YoloV3 | 204 | 232 | 204 | 205 | 507dfc820b8ed56e5389b387d5f86d3947adfa54 | bigcode/the-stack | train |
ec773017237f1cde97a42824 | train | function | def YoloOutput(filters, anchors, classes, name=None):
def yolo_output(x_in):
x = inputs = Input(x_in.shape[1:])
x = DarknetConv(x, filters * 2, 3)
x = DarknetConv(x, anchors * (classes + 5), 1, batch_norm=False)
x = Lambda(lambda x: tf.reshape(x, (-1, tf.shape(x)[1], tf.shape(x)[2],
... | def YoloOutput(filters, anchors, classes, name=None):
| def yolo_output(x_in):
x = inputs = Input(x_in.shape[1:])
x = DarknetConv(x, filters * 2, 3)
x = DarknetConv(x, anchors * (classes + 5), 1, batch_norm=False)
x = Lambda(lambda x: tf.reshape(x, (-1, tf.shape(x)[1], tf.shape(x)[2],
anchors, c... | , x_skip])
else:
x = inputs = Input(x_in.shape[1:])
x = DarknetConv(x, filters, 1)
return Model(inputs, x, name=name)(x_in)
return yolo_conv
def YoloOutput(filters, anchors, classes, name=None):
| 64 | 64 | 130 | 13 | 50 | yichenj/facegate | models/yolov3/yolov3/models.py | Python | YoloOutput | YoloOutput | 140 | 148 | 140 | 140 | 8dfebe021d5394514118629acf14ec987c00c85a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.