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
1bc8a10193abbc359d71d90e
train
function
def view_lines( lines, title = None ): raise NotImplementedError( 'Songrun, you can implement this.' )
def view_lines( lines, title = None ):
raise NotImplementedError( 'Songrun, you can implement this.' )
2pos[0] + w1.getWindowShape()[0], w2pos[1] ) w1.positionWindow( [500, 0] if 'sim' in mesh_path else [0, 0] ) glutMainLoop() def view_lines( lines, title = None ):
64
64
26
10
54
Zhengjun-Du/GeometricPaletteBasedVideoRecoloring
ExtractVideoFrameConvexHull/dynamic_viewer.py
Python
view_lines
view_lines
518
519
518
518
67113b67d4dd2d98a88c6d48b2835e262cf6666d
bigcode/the-stack
train
c3813072f653b068291cd7f0
train
function
def draw_points( mesh, points, video_points): ''' Takes a sequence of points and draws it, setting as little OpenGL state as possible. ''' glShadeModel( GL_SMOOTH ) glBegin( GL_POINTS ) # print(dir(mesh)) for x, y, z in mesh.vs: # v = tuple( v ) glColor(x + .5, y +...
def draw_points( mesh, points, video_points):
''' Takes a sequence of points and draws it, setting as little OpenGL state as possible. ''' glShadeModel( GL_SMOOTH ) glBegin( GL_POINTS ) # print(dir(mesh)) for x, y, z in mesh.vs: # v = tuple( v ) glColor(x + .5, y + .5, z + .5) glVertex3f(x, y, z) ...
) glVertex3f(.5, q, s) glEnd() def draw_linestrips( linestrips ): ''' Takes a sequence of line strips, where each line strip is a sequence of points, and draws it, setting as little OpenGL state as possible. ''' for linestrip in linestrips: glBegin( GL_LINE_STRIP ) ...
104
104
349
11
93
Zhengjun-Du/GeometricPaletteBasedVideoRecoloring
ExtractVideoFrameConvexHull/dynamic_viewer.py
Python
draw_points
draw_points
252
293
252
252
2bf81732ccf77e48d9243e30a165bbec79d4c586
bigcode/the-stack
train
265170410f0d33fdd875651c
train
class
class TestRescaleIntensity(TorchioTestCase): """Tests for :class:`tio.RescaleIntensity` class.""" def test_rescale_to_same_intentisy(self): min_t1 = float(self.sample_subject.t1.data.min()) max_t1 = float(self.sample_subject.t1.data.max()) transform = tio.RescaleIntensity(out_min_max=(m...
class TestRescaleIntensity(TorchioTestCase):
"""Tests for :class:`tio.RescaleIntensity` class.""" def test_rescale_to_same_intentisy(self): min_t1 = float(self.sample_subject.t1.data.min()) max_t1 = float(self.sample_subject.t1.data.max()) transform = tio.RescaleIntensity(out_min_max=(min_t1, max_t1)) transformed = transfo...
import copy import torch import torchio as tio import numpy as np from ...utils import TorchioTestCase class TestRescaleIntensity(TorchioTestCase):
37
256
991
11
25
snavalm/torchio
tests/transforms/preprocessing/test_rescale.py
Python
TestRescaleIntensity
TestRescaleIntensity
8
102
8
8
9c21f83b05d6df03689ce3dcb81183833cb5e436
bigcode/the-stack
train
b1173495e443f3f80a80fc2c
train
class
class QuizAnswerHandler(AbstractRequestHandler): """Handler for Answers to the Quiz.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool attr = handler_input.attributes_manager.session_attributes state = attr["state"] return (is_intent_name("AnswerIntent")(han...
class QuizAnswerHandler(AbstractRequestHandler):
"""Handler for Answers to the Quiz.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool attr = handler_input.attributes_manager.session_attributes state = attr["state"] return (is_intent_name("AnswerIntent")(handler_input) and state == "QUIZ") def handle(...
) questionSet = attr["questionSet"] speak_output = getQuestion(questionSet, questionNumber) reprompt = questionHelp(questionSet, questionNumber) return (handler_input.response_builder.speak(speak_output).ask(reprompt).response) else: speak_output = h...
92
92
308
8
84
InfernapeXavier/song-match
lambda_function.py
Python
QuizAnswerHandler
QuizAnswerHandler
118
155
118
118
5dbc37302261506878f751a2c5f69d7f0c4a37a0
bigcode/the-stack
train
c5e38b5968de551868f8d30e
train
class
class FallbackIntentHandler(AbstractRequestHandler): """The fallback intent handles all "Unknown" requests.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("AMAZON.FallbackIntent")(handler_input) def handle(self, handler_input): ...
class FallbackIntentHandler(AbstractRequestHandler):
"""The fallback intent handles all "Unknown" requests.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("AMAZON.FallbackIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response speak_o...
Input) -> bool return ask_utils.is_request_type("SessionEndedRequest")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response # Any cleanup logic goes here. return handler_input.response_builder.response class FallbackIntentHandler(AbstractRequestHandle...
64
64
113
9
54
InfernapeXavier/song-match
lambda_function.py
Python
FallbackIntentHandler
FallbackIntentHandler
221
233
221
221
51544796637a71570a8c538c1e9ee97455273ca3
bigcode/the-stack
train
c41e6dbd17746d9d30daba38
train
class
class LaunchRequestHandler(AbstractRequestHandler): """ Handler for Skill Launch """ def can_handle(self, handler_input): return is_request_type("LaunchRequest")(handler_input) def handle(self, handler_input): speech = welcomeMessage reprompt = welcomeReprompt attr ...
class LaunchRequestHandler(AbstractRequestHandler):
""" Handler for Skill Launch """ def can_handle(self, handler_input): return is_request_type("LaunchRequest")(handler_input) def handle(self, handler_input): speech = welcomeMessage reprompt = welcomeReprompt attr = handler_input.attributes_manager.session_attribute...
import json import locale import requests import calendar from ask_sdk_s3.adapter import S3Adapter s3_adapter = S3Adapter(bucket_name=os.environ["S3_PERSISTENCE_BUCKET"]) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class LaunchRequestHandler(AbstractRequestHandler):
64
64
104
8
56
InfernapeXavier/song-match
lambda_function.py
Python
LaunchRequestHandler
LaunchRequestHandler
31
46
31
31
47ff53126e1073a82a1155bbd2053490f3901d37
bigcode/the-stack
train
73b726315ada687dc7f7b3c9
train
class
class HelpIntentHandler(AbstractRequestHandler): """Handler for Help Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Respons...
class HelpIntentHandler(AbstractRequestHandler):
"""Handler for Help Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response attr = handler_input.attributes_manager...
, score) song = attr['song'] speak_output = finalResponse(artistName, song) attr["state"] = "INITIALIZING" handler_input.response_builder.speak( speak_output).ask(exitMessage) return (handler_input.response_builder.response) class HelpIntentHan...
66
66
220
8
58
InfernapeXavier/song-match
lambda_function.py
Python
HelpIntentHandler
HelpIntentHandler
158
187
158
158
2d6da43eb9dd2e6636033f812a251338740e5bda
bigcode/the-stack
train
1b4d03107d490d9b99228ab3
train
class
class StartQuizIntentHandler(AbstractRequestHandler): """Handler for Starting the Quiz.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool attr = handler_input.attributes_manager.session_attributes state = attr["state"] return ( ( ...
class StartQuizIntentHandler(AbstractRequestHandler):
"""Handler for Starting the Quiz.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool attr = handler_input.attributes_manager.session_attributes state = attr["state"] return ( ( is_intent_name("StartQuizIntent")(handler_input) or ...
.slots attr = handler_input.attributes_manager.session_attributes artist = slots["artistName"].value attr["artist"] = artist speak_output = capturedArtist(artist) + " " + startQuiz(artist) reprompt = helpWithQuizMessage(artist) return (handler_input.response_builder.sp...
90
90
303
9
81
InfernapeXavier/song-match
lambda_function.py
Python
StartQuizIntentHandler
StartQuizIntentHandler
74
115
74
74
430847c82c4e8af5719a99a3c016e303a7f12bd2
bigcode/the-stack
train
e6a4b0bf5ce6de32e656b89b
train
class
class CatchAllExceptionHandler(AbstractExceptionHandler): """Generic error handling to capture any syntax or routing errors. If you receive an error stating the request handler chain is not found, you have not implemented a handler for the intent being invoked or included it in the skill builder below. ...
class CatchAllExceptionHandler(AbstractExceptionHandler):
"""Generic error handling to capture any syntax or routing errors. If you receive an error stating the request handler chain is not found, you have not implemented a handler for the intent being invoked or included it in the skill builder below. """ def can_handle(self, handler_input, exception): ...
_utils.is_intent_name("AMAZON.FallbackIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response speak_output = fallbackErrorMessage reprompt = errorMessage return (handler_input.response_builder.speak(speak_output).ask(reprompt).response) class Cat...
78
78
261
9
69
InfernapeXavier/song-match
lambda_function.py
Python
CatchAllExceptionHandler
CatchAllExceptionHandler
236
268
236
236
2d1548a0b21b6d232d90c012aa9bcd7fb6db286b
bigcode/the-stack
train
c77ef5ff5be6c48ed525ca9c
train
class
class CaptureArtistIntentHandler(AbstractRequestHandler): """Handler for Capturing the Favorite Artist.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool attr = handler_input.attributes_manager.session_attributes state = attr["state"] return (is_intent_name(...
class CaptureArtistIntentHandler(AbstractRequestHandler):
"""Handler for Capturing the Favorite Artist.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool attr = handler_input.attributes_manager.session_attributes state = attr["state"] return (is_intent_name("CaptureArtistIntent")(handler_input) and (state != "QUIZ"...
= welcomeMessage reprompt = welcomeReprompt attr = handler_input.attributes_manager.session_attributes attr["state"] = "INITIALIZING" handler_input.response_builder.speak(speech).ask(reprompt) return handler_input.response_builder.response class CaptureArtistIntentHandler(Abstr...
64
64
189
9
54
InfernapeXavier/song-match
lambda_function.py
Python
CaptureArtistIntentHandler
CaptureArtistIntentHandler
49
71
49
49
e38fabba347497c051334a3ee80bf11e1216e1c4
bigcode/the-stack
train
4adc9e81f6208a9d648c5289
train
class
class CancelOrStopIntentHandler(AbstractRequestHandler): """Single handler for Cancel and Stop Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or ask_utils.is_in...
class CancelOrStopIntentHandler(AbstractRequestHandler):
"""Single handler for Cancel and Stop Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input)) def h...
= attr["questionNumber"] artist = attr["artist"] questionSet = attr["questionSet"] speak_output = questionHelp(questionSet, question) return (handler_input.response_builder.speak(speak_output).ask( errorMessage).response) class CancelOrStopIntentHandler(Abstract...
64
64
120
10
54
InfernapeXavier/song-match
lambda_function.py
Python
CancelOrStopIntentHandler
CancelOrStopIntentHandler
190
203
190
190
e1efaf291ff41d5ae9503a445fda20a5bb738302
bigcode/the-stack
train
3575ed28f58efdaa904fb98f
train
class
class SessionEndedRequestHandler(AbstractRequestHandler): """Handler for Session End.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_request_type("SessionEndedRequest")(handler_input) def handle(self, handler_input): # type: (HandlerInput...
class SessionEndedRequestHandler(AbstractRequestHandler):
"""Handler for Session End.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_request_type("SessionEndedRequest")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response # Any cleanup logic goes here. ...
.is_intent_name("AMAZON.StopIntent")(handler_input)) def handle(self, handler_input): # type: (HandlerInput) -> Response speak_output = goodbyeMessage return (handler_input.response_builder.speak(speak_output).response) class SessionEndedRequestHandler(AbstractRequestHandler):
64
64
86
9
55
InfernapeXavier/song-match
lambda_function.py
Python
SessionEndedRequestHandler
SessionEndedRequestHandler
206
218
206
206
2b769bf3aa8af5feda7a3a1d4c851ff461df694d
bigcode/the-stack
train
f219c7f9501d9a98e1f57d57
train
class
class NMF(): # XXX: lr_shrink_rate is not used here... how to put it to the equation? def __init__( self, n_users, n_items, n_factors=15, n_epochs=50, lr=.005, lr_bias=None, lr_latent=None, lmbda=.02, lmbda_bias=None, lmbda_latent=None, lr_shrink_rate=.9): self....
class NMF(): # XXX: lr_shrink_rate is not used here... how to put it to the equation?
def __init__( self, n_users, n_items, n_factors=15, n_epochs=50, lr=.005, lr_bias=None, lr_latent=None, lmbda=.02, lmbda_bias=None, lmbda_latent=None, lr_shrink_rate=.9): self.n_users = n_users self.n_items = n_items self.n_epochs = n_epochs ...
# Hung-Hsuan Chen <hhchen1105@gmail.com> # Creation Date : 09-02-2017 # Last Modified: Sat 28 Apr 2018 06:41:15 AM CST import collections import numpy as np class NMF(): # XXX: lr_shrink_rate is not used here... how to put it to the equation?
79
256
1,952
25
53
GroupMovieNight/group-movie-recommendation
testing/nmf.py
Python
NMF
NMF
9
168
9
10
40ad7fb8fb0a53b9f3ef84f5ca4c65283b6b154b
bigcode/the-stack
train
4da975619f6d580c8cf23951
train
class
class MetaflowTask(object): """ MetaflowTask prepares a Flow instance for execution of a single step. """ def __init__(self, flow, datastore, metadata, environment, console_logger, event_logger, ...
class MetaflowTask(object):
""" MetaflowTask prepares a Flow instance for execution of a single step. """ def __init__(self, flow, datastore, metadata, environment, console_logger, event_logger, monitor): ...
from __future__ import print_function import sys import os import time from .metaflow_config import MAX_ATTEMPTS from .metadata import MetaDatum from .datastore import Inputs, MetaflowDatastoreSet from .exception import MetaflowInternalError,\ MetaflowDataMissing,\ MetaflowExceptionWrapper from .util import al...
134
256
3,538
7
127
patrickjohncyh/metaflow
metaflow/task.py
Python
MetaflowTask
MetaflowTask
23
482
23
23
d4cda1094b77aa13e937eab5dee364eeff9f7d54
bigcode/the-stack
train
c4f89995a886519a5d8d6279
train
class
class MetastoreUpdateKafkaTopicBatchRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Emr', '2016-04-08', 'MetastoreUpdateKafkaTopicBatch') def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_que...
class MetastoreUpdateKafkaTopicBatchRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Emr', '2016-04-08', 'MetastoreUpdateKafkaTopicBatch') def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_query_param('ResourceOwnerId',ResourceOwnerId) def get_To...
on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class MetastoreUpdateKafkaTopicBatchRequest(RpcRequest):
67
67
226
12
54
sdk-team/aliyun-openapi-python-sdk
aliyun-python-sdk-emr/aliyunsdkemr/request/v20160408/MetastoreUpdateKafkaTopicBatchRequest.py
Python
MetastoreUpdateKafkaTopicBatchRequest
MetastoreUpdateKafkaTopicBatchRequest
21
40
21
22
d5451666823d493404aaf3672faf513bb7f1af2c
bigcode/the-stack
train
4213a498b4c03f1f98c980c4
train
class
class HumanOracle(IOracle): def __init__(self, labels): self.accepts = [label["concept"] for label in labels if label["value"] == "accept"] self.rejects = [label["concept"] for label in labels if label["value"] == "reject"] def get_labels(self, samples): a = [sample for sample in sample...
class HumanOracle(IOracle):
def __init__(self, labels): self.accepts = [label["concept"] for label in labels if label["value"] == "accept"] self.rejects = [label["concept"] for label in labels if label["value"] == "reject"] def get_labels(self, samples): a = [sample for sample in samples if sample in self.accepts]...
from algorithms.oracle.IOracle import IOracle class HumanOracle(IOracle):
15
64
113
6
8
avineshpvs/vldb2018-sherlock
ukpsummarizer-be/summarizer/algorithms/oracle/human_oracle.py
Python
HumanOracle
HumanOracle
4
13
4
4
83d99773172c1cd8a72c031c980f3af393c821f4
bigcode/the-stack
train
300a4beca1ab62f65132fb4f
train
class
class TestPromise(unittest.TestCase): @async_test async def test_resolved(self): result = None def f(resolve, reject): resolve(42) def g(x): nonlocal result result = x p = Promise(f) p.then(g) await asyncio.sleep(0) ...
class TestPromise(unittest.TestCase): @async_test
async def test_resolved(self): result = None def f(resolve, reject): resolve(42) def g(x): nonlocal result result = x p = Promise(f) p.then(g) await asyncio.sleep(0) while result is None: await asyncio.sleep(...
import asyncio import unittest import pytest import promisio from promisio import Promise, promisify from .utils import async_test, get_fake_error class TestPromise(unittest.TestCase): @async_test
45
256
1,869
12
32
miguelgrinberg/promisio
tests/test_promise.py
Python
TestPromise
TestPromise
9
331
9
10
dd38efa8e2add27b4efc8b82145cf509b7640428
bigcode/the-stack
train
a6fa3df0f0274eef3ee67a88
train
class
class FileProxyMixin: """ A mixin class used to forward file methods to an underlaying file object. The internal file object has to be called "file":: class FileProxy(FileProxyMixin): def __init__(self, file): self.file = file """ encoding = property(lambda sel...
class FileProxyMixin:
""" A mixin class used to forward file methods to an underlaying file object. The internal file object has to be called "file":: class FileProxy(FileProxyMixin): def __init__(self, file): self.file = file """ encoding = property(lambda self: self.file.encoding)...
class FileProxyMixin:
5
114
383
5
0
Lucas11200/LocaPy
Lib/site-packages/django/core/files/utils.py
Python
FileProxyMixin
FileProxyMixin
1
52
1
1
efa5a45aa9ad5c3da3670905d30a1302b8a40779
bigcode/the-stack
train
3192a2dad70834a0ccd97c42
train
class
class TokenEmulate(AuthAPIView): """ This API allows already-authenticated users to request a new token that will emulate a user that is not their own. Due to the obvious security concerns, only 'staff' accounts or tokens owned by an administrator will be allowed. """ def get(self, request...
class TokenEmulate(AuthAPIView):
""" This API allows already-authenticated users to request a new token that will emulate a user that is not their own. Due to the obvious security concerns, only 'staff' accounts or tokens owned by an administrator will be allowed. """ def get(self, request, username): """ C...
""" Atmosphere service user rest api. """ from rest_framework.response import Response from rest_framework import status from threepio import logger from atmosphere.settings import secrets from django_cyverse_auth.models import get_or_create_token from core.models import AtmosphereUser from api.v1.serializers impo...
82
117
391
7
74
xuhang57/atmosphere
api/v1/views/token.py
Python
TokenEmulate
TokenEmulate
19
59
19
20
08a83b2d94386557d40b187224f4429a33f6fa76
bigcode/the-stack
train
eae42d9c8706d8f57edc8407
train
function
def generate_admin(): admin = User( username="admin", password="admin", email="admin@admin", is_admin=True ) db.session.add(admin) db.session.commit() return admin
def generate_admin():
admin = User( username="admin", password="admin", email="admin@admin", is_admin=True ) db.session.add(admin) db.session.commit() return admin
05 @LastEditTime: 2019-08-29 18:01:56 ''' import uuid from app.models import InvitationCode, db, User # from flask import current_app from app import create_app app = create_app() app.app_context().push() def generate_admin():
64
64
46
4
60
Ciyfly/web_info_monitor
server/app/utils/invitationcode_util.py
Python
generate_admin
generate_admin
16
23
16
16
8f4c2955f88aa4b6e9acd9ae0b2147ca13dcffa9
bigcode/the-stack
train
bd813ea7753eb6760c410acd
train
function
def generate_invitationcode(): invitationcode = str(uuid.uuid1()).replace("-", "") current_app.logger.info(f"生成邀请码: {invitationcode}") invitationcode = InvitationCode( invitation_code=invitationcode ) db.session.add(invitationcode) db.session.commit() ...
def generate_invitationcode():
invitationcode = str(uuid.uuid1()).replace("-", "") current_app.logger.info(f"生成邀请码: {invitationcode}") invitationcode = InvitationCode( invitation_code=invitationcode ) db.session.add(invitationcode) db.session.commit() return invitationcode
app = create_app() app.app_context().push() def generate_admin(): admin = User( username="admin", password="admin", email="admin@admin", is_admin=True ) db.session.add(admin) db.session.commit() return admin def generate_invitationcode():
64
64
68
6
57
Ciyfly/web_info_monitor
server/app/utils/invitationcode_util.py
Python
generate_invitationcode
generate_invitationcode
25
33
25
25
b7c9574afd31ac0340330ea67b29ac99a4731297
bigcode/the-stack
train
bedb8bd2d9600bc116b3ab95
train
class
class PrototypicalBatchSampler(object): ''' PrototypicalBatchSampler: yield a batch of indexes at each iteration. Indexes are calculated by keeping in account 'classes_per_it', 'num_support', 'num_query', In fact at every iteration the batch indexes will refer to 'num_support' + 'num_query' samples ...
class PrototypicalBatchSampler(object):
''' PrototypicalBatchSampler: yield a batch of indexes at each iteration. Indexes are calculated by keeping in account 'classes_per_it', 'num_support', 'num_query', In fact at every iteration the batch indexes will refer to 'num_support' + 'num_query' samples for 'classes_per_it' random classes. ...
# coding=utf-8 import numpy as np class PrototypicalBatchSampler(object):
20
160
536
9
10
Anyesh/Prototypical-Networks-for-Few-shot-Learning-PyTorch
src/prototypical_batch_sampler.py
Python
PrototypicalBatchSampler
PrototypicalBatchSampler
5
61
5
5
8f9666b1063d08b23a5d02a87a8efa98bed8e25b
bigcode/the-stack
train
a935e26604b47c3a7a4faf58
train
class
class Ranged(weapon.Weapon): def __init__(self, name, description, value, weight, damage, range, type, equip_message, unequip_message, *args): self.damage = damage self.type = type self.range = range super().__init__(name, description, value, weight, equip_message, unequip_message)
class Ranged(weapon.Weapon):
def __init__(self, name, description, value, weight, damage, range, type, equip_message, unequip_message, *args): self.damage = damage self.type = type self.range = range super().__init__(name, description, value, weight, equip_message, unequip_message)
__init__(self, name, description, value, weight, damage, type, equip_message, unequip_message): self.damage = damage self.type = type super().__init__(name, description, value, weight, equip_message, unequip_message) class Ranged(weapon.Weapon):
64
64
77
8
56
DVDTSB/py-text
py-venture/premade/classes/weapons_types.py
Python
Ranged
Ranged
8
13
8
8
6dd44ac6b7a80021d8f60f5a17aeed59ef600701
bigcode/the-stack
train
33d5b989a6bd02f54651fdff
train
class
class Meele(weapon.Weapon): def __init__(self, name, description, value, weight, damage, type, equip_message, unequip_message): self.damage = damage self.type = type super().__init__(name, description, value, weight, equip_message, unequip_message)
class Meele(weapon.Weapon):
def __init__(self, name, description, value, weight, damage, type, equip_message, unequip_message): self.damage = damage self.type = type super().__init__(name, description, value, weight, equip_message, unequip_message)
import modules.weapon as weapon class Meele(weapon.Weapon):
14
64
66
8
5
DVDTSB/py-text
py-venture/premade/classes/weapons_types.py
Python
Meele
Meele
2
6
2
2
9312e2d114fd6893bda6db2d262f1dd9d629e11b
bigcode/the-stack
train
561d1ece5a247c5241a1ecd4
train
class
@challenges_namespace.route("/<challenge_id>") class Challenge(Resource): @check_challenge_visibility @during_ctf_time_only @require_verified_emails @challenges_namespace.doc( description="Endpoint to get a specific Challenge object", responses={ 200: ("Success", "ChallengeDe...
@challenges_namespace.route("/<challenge_id>") class Challenge(Resource): @check_challenge_visibility @during_ctf_time_only @require_verified_emails @challenges_namespace.doc( description="Endpoint to get a specific Challenge object", responses={ 200: ("Success", "ChallengeDe...
def get(self, challenge_id): if is_admin(): chal = Challenges.query.filter(Challenges.id == challenge_id).first_or_404() else: chal = Challenges.query.filter( Challenges.id == challenge_id, and_(Challenges.state != "hidden", Challenges.state !=...
_type) challenge = challenge_class.create(request) response = challenge_class.read(challenge) return {"success": True, "data": response} @challenges_namespace.route("/types") class ChallengeTypes(Resource): @admins_only def get(self): response = {} for class_id in CHAL...
256
256
1,376
101
155
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
Challenge
Challenge
261
462
261
275
54b0694dd229d3080936fe39fbda8ebd71f900bf
bigcode/the-stack
train
2662ad8b8eddec73e5885ed9
train
class
@challenges_namespace.route("/attempt") class ChallengeAttempt(Resource): @check_challenge_visibility @during_ctf_time_only @require_verified_emails def post(self): if authed() is False: return {"success": True, "data": {"status": "authentication_required"}}, 403 if request....
@challenges_namespace.route("/attempt") class ChallengeAttempt(Resource): @check_challenge_visibility @during_ctf_time_only @require_verified_emails
def post(self): if authed() is False: return {"success": True, "data": {"status": "authentication_required"}}, 403 if request.content_type != "application/json": request_data = request.form else: request_data = request.get_json() challenge_id = r...
", ), }, ) def patch(self, challenge_id): data = request.get_json() # Load data through schema for validation but not for insertion schema = ChallengeSchema() response = schema.load(data) if response.errors: return {"success": False, "erro...
256
256
1,375
35
221
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeAttempt
ChallengeAttempt
465
667
465
469
491e3db3ab032d7f5fabc50e7b3dd6925078202d
bigcode/the-stack
train
edf33df5beed726b889451f3
train
class
class ChallengeListSuccessResponse(APIListSuccessResponse): data: List[ChallengeModel]
class ChallengeListSuccessResponse(APIListSuccessResponse):
data: List[ChallengeModel]
", description="Endpoint to retrieve Challenges" ) ChallengeModel = sqlalchemy_to_pydantic(Challenges) TransientChallengeModel = sqlalchemy_to_pydantic(Challenges, exclude=["id"]) class ChallengeDetailedSuccessResponse(APIDetailedSuccessResponse): data: ChallengeModel class ChallengeListSuccessResponse(APIListSu...
64
64
18
10
53
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeListSuccessResponse
ChallengeListSuccessResponse
65
66
65
65
656cdb0876df727d0ece2e3e8eab1271dd5c89a6
bigcode/the-stack
train
3c78aa7c8e8c21cc5f293f46
train
class
@challenges_namespace.route("/<challenge_id>/tags") class ChallengeTags(Resource): @admins_only def get(self, challenge_id): response = [] tags = Tags.query.filter_by(challenge_id=challenge_id).all() for t in tags: response.append( {"id": t.id, "challenge_id...
@challenges_namespace.route("/<challenge_id>/tags") class ChallengeTags(Resource): @admins_only
def get(self, challenge_id): response = [] tags = Tags.query.filter_by(challenge_id=challenge_id).all() for t in tags: response.append( {"id": t.id, "challenge_id": t.challenge_id, "value": t.value} ) return {"success": True, "data": response...
all() for f in challenge_files: response.append({"id": f.id, "type": f.type, "location": f.location}) return {"success": True, "data": response} @challenges_namespace.route("/<challenge_id>/tags") class ChallengeTags(Resource): @admins_only
64
64
95
22
42
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeTags
ChallengeTags
732
744
732
734
5b2dbb11c1807359135c7f4a631639584caf63f0
bigcode/the-stack
train
85960bccdee8d5fcadb7c8fa
train
class
@challenges_namespace.route("/<challenge_id>/flags") class ChallengeFlags(Resource): @admins_only def get(self, challenge_id): flags = Flags.query.filter_by(challenge_id=challenge_id).all() schema = FlagSchema(many=True) response = schema.dump(flags) if response.errors: ...
@challenges_namespace.route("/<challenge_id>/flags") class ChallengeFlags(Resource): @admins_only
def get(self, challenge_id): flags = Flags.query.filter_by(challenge_id=challenge_id).all() schema = FlagSchema(many=True) response = schema.dump(flags) if response.errors: return {"success": False, "errors": response.errors}, 400 return {"success": True, "data"...
response = schema.dump(hints) if response.errors: return {"success": False, "errors": response.errors}, 400 return {"success": True, "data": response.data} @challenges_namespace.route("/<challenge_id>/flags") class ChallengeFlags(Resource): @admins_only
64
64
96
22
42
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeFlags
ChallengeFlags
761
772
761
763
d93d77dcb46ccf7271a523ec58c4b6a769ec54c9
bigcode/the-stack
train
423e8f05f0a1f9e949707898
train
class
@challenges_namespace.route("/<challenge_id>/solves") class ChallengeSolves(Resource): @check_challenge_visibility @check_score_visibility @during_ctf_time_only @require_verified_emails def get(self, challenge_id): response = [] challenge = Challenges.query.filter_by(id=challenge_id)...
@challenges_namespace.route("/<challenge_id>/solves") class ChallengeSolves(Resource): @check_challenge_visibility @check_score_visibility @during_ctf_time_only @require_verified_emails
def get(self, challenge_id): response = [] challenge = Challenges.query.filter_by(id=challenge_id).first_or_404() # TODO: Need a generic challenge visibility call. # However, it should be stated that a solve on a gated challenge is not considered private. if challenge.state ...
=challenge_id, kpm=kpm, ) return { "success": True, "data": { "status": "already_solved", "message": "You already solved this", }, } @challenges_namespace.route("/<challenge_id>/so...
96
96
323
47
49
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeSolves
ChallengeSolves
670
714
670
675
939da51d99d98164ef4641c5b1b42676d71a5565
bigcode/the-stack
train
b7595a407f79c1aa5b2c54d0
train
class
@challenges_namespace.route("/<challenge_id>/files") class ChallengeFiles(Resource): @admins_only def get(self, challenge_id): response = [] challenge_files = ChallengeFilesModel.query.filter_by( challenge_id=challenge_id ).all() for f in challenge_files: ...
@challenges_namespace.route("/<challenge_id>/files") class ChallengeFiles(Resource): @admins_only
def get(self, challenge_id): response = [] challenge_files = ChallengeFilesModel.query.filter_by( challenge_id=challenge_id ).all() for f in challenge_files: response.append({"id": f.id, "type": f.type, "location": f.location}) return {"success": Tru...
, "date": isoformat(solve.date), "account_url": generate_account_url(account_id=solve.account_id), } ) return {"success": True, "data": response} @challenges_namespace.route("/<challenge_id>/files") class ChallengeFiles(Resource): @admins_...
64
64
96
22
42
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeFiles
ChallengeFiles
717
729
717
719
bacb70770a67ec1690b996ffaeff1853c6d63902
bigcode/the-stack
train
d6f6b96fed497ca16316fa8d
train
class
@challenges_namespace.route("/<challenge_id>/hints") class ChallengeHints(Resource): @admins_only def get(self, challenge_id): hints = Hints.query.filter_by(challenge_id=challenge_id).all() schema = HintSchema(many=True) response = schema.dump(hints) if response.errors: ...
@challenges_namespace.route("/<challenge_id>/hints") class ChallengeHints(Resource): @admins_only
def get(self, challenge_id): hints = Hints.query.filter_by(challenge_id=challenge_id).all() schema = HintSchema(many=True) response = schema.dump(hints) if response.errors: return {"success": False, "errors": response.errors}, 400 return {"success": True, "data"...
tags: response.append( {"id": t.id, "challenge_id": t.challenge_id, "value": t.value} ) return {"success": True, "data": response} @challenges_namespace.route("/<challenge_id>/hints") class ChallengeHints(Resource): @admins_only
64
64
99
23
41
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeHints
ChallengeHints
747
758
747
749
6f941647e13d955fb4783caff9d52332db95dd64
bigcode/the-stack
train
c573c6401a08b383dc584899
train
class
@challenges_namespace.route("/<challenge_id>/requirements") class ChallengeRequirements(Resource): @admins_only def get(self, challenge_id): challenge = Challenges.query.filter_by(id=challenge_id).first_or_404() return {"success": True, "data": challenge.requirements}
@challenges_namespace.route("/<challenge_id>/requirements") class ChallengeRequirements(Resource): @admins_only
def get(self, challenge_id): challenge = Challenges.query.filter_by(id=challenge_id).first_or_404() return {"success": True, "data": challenge.requirements}
) response = schema.dump(flags) if response.errors: return {"success": False, "errors": response.errors}, 400 return {"success": True, "data": response.data} @challenges_namespace.route("/<challenge_id>/requirements") class ChallengeRequirements(Resource): @admins_only
64
64
61
22
42
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeRequirements
ChallengeRequirements
775
780
775
777
d6e2bba7ffa7e41f028e8725b198560737e63e5d
bigcode/the-stack
train
1980a0095bd35ea08529a68e
train
class
class ChallengeDetailedSuccessResponse(APIDetailedSuccessResponse): data: ChallengeModel
class ChallengeDetailedSuccessResponse(APIDetailedSuccessResponse):
data: ChallengeModel
_current_user, is_admin challenges_namespace = Namespace( "challenges", description="Endpoint to retrieve Challenges" ) ChallengeModel = sqlalchemy_to_pydantic(Challenges) TransientChallengeModel = sqlalchemy_to_pydantic(Challenges, exclude=["id"]) class ChallengeDetailedSuccessResponse(APIDetailedSuccessResponse...
63
64
17
11
52
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeDetailedSuccessResponse
ChallengeDetailedSuccessResponse
61
62
61
61
d62a956a49cd8e84da1fc1984d29cb385d16c532
bigcode/the-stack
train
ee54bacba43881674406e420
train
class
@challenges_namespace.route("/types") class ChallengeTypes(Resource): @admins_only def get(self): response = {} for class_id in CHALLENGE_CLASSES: challenge_class = CHALLENGE_CLASSES.get(class_id) response[challenge_class.id] = { "id": challenge_class.id,...
@challenges_namespace.route("/types") class ChallengeTypes(Resource): @admins_only
def get(self): response = {} for class_id in CHALLENGE_CLASSES: challenge_class = CHALLENGE_CLASSES.get(class_id) response[challenge_class.id] = { "id": challenge_class.id, "name": challenge_class.name, "templates": challenge_c...
= data["type"] challenge_class = get_chal_class(challenge_type) challenge = challenge_class.create(request) response = challenge_class.read(challenge) return {"success": True, "data": response} @challenges_namespace.route("/types") class ChallengeTypes(Resource): @admins_only
64
64
124
18
46
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeTypes
ChallengeTypes
241
258
241
243
b39d62c91f24890cda14cd4d926dc6d9cc5df87c
bigcode/the-stack
train
1cbb7099fa8f875231e4825a
train
class
@challenges_namespace.route("") class ChallengeList(Resource): @check_challenge_visibility @during_ctf_time_only @require_verified_emails @challenges_namespace.doc( description="Endpoint to get Challenge objects in bulk", responses={ 200: ("Success", "ChallengeListSuccessResp...
@challenges_namespace.route("") class ChallengeList(Resource): @check_challenge_visibility @during_ctf_time_only @require_verified_emails @challenges_namespace.doc( description="Endpoint to get Challenge objects in bulk", responses={ 200: ("Success", "ChallengeListSuccessResp...
def get(self, query_args): # Build filtering queries q = query_args.pop("q", None) field = str(query_args.pop("field", None)) filters = build_model_filters(model=Challenges, query=q, field=field) # This can return None (unauth) if visibility is set to public user = g...
( "ChallengeListSuccessResponse", ChallengeListSuccessResponse.apidoc() ) @challenges_namespace.route("") class ChallengeList(Resource): @check_challenge_visibility @during_ctf_time_only @require_verified_emails @challenges_namespace.doc( description="Endpoint to get Challenge objects in bul...
256
256
1,038
239
17
pynight-update/new-ctfd
CTFd/api/v1/challenges.py
Python
ChallengeList
ChallengeList
78
238
78
117
e6178e6976260a939e21f502320e928f46691bad
bigcode/the-stack
train
2d947bd7f70d388b5967b0b4
train
function
def rsaset(tb,tff,nb,base,ml) : bd="B"+tb+"_"+base fnameh="config_big_"+bd+".h" run_in_shell(copytext+" config_big.h "+fnameh) replace(fnameh,"XXX",bd) replace(fnameh,"@NB@",nb) replace(fnameh,"@BASE@",base) fnameh="config_ff_"+tff+".h" run_in_shell(copytext+" config_ff.h "+fnameh) replace(fnameh,"XXX",bd) r...
def rsaset(tb,tff,nb,base,ml) :
bd="B"+tb+"_"+base fnameh="config_big_"+bd+".h" run_in_shell(copytext+" config_big.h "+fnameh) replace(fnameh,"XXX",bd) replace(fnameh,"@NB@",nb) replace(fnameh,"@BASE@",base) fnameh="config_ff_"+tff+".h" run_in_shell(copytext+" config_ff.h "+fnameh) replace(fnameh,"XXX",bd) replace(fnameh,"WWW",tff) replac...
if sys.platform.startswith("darwin") : deltext="rm" copytext="cp" if sys.platform.startswith("win") : deltext="del" copytext="copy" def run_in_shell(cmd): subprocess.check_call(cmd, shell=True) def replace(namefile,oldtext,newtext): f = open(namefile,'r') filedata = f.read() f.close() newdata = filedata...
121
121
406
14
107
kirk-baird/amcl
version3/cpp/config16.py
Python
rsaset
rsaset
31
77
31
31
2f0cb69beb6bbb27fc17f6857b1555639a7824c3
bigcode/the-stack
train
7ddc867d89671cb1a7990656
train
function
def run_in_shell(cmd): subprocess.check_call(cmd, shell=True)
def run_in_shell(cmd):
subprocess.check_call(cmd, shell=True)
="" if sys.platform.startswith("linux") : deltext="rm" copytext="cp" if sys.platform.startswith("darwin") : deltext="rm" copytext="cp" if sys.platform.startswith("win") : deltext="del" copytext="copy" def run_in_shell(cmd):
64
64
15
6
58
kirk-baird/amcl
version3/cpp/config16.py
Python
run_in_shell
run_in_shell
16
17
16
16
2b88a41fdb8ad19bc4d6e0d0ffe48f71363dbb7f
bigcode/the-stack
train
95c2a4146b7a8773375311b4
train
function
def replace(namefile,oldtext,newtext): f = open(namefile,'r') filedata = f.read() f.close() newdata = filedata.replace(oldtext,newtext) f = open(namefile,'w') f.write(newdata) f.close()
def replace(namefile,oldtext,newtext):
f = open(namefile,'r') filedata = f.read() f.close() newdata = filedata.replace(oldtext,newtext) f = open(namefile,'w') f.write(newdata) f.close()
" if sys.platform.startswith("darwin") : deltext="rm" copytext="cp" if sys.platform.startswith("win") : deltext="del" copytext="copy" def run_in_shell(cmd): subprocess.check_call(cmd, shell=True) def replace(namefile,oldtext,newtext):
64
64
54
10
54
kirk-baird/amcl
version3/cpp/config16.py
Python
replace
replace
19
28
19
19
7aaa3696f168cb03924bceb9eb8dd227aea9d61a
bigcode/the-stack
train
96f17049a70819498e429ac9
train
function
def curveset(tb,tf,tc,nb,base,nbt,m8,mt,ct,pf,stw,sx,ab,cs) : bd="B"+tb+"_"+base fnameh="config_big_"+bd+".h" run_in_shell(copytext+" config_big.h "+fnameh) replace(fnameh,"XXX",bd) replace(fnameh,"@NB@",nb) replace(fnameh,"@BASE@",base) fnameh="config_field_"+tf+".h" run_in_shell(copytext+" config_field.h "+f...
def curveset(tb,tf,tc,nb,base,nbt,m8,mt,ct,pf,stw,sx,ab,cs) :
bd="B"+tb+"_"+base fnameh="config_big_"+bd+".h" run_in_shell(copytext+" config_big.h "+fnameh) replace(fnameh,"XXX",bd) replace(fnameh,"@NB@",nb) replace(fnameh,"@BASE@",base) fnameh="config_field_"+tf+".h" run_in_shell(copytext+" config_field.h "+fnameh) replace(fnameh,"XXX",bd) replace(fnameh,"YYY",tf) re...
) replace(fnameh,"XXX",bd) run_in_shell("g++ -O3 -c "+fnamec) fnamec="ff_"+tff+".cpp" fnameh="ff_"+tff+".h" run_in_shell(copytext+" ff.cpp "+fnamec) run_in_shell(copytext+" ff.h "+fnameh) replace(fnamec,"WWW",tff) replace(fnamec,"XXX",bd) replace(fnameh,"WWW",tff) replace(fnameh,"XXX",bd) run_in_shell("g+...
256
256
1,683
33
223
kirk-baird/amcl
version3/cpp/config16.py
Python
curveset
curveset
79
260
79
79
4842978f243d6286154ad8a289fc45dfdd1a9d69
bigcode/the-stack
train
1b0e828b054745d59a3eadfc
train
function
def gumbel_softmax_sample(logits, temperature=1): y = logits + sample_gumbel(logits.size()) return F.softmax(y / temperature, dim=-1)
def gumbel_softmax_sample(logits, temperature=1):
y = logits + sample_gumbel(logits.size()) return F.softmax(y / temperature, dim=-1)
umbel_softmax_vae.py def sample_gumbel(shape, eps=1e-20): U = torch.rand(shape) U = U.cuda() return -torch.log(-torch.log(U + eps) + eps) def gumbel_softmax_sample(logits, temperature=1):
64
64
39
14
50
RICE-EIC/Auto-NBA
model_search.py
Python
gumbel_softmax_sample
gumbel_softmax_sample
28
30
28
28
cc22bbfa3193d08088c2104b32e45fc583d17720
bigcode/the-stack
train
fc7e21c5e6ca4140f226c6c0
train
function
def sample_gumbel(shape, eps=1e-20): U = torch.rand(shape) U = U.cuda() return -torch.log(-torch.log(U + eps) + eps)
def sample_gumbel(shape, eps=1e-20):
U = torch.rand(shape) U = U.cuda() return -torch.log(-torch.log(U + eps) + eps)
from thop import profile from analytical_model.analytical_prediction import search_for_best_latency, evaluate_latency # https://github.com/YongfeiYan/Gumbel_Softmax_VAE/blob/master/gumbel_softmax_vae.py def sample_gumbel(shape, eps=1e-20):
64
64
42
14
49
RICE-EIC/Auto-NBA
model_search.py
Python
sample_gumbel
sample_gumbel
22
25
22
22
fc81691ced264670d29a3d5070dd736de384ff63
bigcode/the-stack
train
2e2d405039da1851b8111e38
train
class
class MixedOp(nn.Module): def __init__(self, C_in, C_out, layer_id, stride=1, num_bits_list=[32], mode='soft', mode_bit='soft', act_num=1, act_num_bit=1, hetero=False, flops_mode='sum'): super(MixedOp, self).__init__() self._ops = nn.ModuleList() self.layer_id = layer_id self....
class MixedOp(nn.Module):
def __init__(self, C_in, C_out, layer_id, stride=1, num_bits_list=[32], mode='soft', mode_bit='soft', act_num=1, act_num_bit=1, hetero=False, flops_mode='sum'): super(MixedOp, self).__init__() self._ops = nn.ModuleList() self.layer_id = layer_id self.num_bits_list = num_bits_list...
.log(U + eps) + eps) def gumbel_softmax_sample(logits, temperature=1): y = logits + sample_gumbel(logits.size()) return F.softmax(y / temperature, dim=-1) def gumbel_softmax(logits, temperature=1, hard=False): """ ST-gumple-softmax input: [*, n_class] return: flatten --> [*, n_cl...
256
256
1,619
6
249
RICE-EIC/Auto-NBA
model_search.py
Python
MixedOp
MixedOp
56
197
56
57
bdf8933255c0ad1486c40127fc10127930eac2c1
bigcode/the-stack
train
6a296b350d19935fb756fa7b
train
class
class FBNet(nn.Module): def __init__(self, config): super(FBNet, self).__init__() self.hard = config.hard self.mode = config.mode self.mode_bit = config.mode_bit self.act_num = config.act_num self.act_num_bit = config.act_num_bit self.num_classes...
class FBNet(nn.Module):
def __init__(self, config): super(FBNet, self).__init__() self.hard = config.hard self.mode = config.mode self.mode_bit = config.mode_bit self.act_num = config.act_num self.act_num_bit = config.act_num_bit self.num_classes = config.num_classes ...
if type(self.num_bits_list) == list: bit_id = beta[op_id].argsort(descending=True)[0] result = alpha[op_id] * flops * beta[op_id][bit_id] * self.num_bits_list[bit_id] * self.num_bits_list[bit_id] /32 /32 else: result = alpha[op_id] * flops ...
256
256
2,212
6
249
RICE-EIC/Auto-NBA
model_search.py
Python
FBNet
FBNet
201
442
201
201
7d59c31c1758ab796dabc828126ebf82fd902d8a
bigcode/the-stack
train
65c511d980edba01e2dc38bc
train
function
def gumbel_softmax(logits, temperature=1, hard=False): """ ST-gumple-softmax input: [*, n_class] return: flatten --> [*, n_class] an one-hot vector """ y = gumbel_softmax_sample(F.log_softmax(logits, dim=-1), temperature) return y
def gumbel_softmax(logits, temperature=1, hard=False):
""" ST-gumple-softmax input: [*, n_class] return: flatten --> [*, n_class] an one-hot vector """ y = gumbel_softmax_sample(F.log_softmax(logits, dim=-1), temperature) return y
torch.log(U + eps) + eps) def gumbel_softmax_sample(logits, temperature=1): y = logits + sample_gumbel(logits.size()) return F.softmax(y / temperature, dim=-1) def gumbel_softmax(logits, temperature=1, hard=False):
64
64
77
16
48
RICE-EIC/Auto-NBA
model_search.py
Python
gumbel_softmax
gumbel_softmax
33
41
33
33
e656489e661094c9156639d269025ac1c79a02e7
bigcode/the-stack
train
728c7e9bd862c459811300ca
train
class
class GetQualificationUploadPolicyRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Domain', '2018-01-29', 'GetQualificationUploadPolicy') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_re...
class GetQualificationUploadPolicyRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Domain', '2018-01-29', 'GetQualificationUploadPolicy') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint...
WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkdomain.endpoint import endpoint_data class GetQualificationUploadPolicyRequest(RpcReques...
64
64
180
10
53
yndu13/aliyun-openapi-python-sdk
aliyun-python-sdk-domain/aliyunsdkdomain/request/v20180129/GetQualificationUploadPolicyRequest.py
Python
GetQualificationUploadPolicyRequest
GetQualificationUploadPolicyRequest
23
44
23
24
2c8f4dff28a11d6f2f201e7755bf3c116503a601
bigcode/the-stack
train
700154db635e157896c1205f
train
class
class CategoriesService(Protocol): async def get_all(self) -> list[ProductCategory]: ...
class CategoriesService(Protocol):
async def get_all(self) -> list[ProductCategory]: ...
from typing import Protocol from app.core.models import ProductCategory class CategoriesService(Protocol):
19
64
21
6
12
t3m8ch/aiogram-dialog-store
app/core/abstractions/services/categories.py
Python
CategoriesService
CategoriesService
6
8
6
6
a0ddef8fee10143f3fc2a4463511cff875942d5a
bigcode/the-stack
train
91c6357973d1b8d2e1abc173
train
function
def get_all_commit_info( user_id: str, name_with_owner: str, start_date: datetime, end_date: datetime, access_token: Optional[str] = None, ) -> List[RESTRawCommit]: """Gets all user's commit times for a given repository""" owner, repo = name_with_owner.split("/") data: List[RESTRawCommit...
def get_all_commit_info( user_id: str, name_with_owner: str, start_date: datetime, end_date: datetime, access_token: Optional[str] = None, ) -> List[RESTRawCommit]:
"""Gets all user's commit times for a given repository""" owner, repo = name_with_owner.split("/") data: List[RESTRawCommit] = [] def _get_repo_commits(page: int): return get_repo_commits( owner, repo, user_id, start_date, end_date, page, access_token ) for i in range(1...
.occurred_at)) ) return repo_contribs def get_all_commit_info( user_id: str, name_with_owner: str, start_date: datetime, end_date: datetime, access_token: Optional[str] = None, ) -> List[RESTRawCommit]:
64
64
179
50
13
rutvikpadhiyar000/github-trends
backend/src/subscriber/aggregation/user/contributions.py
Python
get_all_commit_info
get_all_commit_info
84
106
84
90
2a7f9b79d9cfee8272df296ffc0c946ea3fa3e0c
bigcode/the-stack
train
d9393755deade1440f5da1fe
train
function
async def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", full: bool = False, access_token: Optional[str] = None, ) -> Union[UserContributions, FullUserContributions]: tz = pytz.timezone(timez...
async def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", full: bool = False, access_token: Optional[str] = None, ) -> Union[UserContributions, FullUserContributions]:
tz = pytz.timezone(timezone_str) start = datetime.now() # Step 1: get years for contribution calendar (GraphQL) years = sorted( filter( lambda x: start_date.year <= x <= end_date.year, get_user_contribution_years(user_id, access_token), ) ) dates = [ ...
def get_all_commit_info( user_id: str, name_with_owner: str, start_date: datetime, end_date: datetime, access_token: Optional[str] = None, ) -> List[RESTRawCommit]: """Gets all user's commit times for a given repository""" owner, repo = name_with_owner.split("/") data: List[RESTRawCom...
256
256
3,274
76
179
rutvikpadhiyar000/github-trends
backend/src/subscriber/aggregation/user/contributions.py
Python
get_contributions
get_contributions
109
485
109
116
b7cc5493d11c4fad45f4c1c29fa3d76e3b0df8ad
bigcode/the-stack
train
cef42e14558a9bf3e32ffda8
train
function
def get_user_all_contribution_events( user_id: str, start_date: datetime, end_date: datetime, access_token: Optional[str] = None, ) -> t_stats: repo_contribs: t_stats = defaultdict( lambda: {"commits": [], "issues": [], "prs": [], "reviews": [], "repos": []} ) after: Optional[str] = ...
def get_user_all_contribution_events( user_id: str, start_date: datetime, end_date: datetime, access_token: Optional[str] = None, ) -> t_stats:
repo_contribs: t_stats = defaultdict( lambda: {"commits": [], "issues": [], "prs": [], "reviews": [], "repos": []} ) after: Optional[str] = "" cont = True while cont: after_str = after if isinstance(after, str) else "" response = get_user_contribution_events( user...
Dict[str, List[Union[RawEventsEvent, RawEventsCommit]]]] t_commits = List[Dict[str, Union[Dict[str, Dict[str, Union[str, int]]], str]]] t_languages = List[Dict[str, Dict[str, Union[str, int]]]] def get_user_all_contribution_events( user_id: str, start_date: datetime, end_date: datetime, access_token: O...
100
101
338
41
59
rutvikpadhiyar000/github-trends
backend/src/subscriber/aggregation/user/contributions.py
Python
get_user_all_contribution_events
get_user_all_contribution_events
36
81
36
41
150f706feb9c4d3a53124a43dcba1ba61a2624c6
bigcode/the-stack
train
44f08ea6f5816267760d7399
train
function
def read_worker(args, q_in, q_out): while True: deq = q_in.get() if deq is None: break i, item = deq audio_encode(args, i, item, q_out)
def read_worker(args, q_in, q_out):
while True: deq = q_in.get() if deq is None: break i, item = deq audio_encode(args, i, item, q_out)
parse.ArgumentDefaultsHelpFormatter, description='Create an image list or \ make a record database by reading from an image list') args = parser.parse_args() return args def audio_encode(args, i, item, q_out): pass def read_worker(args, q_in, q_out):
64
64
53
11
52
fanlu/deepspeech.mxnet
create_rec.py
Python
read_worker
read_worker
28
34
28
28
c9671a7c54bfb059e53e80da31c5e84de7426797
bigcode/the-stack
train
487e79f453be5f1e9f203e4e
train
function
def parse_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Create an image list or \ make a record database by reading from an image list') args = parser.parse_args() return args
def parse_args():
parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Create an image list or \ make a record database by reading from an image list') args = parser.parse_args() return args
from __future__ import print_function import mxnet as mx import glob import argparse import os import time try: import multiprocessing except ImportError: multiprocessing = None def parse_args():
45
64
54
4
40
fanlu/deepspeech.mxnet
create_rec.py
Python
parse_args
parse_args
15
21
15
15
7b92b38180dc491723af95e8fedc89622f1e7660
bigcode/the-stack
train
3cb093e3e23a5f7d7023cc59
train
function
def audio_encode(args, i, item, q_out): pass
def audio_encode(args, i, item, q_out):
pass
_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Create an image list or \ make a record database by reading from an image list') args = parser.parse_args() return args def audio_encode(args, i, item, q_out):
64
64
15
12
51
fanlu/deepspeech.mxnet
create_rec.py
Python
audio_encode
audio_encode
24
25
24
24
7d82d693614ac8780a18775a5e8d0b7a3fc9e52a
bigcode/the-stack
train
6fd5f8e136bd805781f268b4
train
function
def write_worker(q_out, fname, working_dir): pre_time = time.time() count = 0 fname = os.path.basename(fname) fname_rec = os.path.splitext(fname)[0] + '.rec' fname_idx = os.path.splitext(fname)[0] + '.idx' record = mx.recordio.MXIndexedRecordIO(os.path.join(working_dir, fname_idx), ...
def write_worker(q_out, fname, working_dir):
pre_time = time.time() count = 0 fname = os.path.basename(fname) fname_rec = os.path.splitext(fname)[0] + '.rec' fname_idx = os.path.splitext(fname)[0] + '.idx' record = mx.recordio.MXIndexedRecordIO(os.path.join(working_dir, fname_idx), os.path.join(wo...
, q_out): pass def read_worker(args, q_in, q_out): while True: deq = q_in.get() if deq is None: break i, item = deq audio_encode(args, i, item, q_out) def write_worker(q_out, fname, working_dir):
71
71
237
11
60
fanlu/deepspeech.mxnet
create_rec.py
Python
write_worker
write_worker
37
64
37
37
f0eda52d02652279854ddc554751b928c05504ab
bigcode/the-stack
train
e9cce16556552854c0edcf89
train
class
class LLVM(GCC): DEFINES = ['__GNUC__', '__GNUG__'] NAMES = ('LLVM', 'GCC') def __init__(self, gcc, gxx, extra_args={}): GCC.__init__(self, gcc, gxx, extra_args)
class LLVM(GCC):
DEFINES = ['__GNUC__', '__GNUG__'] NAMES = ('LLVM', 'GCC') def __init__(self, gcc, gxx, extra_args={}): GCC.__init__(self, gcc, gxx, extra_args)
v.append_unique('CFLAGS', ['-fvisibility=hidden']) v.append_unique('CXXFLAGS', ['-fvisibility=hidden']) v.CFLAGS_exportall = ['-fvisibility=default'] v.CXXFLAGS_exportall = ['-fvisibility=default'] class LLVM(GCC):
64
64
61
5
59
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
LLVM
LLVM
57
62
57
57
0a39d0bf215ebe7d8499911f935cc7875e594b4f
bigcode/the-stack
train
5ad3613540d74e6717676b94
train
function
def detect_gcc_version(conf, bindir, version, target, seen): gcc_compilers = [] v = version.split('.') versions = [ '.'.join(v), ''.join(v), '.'.join(v[0:2]), ''.join(v[0:2]), v[0], '-' + '.'.join(v), '-' + ''.join(v), '-' + '.'.join(v[0:2]), ...
def detect_gcc_version(conf, bindir, version, target, seen):
gcc_compilers = [] v = version.split('.') versions = [ '.'.join(v), ''.join(v), '.'.join(v[0:2]), ''.join(v[0:2]), v[0], '-' + '.'.join(v), '-' + ''.join(v), '-' + '.'.join(v[0:2]), '-' + ''.join(v[0:2]), '-' + v[0], '',...
): if platform.NAME != 'windows': v.append_unique('CFLAGS', ['-fvisibility=hidden']) v.append_unique('CXXFLAGS', ['-fvisibility=hidden']) v.CFLAGS_exportall = ['-fvisibility=default'] v.CXXFLAGS_exportall = ['-fvisibility=default'] class LLV...
146
146
489
16
130
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
detect_gcc_version
detect_gcc_version
65
127
65
65
17e29ead983bb6f7d7e1e09ff8b92523e7739a49
bigcode/the-stack
train
102191ff3d52517557a293d2
train
function
def detect_gcc(conf): environ = getattr(conf, 'environ', os.environ) bindirs = environ['PATH'].split(os.pathsep) + conf.env.EXTRA_PATH paths = [os.path.normpath(os.path.join(path, '..', 'lib')) for path in bindirs] paths = set([path for path in paths if os.path.isdir(path)]) for bindir in bindirs: ...
def detect_gcc(conf):
environ = getattr(conf, 'environ', os.environ) bindirs = environ['PATH'].split(os.pathsep) + conf.env.EXTRA_PATH paths = [os.path.normpath(os.path.join(path, '..', 'lib')) for path in bindirs] paths = set([path for path in paths if os.path.isdir(path)]) for bindir in bindirs: try: ...
bsd': try: c = GCC('/usr/bin/gcc', '/usr/bin/g++') except BaseException: pass else: if c.is_valid(conf): try: seen[c.name()].add_sibling(c) except KeyError: seen[c.name()] = c ...
153
153
511
6
147
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
detect_gcc
detect_gcc
219
259
219
219
91ab3a9de5eaced424e528c8d8b5c6f1e1da514c
bigcode/the-stack
train
3cda5181c504ffb2ed843c8a
train
function
@Configure.conf def gcc_modifier_platform(conf): pass
@Configure.conf def gcc_modifier_platform(conf):
pass
from waflib import Utils, Logs, Configure, Options from waflib.Tools import c_config, gcc, gxx import os import sys @Configure.conf def check_gcc_o_space(self, mode='c'): pass @Configure.conf def gcc_modifier_platform(conf):
60
64
13
10
49
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
gcc_modifier_platform
gcc_modifier_platform
12
14
12
13
fe37be76956c790b13198d7d797a8f6b40bfba85
bigcode/the-stack
train
8c9ba281ab3560865b4bc881
train
function
def detect_multilib_compilers(conf, gcc_compilers, seen): multilib_compilers = [] for c in gcc_compilers: for multilib_compiler in c.get_multilib_compilers(): if not multilib_compiler.is_valid(conf): continue try: seen[multilib_compiler.name()].add...
def detect_multilib_compilers(conf, gcc_compilers, seen):
multilib_compilers = [] for c in gcc_compilers: for multilib_compiler in c.get_multilib_compilers(): if not multilib_compiler.is_valid(conf): continue try: seen[multilib_compiler.name()].add_sibling(multilib_compiler) except KeyError: ...
if os.path.isdir(os.path.join(path, version, 'gcc')): for target in os.listdir(os.path.join(path, version, 'gcc')): bindir = os.path.normpath(os.path.join(path, '..', '..', 'bin')) gcc_compilers += detect_gcc_version(conf, bindir, version, target, seen) return gcc_compil...
90
90
302
14
75
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
detect_multilib_compilers
detect_multilib_compilers
161
192
161
161
404a8d2da3650351a9d08f499df8be76de077353
bigcode/the-stack
train
e9b06581c06b5c3ac5712eca
train
function
def detect_gcc_from_path(conf, path, seen): gcc_compilers = [] for subdir, relative in [ ('', '../..'), ('lib/gcc', '../../../..'), ('lib64/gcc', '../../../..'), ('gcc', '../../..'), ('llvm', '../../..') ]: libdir = os.path.join(path, subdir) if not os.path.isdir(libdir): ...
def detect_gcc_from_path(conf, path, seen):
gcc_compilers = [] for subdir, relative in [ ('', '../..'), ('lib/gcc', '../../../..'), ('lib64/gcc', '../../../..'), ('gcc', '../../..'), ('llvm', '../../..') ]: libdir = os.path.join(path, subdir) if not os.path.isdir(libdir): continue for target in os.l...
c = find_target_gcc(target, GCC) if c: gcc_compilers.append(c) result, out, err = c.run_c(['-fplugin=dragonegg', '-E', '-'], '') if result == 0: c = find_target_gcc('llvm', LLVM) if c: gcc_compilers.append(c) return gcc_compilers def detect_g...
96
96
321
12
83
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
detect_gcc_from_path
detect_gcc_from_path
130
158
130
130
5621e8e5a68c6045151000226d9f95d7fae8abe5
bigcode/the-stack
train
b702cc90d153d60be1758ce1
train
function
@Configure.conf def gxx_modifier_platform(conf): pass
@Configure.conf def gxx_modifier_platform(conf):
pass
Options from waflib.Tools import c_config, gcc, gxx import os import sys @Configure.conf def check_gcc_o_space(self, mode='c'): pass @Configure.conf def gcc_modifier_platform(conf): pass @Configure.conf def gxx_modifier_platform(conf):
64
64
14
11
52
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
gxx_modifier_platform
gxx_modifier_platform
17
19
17
18
3131acf9fc24b75f8b8b0f9cd2238f893efa31ac
bigcode/the-stack
train
26aea0a788693410b1eead30
train
function
def configure(conf): conf.start_msg('Looking for gcc compilers') detect_gcc(conf) conf.end_msg('done')
def configure(conf):
conf.start_msg('Looking for gcc compilers') detect_gcc(conf) conf.end_msg('done')
_compilers += detect_gcc_from_path( conf, os.path.join(gcc_lib_path, version, 'gcc'), seen ) except OSError: pass detect_multilib_compilers(conf, gcc_compilers, seen) get_native_gcc(conf, seen) def configure(conf):
64
64
28
4
60
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
configure
configure
262
265
262
262
fe228053161368cac75a0a8b7d7699fa3ea9a840
bigcode/the-stack
train
5b7107a488010525666d6096
train
function
@Configure.conf def check_gcc_o_space(self, mode='c'): pass
@Configure.conf def check_gcc_o_space(self, mode='c'):
pass
from waflib import Utils, Logs, Configure, Options from waflib.Tools import c_config, gcc, gxx import os import sys @Configure.conf def check_gcc_o_space(self, mode='c'):
47
64
19
16
30
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
check_gcc_o_space
check_gcc_o_space
7
9
7
8
69d6a3a76afe47bdd71e5e5d50147d175937d460
bigcode/the-stack
train
07a8a0d22b5c0ed9ef3a2f5e
train
function
def get_native_gcc(conf, seen): import platform if platform.uname()[0].lower() == 'freebsd': try: c = GCC('/usr/bin/gcc', '/usr/bin/g++') except BaseException: pass else: if c.is_valid(conf): try: seen[c.name()].add_...
def get_native_gcc(conf, seen):
import platform if platform.uname()[0].lower() == 'freebsd': try: c = GCC('/usr/bin/gcc', '/usr/bin/g++') except BaseException: pass else: if c.is_valid(conf): try: seen[c.name()].add_sibling(c) excep...
: pass else: try: seen[compiler.name()].add_sibling(compiler) except KeyError: seen[compiler.name()] = compiler multilib_compilers.append(compil...
64
64
173
9
54
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
get_native_gcc
get_native_gcc
195
216
195
195
d9e7ca4f584c74e6247f4fce78b0ea0c02c8b69f
bigcode/the-stack
train
de0663773b823183abb8bc08
train
class
class GCC(Configure.ConfigurationContext.GnuCompiler): DEFINES = ['__GNUC__', '__GNUG__'] NAMES = ('GCC', ) TOOLS = 'gcc gxx' def __init__(self, gcc, gxx, extra_args={}, extra_env={}): Configure.ConfigurationContext.GnuCompiler.__init__(self, gcc, gxx, extra_args, extra_env) def set_optimi...
class GCC(Configure.ConfigurationContext.GnuCompiler):
DEFINES = ['__GNUC__', '__GNUG__'] NAMES = ('GCC', ) TOOLS = 'gcc gxx' def __init__(self, gcc, gxx, extra_args={}, extra_env={}): Configure.ConfigurationContext.GnuCompiler.__init__(self, gcc, gxx, extra_args, extra_env) def set_optimisation_options(self, conf): Configure.Configura...
from waflib import Utils, Logs, Configure, Options from waflib.Tools import c_config, gcc, gxx import os import sys @Configure.conf def check_gcc_o_space(self, mode='c'): pass @Configure.conf def gcc_modifier_platform(conf): pass @Configure.conf def gxx_modifier_platform(conf): pass class GCC(Configur...
87
102
340
10
76
bugengine/BugEngine
mak/build_framework/configure/compiler/gcc.py
Python
GCC
GCC
22
54
22
22
1c46ae3b897470c9d302221934c61b3f2e906ffa
bigcode/the-stack
train
8176caa32678d42511d6bbd9
train
class
class ExtOperationError(PosixOperationError): pass
class ExtOperationError(PosixOperationError):
pass
interface. For now, this just offers the posix operations, nothing more. @author: Stijn De Weirdt (Ghent University) @author: Andy Georges (Ghent University) """ from vsc.filesystem.posix import PosixOperations, PosixOperationError class ExtOperationError(PosixOperationError):
64
64
12
9
54
hpcugent/vsc-filesystems
lib/vsc/filesystem/ext.py
Python
ExtOperationError
ExtOperationError
27
28
27
27
ab8c39c24e369da25f86acea4b0addba53ad78ef
bigcode/the-stack
train
16c387df9b74b2789c57dbfd
train
class
class ExtOperations(PosixOperations): def __init__(self): super(ExtOperations, self).__init__() self.supportedfilesystems = ['ext2', 'ext3', 'ext4']
class ExtOperations(PosixOperations):
def __init__(self): super(ExtOperations, self).__init__() self.supportedfilesystems = ['ext2', 'ext3', 'ext4']
ix operations, nothing more. @author: Stijn De Weirdt (Ghent University) @author: Andy Georges (Ghent University) """ from vsc.filesystem.posix import PosixOperations, PosixOperationError class ExtOperationError(PosixOperationError): pass class ExtOperations(PosixOperations):
64
64
43
7
56
hpcugent/vsc-filesystems
lib/vsc/filesystem/ext.py
Python
ExtOperations
ExtOperations
31
35
31
32
7014654615bc46c893896295423a3dacfa119be9
bigcode/the-stack
train
3e5f4ed991f5d5dca8b81c1a
train
function
def server_run(args): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((args.host, args.port)) server_socket.listen() print('Kernel tuning daemon ready') while True: print('Wait fo...
def server_run(args):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((args.host, args.port)) server_socket.listen() print('Kernel tuning daemon ready') while True: print('Wait for request...') ...
#!/usr/bin/env python3 import argparse import struct import socket import pickle import time from utils import KernelTask, KernelDB, recvall def server_run(args):
39
64
190
5
33
SKKU-ESLAB/ANT-Model-DB
kernel-db/kernel_tuner.py
Python
server_run
server_run
10
36
10
10
84b1e9370db979d4afc7c1fe7666910f69afabff
bigcode/the-stack
train
06d918720a8e5c8a753d04b8
train
function
def auto_tune(args): kernel_db = KernelDB() while True: new_model_list = kernel_db.find_new_model() kernel_db.tune_model(new_model_list) # Sleep print("Sleep...") time.sleep(5)
def auto_tune(args):
kernel_db = KernelDB() while True: new_model_list = kernel_db.find_new_model() kernel_db.tune_model(new_model_list) # Sleep print("Sleep...") time.sleep(5)
_socket.sendall('Task received successfully'.encode()) client_socket.close() # Tuning start data = pickle.loads(data) kernel_task = KernelTask(data['task'], data['target'], data['device_key']) kernel_task.tune() server_socket.close() def auto_tune(args):
64
64
53
6
58
SKKU-ESLAB/ANT-Model-DB
kernel-db/kernel_tuner.py
Python
auto_tune
auto_tune
38
47
38
38
1ab56840e65f535cf588edec56ca5ff6829ac35a
bigcode/the-stack
train
4f57c9852895232040ff9018
train
function
def main(args): #server_run(args) auto_tune(args)
def main(args): #server_run(args)
auto_tune(args)
def auto_tune(args): kernel_db = KernelDB() while True: new_model_list = kernel_db.find_new_model() kernel_db.tune_model(new_model_list) # Sleep print("Sleep...") time.sleep(5) def main(args): #server_run(args)
63
64
16
10
53
SKKU-ESLAB/ANT-Model-DB
kernel-db/kernel_tuner.py
Python
main
main
50
52
50
51
b01bebaef27a7745960429c1830c7d75c9833415
bigcode/the-stack
train
b0ce3d161a5390db54cae97d
train
class
class SparkThriftServer(Script): def install(self, env): import params env.set_params(params) self.install_packages(env) def configure(self, env, upgrade_type=None, config_dir=None): import params env.set_params(params) setup_spark(env, 'server', upgrade_type = upgrade_type, action = 'con...
class SparkThriftServer(Script):
def install(self, env): import params env.set_params(params) self.install_packages(env) def configure(self, env, upgrade_type=None, config_dir=None): import params env.set_params(params) setup_spark(env, 'server', upgrade_type = upgrade_type, action = 'config') def start(self, env, upgr...
resource_management.libraries.script.script import Script from resource_management.libraries.functions import conf_select, stack_select from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.libraries.functions.constants import StackFeature from resource_managem...
99
99
333
8
90
dawnwish/ambari
ambari-server/src/main/resources/common-services/SPARK/2.2.0/scripts/spark_thrift_server.py
Python
SparkThriftServer
SparkThriftServer
35
86
35
36
9aece413a7e68dcf95115c0eb9c7504702ee3885
bigcode/the-stack
train
6edc653a1734ab456950c900
train
function
def _load_mne_locs(fname=None): """Load MNE locs structure from file (if exists) or recreate it.""" if (not fname): # find input file resource_dir = op.join(op.dirname(op.abspath(__file__)), 'resources') fname = op.join(resource_dir, 'Artemis123_mneLoc.csv') if not op.exists(fname):...
def _load_mne_locs(fname=None):
"""Load MNE locs structure from file (if exists) or recreate it.""" if (not fname): # find input file resource_dir = op.join(op.dirname(op.abspath(__file__)), 'resources') fname = op.join(resource_dir, 'Artemis123_mneLoc.csv') if not op.exists(fname): raise IOError('MNE locs...
import numpy as np import os.path as op from .._digitization import _artemis123_read_pos from ...utils import logger from ...transforms import rotation3d_align_z_axis def _load_mne_locs(fname=None):
52
64
171
10
41
rylaw/mne-python
mne/io/artemis123/utils.py
Python
_load_mne_locs
_load_mne_locs
8
25
8
8
c9525b03e4722418370a787824277dea0b904f68
bigcode/the-stack
train
5eb5acaa7fe05978aa40892a
train
function
def _load_tristan_coil_locs(coil_loc_path): """Load the Coil locations from Tristan CAD drawings.""" channel_info = dict() with open(coil_loc_path, 'r') as fid: # skip 2 Header lines fid.readline() fid.readline() for line in fid: line = line.strip() va...
def _load_tristan_coil_locs(coil_loc_path):
"""Load the Coil locations from Tristan CAD drawings.""" channel_info = dict() with open(coil_loc_path, 'r') as fid: # skip 2 Header lines fid.readline() fid.readline() for line in fid: line = line.strip() vals = line.split(',') channel_inf...
with open(output_fname, 'w') as fid: for n in sorted(locs.keys()): fid.write('%s,' % n) fid.write(','.join(locs[n].astype(str))) fid.write('\n') def _load_tristan_coil_locs(coil_loc_path):
64
64
203
14
50
rylaw/mne-python
mne/io/artemis123/utils.py
Python
_load_tristan_coil_locs
_load_tristan_coil_locs
46
65
46
46
40b815610867123ec4af996139e2e87d38350ab5
bigcode/the-stack
train
33c2e7cdd61c2db499522241
train
function
def _read_pos(fname): """Read the .pos file and return positions as dig points.""" nas, lpa, rpa, hpi, extra = None, None, None, None, None with open(fname, 'r') as fid: for line in fid: line = line.strip() if len(line) > 0: parts = line.split() ...
def _read_pos(fname):
"""Read the .pos file and return positions as dig points.""" nas, lpa, rpa, hpi, extra = None, None, None, None, None with open(fname, 'r') as fid: for line in fid: line = line.strip() if len(line) > 0: parts = line.split() # The lines can have...
il_loc['outer_coil']) == 0): return loc # channel location is inner coil location converted to meters From inches loc[0:3] = coil_loc['inner_coil'] / 39.370078 # figure out rotation z_axis = coil_loc['outer_coil'] - coil_loc['inner_coil'] R = rotation3d_align_z_axis(z_axis) loc[3:13] =...
112
112
374
6
105
rylaw/mne-python
mne/io/artemis123/utils.py
Python
_read_pos
_read_pos
88
119
88
88
3853e0a6f172e8351dd6c4e6a66287c7a94b4459
bigcode/the-stack
train
d70f2634b0808cd980ee0227
train
function
def _generate_mne_locs_file(output_fname): """Generate mne coil locs and save to supplied file.""" logger.info('Converting Tristan coil file to mne loc file...') resource_dir = op.join(op.dirname(op.abspath(__file__)), 'resources') chan_fname = op.join(resource_dir, 'Artemis123_ChannelMap.csv') chan...
def _generate_mne_locs_file(output_fname):
"""Generate mne coil locs and save to supplied file.""" logger.info('Converting Tristan coil file to mne loc file...') resource_dir = op.join(op.dirname(op.abspath(__file__)), 'resources') chan_fname = op.join(resource_dir, 'Artemis123_ChannelMap.csv') chans = _load_tristan_coil_locs(chan_fname) ...
= dict() with open(fname, 'r') as fid: for line in fid: vals = line.strip().split(',') locs[vals[0]] = np.array(vals[1::], np.float64) return locs def _generate_mne_locs_file(output_fname):
64
64
181
11
52
rylaw/mne-python
mne/io/artemis123/utils.py
Python
_generate_mne_locs_file
_generate_mne_locs_file
28
43
28
28
5a6c1dc30b78c530d2d382227a80f53feacc0e19
bigcode/the-stack
train
adfa78840d09f2339a8be246
train
function
def _compute_mne_loc(coil_loc): """Convert a set of coils to an mne Struct. Note input coil locations are in inches. """ loc = np.zeros((12)) if (np.linalg.norm(coil_loc['inner_coil']) == 0) and \ (np.linalg.norm(coil_loc['outer_coil']) == 0): return loc # channel location is in...
def _compute_mne_loc(coil_loc):
"""Convert a set of coils to an mne Struct. Note input coil locations are in inches. """ loc = np.zeros((12)) if (np.linalg.norm(coil_loc['inner_coil']) == 0) and \ (np.linalg.norm(coil_loc['outer_coil']) == 0): return loc # channel location is inner coil location converted to m...
.float64) else: # nothing supplied channel_info[vals[0]]['inner_coil'] = np.zeros(3) channel_info[vals[0]]['outer_coil'] = np.zeros(3) return channel_info def _compute_mne_loc(coil_loc):
64
64
174
10
53
rylaw/mne-python
mne/io/artemis123/utils.py
Python
_compute_mne_loc
_compute_mne_loc
68
85
68
68
bbf488ac86c7ec90732a0858cafc483e7ac61dde
bigcode/the-stack
train
b52483699aca19d71e93c649
train
function
def fix_return(ret): ret = replace_all(ret) tuple_contents = reTuple.match(ret) if tuple_contents: ret = f"{tuple_contents.group(1)}" else: ret = f"{ret}" return ret
def fix_return(ret):
ret = replace_all(ret) tuple_contents = reTuple.match(ret) if tuple_contents: ret = f"{tuple_contents.group(1)}" else: ret = f"{ret}" return ret
(p_name): p_type = m.group(1) p_name = m.group(2) ret += f"{p_name}: {p_type}, " ret = ret[:-2] return ret[:-2] reTuple = re.compile(r"tuple<(.*?)>") def fix_return(ret):
63
64
52
5
59
spelunky-fyi/rust-injector
docs/generate_emmylua.py
Python
fix_return
fix_return
130
137
130
130
e9be1dd1a46f2328f91496ec601d574d989e8793
bigcode/the-stack
train
809810ec956346e4aa4394c0
train
function
def print_func(name, params, ret, typed_params): ret = fix_return(ret) fun = f"{typed_params}\n---@return {ret}\nfunction {name}({params}) end".strip() print(fun)
def print_func(name, params, ret, typed_params):
ret = fix_return(ret) fun = f"{typed_params}\n---@return {ret}\nfunction {name}({params}) end".strip() print(fun)
def fix_return(ret): ret = replace_all(ret) tuple_contents = reTuple.match(ret) if tuple_contents: ret = f"{tuple_contents.group(1)}" else: ret = f"{ret}" return ret def print_func(name, params, ret, typed_params):
64
64
49
12
51
spelunky-fyi/rust-injector
docs/generate_emmylua.py
Python
print_func
print_func
140
143
140
140
7593bf0fcd854c6949278162ccf1300bca28fe05
bigcode/the-stack
train
a3080b44d6bebd68201745f5
train
function
def print_comment(lf): if lf["comment"]: for com in lf["comment"]: print(f"---{com}")
def print_comment(lf):
if lf["comment"]: for com in lf["comment"]: print(f"---{com}")
= f"{ret}" return ret def print_func(name, params, ret, typed_params): ret = fix_return(ret) fun = f"{typed_params}\n---@return {ret}\nfunction {name}({params}) end".strip() print(fun) def print_comment(lf):
64
64
28
6
58
spelunky-fyi/rust-injector
docs/generate_emmylua.py
Python
print_comment
print_comment
146
149
146
146
9611483764468c916d10967e0e65001bd01eb941
bigcode/the-stack
train
66c3d5999959017e5c584a6a
train
function
def cpp_params_to_emmy_lua(params_text): return_typed = "" return_normal = "" params_iterator = reGetParam.finditer(params_text) for param_match in params_iterator: p_type = replace_all(param_match.group(1)) p_name = reRemoveDefault.sub("", param_match.group(2)) if p_type == "var...
def cpp_params_to_emmy_lua(params_text):
return_typed = "" return_normal = "" params_iterator = reGetParam.finditer(params_text) for param_match in params_iterator: p_type = replace_all(param_match.group(1)) p_name = reRemoveDefault.sub("", param_match.group(2)) if p_type == "variadic_args": return_typed += ...
.run_parse() reGetParam = re.compile(r"(?!const)(\b[^ ]+) *([^,]+),?") reRemoveDefault = re.compile(r" = .*") reHandleConst = re.compile(r"const (\w+) (\w+)") def cpp_params_to_emmy_lua(params_text):
63
64
182
11
52
spelunky-fyi/rust-injector
docs/generate_emmylua.py
Python
cpp_params_to_emmy_lua
cpp_params_to_emmy_lua
91
109
91
91
bdb94b2ae1e751ee13e3ec6e2053e3acd52ce8d7
bigcode/the-stack
train
d3b7a4bb961b85d7aab1160c
train
function
def print_af(lf, af): if lf["comment"] and lf["comment"][0] == "NoDoc": return ret = replace_all(af["return"]) or "nil" name = lf["name"] typed_params, params = cpp_params_to_emmy_lua(af["param"]) typed_params.strip() typed_params = replace_all(typed_params) print_comment(lf if lf["c...
def print_af(lf, af):
if lf["comment"] and lf["comment"][0] == "NoDoc": return ret = replace_all(af["return"]) or "nil" name = lf["name"] typed_params, params = cpp_params_to_emmy_lua(af["param"]) typed_params.strip() typed_params = replace_all(typed_params) print_comment(lf if lf["comment"] else af) ...
f"{typed_params}\n---@return {ret}\nfunction {name}({params}) end".strip() print(fun) def print_comment(lf): if lf["comment"]: for com in lf["comment"]: print(f"---{com}") def print_af(lf, af):
63
64
108
8
55
spelunky-fyi/rust-injector
docs/generate_emmylua.py
Python
print_af
print_af
152
161
152
152
419992943b21923449be18535b4b19dabcf3ae58
bigcode/the-stack
train
6f88897af74f96e4967305e8
train
function
def cpp_params_to_emmy_lua_fun(params_text): ret = "" params_iterator = reGetParam.finditer(params_text) for param_match in params_iterator: p_type = param_match.group(1) p_name = param_match.group(2) p_name = reRemoveDefault.sub("", p_name) if m := reHandleConst.match(p_name...
def cpp_params_to_emmy_lua_fun(params_text):
ret = "" params_iterator = reGetParam.finditer(params_text) for param_match in params_iterator: p_type = param_match.group(1) p_name = param_match.group(2) p_name = reRemoveDefault.sub("", p_name) if m := reHandleConst.match(p_name): p_type = m.group(1) ...
) return_typed += f"\n---@param {p_name} {p_type}" return_normal += p_name return_normal += ", " return_normal = return_normal[0:-2] return return_typed, return_normal def cpp_params_to_emmy_lua_fun(params_text):
64
64
123
12
51
spelunky-fyi/rust-injector
docs/generate_emmylua.py
Python
cpp_params_to_emmy_lua_fun
cpp_params_to_emmy_lua_fun
112
124
112
112
856efc14ba7194d9cca89bb5240616197f7f4e4b
bigcode/the-stack
train
197d1a5ab93c7539a4dd67a7
train
function
def replace_all(text): text = reFloat.sub("number", text) text = reInt.sub("integer", text) text = reBool.sub("boolean", text) text = reOptional.sub(r"\1?", text) text = reMap.sub("table<", text) if "Array<" in text: newText = text dimension = 1 while True: m ...
def replace_all(text):
text = reFloat.sub("number", text) text = reInt.sub("integer", text) text = reBool.sub("boolean", text) text = reOptional.sub(r"\1?", text) text = reMap.sub("table<", text) if "Array<" in text: newText = text dimension = 1 while True: m = reArr.search(newText)...
Optional = re.compile(r"optional<(.+?)>") reBool = re.compile(r"bool\b") reMap = re.compile(r"\bmap<") reArr = re.compile(r"(\bArray<(?:(\w+<.+>)|(\w+(?:<.+>)?))(?:, )?.*>)") def replace_all(text):
74
74
248
5
69
spelunky-fyi/rust-injector
docs/generate_emmylua.py
Python
replace_all
replace_all
49
79
49
49
1acfa4d17bbe2fcdc1123f7b4b196c82e064b676
bigcode/the-stack
train
65a85c8f4a602e0ec910793e
train
function
def _check_selection(selection): """Handle default and validation of selection""" available = ["counts", "exposure", "background"] if selection is None: selection = available if not isinstance(selection, list): raise TypeError("Selection must be a list of str") for name in selecti...
def _check_selection(selection):
"""Handle default and validation of selection""" available = ["counts", "exposure", "background"] if selection is None: selection = available if not isinstance(selection, list): raise TypeError("Selection must be a list of str") for name in selection: if name not in availa...
if self.fov_mask is not None: background.data[..., self.fov_mask] = 0 # TODO: decide what background modeling options to support # Extra things like FOV norm scale or ring would go here. self.maps["background"] = background def _check_selection(selection):
64
64
92
6
57
watsonjj/gammapy
gammapy/cube/make.py
Python
_check_selection
_check_selection
250
264
250
250
fc6241b459bc1678848cf29eb203a7d549f793af
bigcode/the-stack
train
a8f220df523e6823c49b5a8e
train
class
class MapMakerObs: """Make maps for a single IACT observation. Parameters ---------- observation : `~gammapy.data.DataStoreObservation` Observation geom : `~gammapy.maps.WcsGeom` Reference image geometry geom_true : `~gammapy.maps.WcsGeom` Reference image geometry in tru...
class MapMakerObs:
"""Make maps for a single IACT observation. Parameters ---------- observation : `~gammapy.data.DataStoreObservation` Observation geom : `~gammapy.maps.WcsGeom` Reference image geometry geom_true : `~gammapy.maps.WcsGeom` Reference image geometry in true energy, used for ...
"""Create images by summing over the energy axis. Exposure is weighted with an assumed spectrum, resulting in a weighted mean exposure image. Parameters ---------- spectrum : `~gammapy.spectrum.models.SpectralModel` Spectral model to compute the weights. ...
186
186
621
5
180
watsonjj/gammapy
gammapy/cube/make.py
Python
MapMakerObs
MapMakerObs
162
247
162
162
278e0d510c8ef24b3c5859490cb33218f7e2ed3c
bigcode/the-stack
train
a38c17513819b6871c0e517e
train
class
class MapMaker: """Make maps from IACT observations. Parameters ---------- geom : `~gammapy.maps.WcsGeom` Reference image geometry in reco energy offset_max : `~astropy.coordinates.Angle` Maximum offset angle geom_true : `~gammapy.maps.WcsGeom` Reference image geometry i...
class MapMaker:
"""Make maps from IACT observations. Parameters ---------- geom : `~gammapy.maps.WcsGeom` Reference image geometry in reco energy offset_max : `~astropy.coordinates.Angle` Maximum offset angle geom_true : `~gammapy.maps.WcsGeom` Reference image geometry in true energy, u...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import logging from astropy.nddata.utils import NoOverlapError from astropy.coordinates import Angle from ..maps import Map, WcsGeom from .counts import fill_map_counts from .exposure import make_map_exposure_true_energy, _map_spectrum_weight from .backgro...
109
256
1,136
4
105
watsonjj/gammapy
gammapy/cube/make.py
Python
MapMaker
MapMaker
15
159
15
15
d16554805d79ebafde43f612528a919885a4243e
bigcode/the-stack
train
07db87969e2eb1e8cd3d96f3
train
class
class MyPresenterClass(BaseCase): def test_presenter(self): self.create_presentation(theme="serif") self.add_slide( '<h1>Welcome</h1><br />\n' '<h3>Press the <b>Right Arrow</b></h3>') self.add_slide( '<h3>SeleniumBase Presenter</h3><br />\n' '...
class MyPresenterClass(BaseCase):
def test_presenter(self): self.create_presentation(theme="serif") self.add_slide( '<h1>Welcome</h1><br />\n' '<h3>Press the <b>Right Arrow</b></h3>') self.add_slide( '<h3>SeleniumBase Presenter</h3><br />\n' '<img width="240" src="https://selen...
from seleniumbase import BaseCase class MyPresenterClass(BaseCase):
14
256
1,615
7
6
johnhiggs/SeleniumBase
examples/presenter/my_presentation.py
Python
MyPresenterClass
MyPresenterClass
4
114
4
5
9094ecfadbc74828dd2744caff979f4f9dfbad94
bigcode/the-stack
train
3d9fd4281310f45b711b0625
train
function
def whitestripe(img, contrast, mask=None, width=0.05, width_l=None, width_u=None): """ find the "(normal appearing) white (matter) stripe" of the input MR image and return the indices Args: img (nibabel.nifti1.Nifti1Image): target MR image contrast (str): contrast of img (e.g., T1) ...
def whitestripe(img, contrast, mask=None, width=0.05, width_l=None, width_u=None):
""" find the "(normal appearing) white (matter) stripe" of the input MR image and return the indices Args: img (nibabel.nifti1.Nifti1Image): target MR image contrast (str): contrast of img (e.g., T1) mask (nibabel.nifti1.Nifti1Image): brainmask for img (None is default, for skul...
})'.format(img_fn, i, len(data))) img = io.open_nii(img_fn) mask = io.open_nii(mask_fn) if mask_fn is not None else None indices = whitestripe(img, contrast, mask=mask) normalized = whitestripe_norm(img, indices) if write_to_disk: logger.info('Saving normalized image:...
150
150
503
25
124
sarthakpati/intensity-normalization
intensity_normalization/normalize/whitestripe.py
Python
whitestripe
whitestripe
97
138
97
97
1caa3539669329e58106bb8d158a339306696584
bigcode/the-stack
train
b917f53b5d5cdfaf97b5ff9e
train
function
def whitestripe_norm(img, indices): """ use the whitestripe indices to standardize the data (i.e., subtract the mean of the values in the indices and divide by the std of those values) Args: img (nibabel.nifti1.Nifti1Image): target MR image indices (np.ndarray): whitestripe indices (see...
def whitestripe_norm(img, indices):
""" use the whitestripe indices to standardize the data (i.e., subtract the mean of the values in the indices and divide by the std of those values) Args: img (nibabel.nifti1.Nifti1Image): target MR image indices (np.ndarray): whitestripe indices (see whitestripe func) Returns: ...
) * 100)) ws_ind = np.logical_and(masked > ws[0], masked < ws[1]) if len(ws_ind) == 0: raise NormalizationError('WhiteStripe failed to find any valid indices!') return ws_ind def whitestripe_norm(img, indices):
64
64
185
9
54
sarthakpati/intensity-normalization
intensity_normalization/normalize/whitestripe.py
Python
whitestripe_norm
whitestripe_norm
141
158
141
141
51edd814482a62f9c5ada94d535acd65b1ff8d1d
bigcode/the-stack
train
8ec78beab22e1c93f77cf767
train
function
def ws_normalize(img_dir, contrast, mask_dir=None, output_dir=None, write_to_disk=True): """ Use WhiteStripe normalization method ([1]) to normalize the intensities of a set of MR images by normalizing an area around the white matter peak of the histogram Args: img_dir (str): directory containi...
def ws_normalize(img_dir, contrast, mask_dir=None, output_dir=None, write_to_disk=True):
""" Use WhiteStripe normalization method ([1]) to normalize the intensities of a set of MR images by normalizing an area around the white matter peak of the histogram Args: img_dir (str): directory containing MR images to be normalized contrast (str): contrast of MR images to be normali...
:  [1] R. T. Shinohara, E. M. Sweeney, J. Goldsmith, N. Shiee, F. J. Mateen, P. A. Calabresi, S. Jarso, D. L. Pham, D. S. Reich, and C. M. Crainiceanu, “Statistical normalization techniques for magnetic resonance imaging,” NeuroImage Clin., vol. 6, pp. 9–19, 2014. Author: Jacob Reinh...
205
205
686
22
183
sarthakpati/intensity-normalization
intensity_normalization/normalize/whitestripe.py
Python
ws_normalize
ws_normalize
33
94
33
33
3e28a48400584e1f97e142a5359f3358dc1d4d62
bigcode/the-stack
train
7255f3bf8404ea00e1003113
train
function
def read_atoms(filename='CONTCAR', return_velocities=False, species_list=None, species_from_potcar=False): """ Routine to read structural static from a POSCAR type file Args: filename (str): Input filename return_velocities (bool): True if the predictor corrector velocities are read (only f...
def read_atoms(filename='CONTCAR', return_velocities=False, species_list=None, species_from_potcar=False):
""" Routine to read structural static from a POSCAR type file Args: filename (str): Input filename return_velocities (bool): True if the predictor corrector velocities are read (only from MD output) species_list (list/numpy.ndarray): A list of the species (if not present in the POSC...
version__ = "1.0" __maintainer__ = "Sudarsan Surendralal" __email__ = "surendralal@mpie.de" __status__ = "production" __date__ = "Sep 1, 2017" def read_atoms(filename='CONTCAR', return_velocities=False, species_list=None, species_from_potcar=False):
81
81
270
25
56
SanderBorgmans/pyiron
pyiron/vasp/structure.py
Python
read_atoms
read_atoms
20
44
20
20
37801f57a2ae09c887dcc71994650698764112b0
bigcode/the-stack
train
23774dd1b3cd3210e152eff4
train
function
def atoms_from_string(string, read_velocities=False, species_list=None): """ Routine to convert a string list read from a input/output structure file and convert into Atoms instance Args: string (list): A list of strings (lines) read from the POSCAR/CONTCAR/CHGCAR/LOCPOT file read_velocitie...
def atoms_from_string(string, read_velocities=False, species_list=None):
""" Routine to convert a string list read from a input/output structure file and convert into Atoms instance Args: string (list): A list of strings (lines) read from the POSCAR/CONTCAR/CHGCAR/LOCPOT file read_velocities (bool): True if the velocities from a CONTCAR file should be read (pred...
for species in atom_numbers.keys(): indices = structure.select_index(species) for i in indices: if cartesian: sorted_coords.append(structure.positions[i]) else: sorted_coords.append(structure.get_scaled_positions()[i]) ...
256
256
1,107
15
241
SanderBorgmans/pyiron
pyiron/vasp/structure.py
Python
atoms_from_string
atoms_from_string
125
222
125
125
82435a21566d083094ac5070fcd131b561d253bd
bigcode/the-stack
train
f20e01b61f3a4528ed03c76c
train
function
def manip_contcar(filename, new_filename, add_pos): """ Manipulate a CONTCAR/POSCAR file by adding something to the positions Args: filename (str): Filename/path of the input file new_filename (str): Filename/path of the output file add_pos (list/numpy.ndarray): Array of values to ...
def manip_contcar(filename, new_filename, add_pos):
""" Manipulate a CONTCAR/POSCAR file by adding something to the positions Args: filename (str): Filename/path of the input file new_filename (str): Filename/path of the output file add_pos (list/numpy.ndarray): Array of values to be added to the positions of the input """ ...
cell=cell) else: atoms = Atoms(elements, scaled_positions=positions, cell=cell) return atoms def vasp_sorter(structure): """ Routine to sort the indices of a structure as it would be when written to a POSCAR file Args: structure (pyiron.atomistics.structure.atoms.Atoms): The stru...
170
170
567
12
157
SanderBorgmans/pyiron
pyiron/vasp/structure.py
Python
manip_contcar
manip_contcar
301
356
301
301
65e165daf6b7c5bb1e5dfc1f6050ab55689be662
bigcode/the-stack
train
4c8d500887cfdf44bf294d77
train
function
def get_species_list_from_potcar(filename="POTCAR"): """ Generates the species list from a POTCAR type file Args: filename (str): Input filename Returns: list: A list of species symbols """ trigger = "VRHFIN =" species_list = list() with open(filename) as potcar_file: ...
def get_species_list_from_potcar(filename="POTCAR"):
""" Generates the species list from a POTCAR type file Args: filename (str): Input filename Returns: list: A list of species symbols """ trigger = "VRHFIN =" species_list = list() with open(filename) as potcar_file: lines = potcar_file.readlines() for l...
list() with open(filename) as f: for line in f: line = line.strip() file_string.append(line) return atoms_from_string(file_string, read_velocities=return_velocities, species_list=species_list) def get_species_list_from_potcar(filename="POTCAR"):
64
64
147
14
50
SanderBorgmans/pyiron
pyiron/vasp/structure.py
Python
get_species_list_from_potcar
get_species_list_from_potcar
47
68
47
47
7840bb7f07586740ef60cf1fedc49fedf378c174
bigcode/the-stack
train
c576b35db80b48bf6b65ed2c
train
function
def vasp_sorter(structure): """ Routine to sort the indices of a structure as it would be when written to a POSCAR file Args: structure (pyiron.atomistics.structure.atoms.Atoms): The structure whose indices need to be sorted Returns: list: A list of indices which is sorted by the corre...
def vasp_sorter(structure):
""" Routine to sort the indices of a structure as it would be when written to a POSCAR file Args: structure (pyiron.atomistics.structure.atoms.Atoms): The structure whose indices need to be sorted Returns: list: A list of indices which is sorted by the corresponding species for writing...
: elements_new.append(e) elements = elements_new if is_absolute: atoms = Atoms(elements, positions=positions, cell=cell) else: atoms = Atoms(elements, scaled_positions=positions, cell=cell) return atoms def vasp_sorter(structure):
64
64
131
8
55
SanderBorgmans/pyiron
pyiron/vasp/structure.py
Python
vasp_sorter
vasp_sorter
281
298
281
281
f8eb40c72ea0b06ab564638a514a14744b8136ec
bigcode/the-stack
train
528645789ad8e94e42afa0f1
train
function
def write_poscar(structure, filename="POSCAR", write_species=True, cartesian=True): """ Writes a POSCAR type file from a structure object Args: structure (pyiron.atomistics.structure.atoms.Atoms): The structure instance to be written to the POSCAR format filename (str): Output filename ...
def write_poscar(structure, filename="POSCAR", write_species=True, cartesian=True):
""" Writes a POSCAR type file from a structure object Args: structure (pyiron.atomistics.structure.atoms.Atoms): The structure instance to be written to the POSCAR format filename (str): Output filename write_species (bool): True if the species should be written to the file ...
_list_from_potcar(filename="POTCAR"): """ Generates the species list from a POTCAR type file Args: filename (str): Input filename Returns: list: A list of species symbols """ trigger = "VRHFIN =" species_list = list() with open(filename) as potcar_file: lines =...
164
164
549
20
143
SanderBorgmans/pyiron
pyiron/vasp/structure.py
Python
write_poscar
write_poscar
71
122
71
71
e2c7c3f57c697b2ab4205b334d9d2e23c8e37414
bigcode/the-stack
train
8f681b50b9a125129308beb2
train
function
def _dict_to_atoms(atoms_dict, species_list=None, read_from_first_line=False): """ Function to convert a generated dict into an structure object Args: atoms_dict (dict): Dictionary with the details (from string_to_atom) species_list (list/numpy.ndarray): List of species read_from_fi...
def _dict_to_atoms(atoms_dict, species_list=None, read_from_first_line=False):
""" Function to convert a generated dict into an structure object Args: atoms_dict (dict): Dictionary with the details (from string_to_atom) species_list (list/numpy.ndarray): List of species read_from_first_line (bool): True if we are to read the species information from the first ...
is_not_majority[i]: for key in np.argwhere(inverse == i).flatten(): atoms.selective_dynamics[int(key)] = val.tolist() if read_velocities: velocity_index = position_index + n_atoms + 1 for i in range(velocity_index, velocity_index + n_atoms): try: ...
177
177
591
19
157
SanderBorgmans/pyiron
pyiron/vasp/structure.py
Python
_dict_to_atoms
_dict_to_atoms
225
278
225
225
6142abc29578a2cba1f2caef460fad81c10598c6
bigcode/the-stack
train
ecb7f9822a9eb4a5ebd2bdc4
train
function
def generate_classification_csv(): # Generate a random binary classification problem. X, y = make_classification(n_samples=100000, n_features=100, n_informative=80, random_state=2018, n_classes=2) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=2018) X_tr...
def generate_classification_csv(): # Generate a random binary classification problem.
X, y = make_classification(n_samples=100000, n_features=100, n_informative=80, random_state=2018, n_classes=2) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=2018) X_train = pd.DataFrame(X_train) X_test = pd.DataFrame(X_test) y_train = pd.DataFrame(y_tr...
import numpy as np import pandas as pd import sklearn as sk from sklearn import datasets from sklearn.datasets import make_classification try: from sklearn.model_selection import train_test_split except ImportError: from sklearn.cross_validation import train_test_split def generate_classification_csv(): # G...
67
129
432
15
51
KaiminLai/tiny-machine-learning-system
generate_classification_dataset.py
Python
generate_classification_csv
generate_classification_csv
11
42
11
12
fe6fac1e73088f6fbb3c05a7166c19d5482b45e9
bigcode/the-stack
train
fd1f5c778bdadb3db7e40379
train
function
def Factory(settings, Model): if(type(settings) != KratosMultiphysics.Parameters): raise Exception("expected input shall be a Parameters object, encapsulating a json string") return AssignVectorByDirectionToConditionProcess(Model, settings["Parameters"])
def Factory(settings, Model):
if(type(settings) != KratosMultiphysics.Parameters): raise Exception("expected input shall be a Parameters object, encapsulating a json string") return AssignVectorByDirectionToConditionProcess(Model, settings["Parameters"])
import math import KratosMultiphysics def Factory(settings, Model):
16
64
52
6
9
AndreaVoltan/MyKratos7.0
kratos/python_scripts/assign_vector_by_direction_to_condition_process.py
Python
Factory
Factory
4
7
4
4
04282df14e4925679f369e11e0a4122e25e44187
bigcode/the-stack
train
05ae1e4559dea957bebceec2
train
class
class AssignVectorByDirectionToConditionProcess(KratosMultiphysics.Process): def __init__(self, Model, settings ): KratosMultiphysics.Process.__init__(self) default_settings = KratosMultiphysics.Parameters(""" { "help" : "This process sets a variable a ce...
class AssignVectorByDirectionToConditionProcess(KratosMultiphysics.Process):
def __init__(self, Model, settings ): KratosMultiphysics.Process.__init__(self) default_settings = KratosMultiphysics.Parameters(""" { "help" : "This process sets a variable a certain scalar value in a given direction, for all the conditions belonging to ...
import math import KratosMultiphysics def Factory(settings, Model): if(type(settings) != KratosMultiphysics.Parameters): raise Exception("expected input shall be a Parameters object, encapsulating a json string") return AssignVectorByDirectionToConditionProcess(Model, settings["Parameters"]) ## All th...
90
256
1,494
16
74
AndreaVoltan/MyKratos7.0
kratos/python_scripts/assign_vector_by_direction_to_condition_process.py
Python
AssignVectorByDirectionToConditionProcess
AssignVectorByDirectionToConditionProcess
10
133
10
10
0f1465f28c4b6b436490de53ede02fc365c9e845
bigcode/the-stack
train