body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
3d71bad23c2619718cb2487e16a7a3ff975b3ff540e85883b849e0ca35cfb9bd | def fetch_ongoing_operation_id(self, publisher_id: str, offer_id: str, transport_dest: AzmpTransportDest):
'Fetches the id of an ongoing Azure Marketplace transport operation to a certain transport destination.'
response = self._request(url=self._api_url(publisher_id, 'offers', offer_id, 'submissions'))
sel... | Fetches the id of an ongoing Azure Marketplace transport operation to a certain transport destination. | ci/glci/az.py | fetch_ongoing_operation_id | clyann/gardenlinux | 69 | python | def fetch_ongoing_operation_id(self, publisher_id: str, offer_id: str, transport_dest: AzmpTransportDest):
response = self._request(url=self._api_url(publisher_id, 'offers', offer_id, 'submissions'))
self._raise_for_status(response=response, message='Could not fetch Azure Marketplace transport operations f... | def fetch_ongoing_operation_id(self, publisher_id: str, offer_id: str, transport_dest: AzmpTransportDest):
response = self._request(url=self._api_url(publisher_id, 'offers', offer_id, 'submissions'))
self._raise_for_status(response=response, message='Could not fetch Azure Marketplace transport operations f... |
93d27fe4f125a17b0d851aa9df65e01517bcf0b2d9e5b0f0c7f50b59748e6aa5 | def fetch_operation_state(self, publisher_id: str, offer_id: str, operation_id: str):
'Fetches the state of a given Azure Marketplace transport operation.'
response = self._request(url=self._api_url(publisher_id, 'offers', offer_id, 'operations', operation_id))
self._raise_for_status(response=response, mess... | Fetches the state of a given Azure Marketplace transport operation. | ci/glci/az.py | fetch_operation_state | clyann/gardenlinux | 69 | python | def fetch_operation_state(self, publisher_id: str, offer_id: str, operation_id: str):
response = self._request(url=self._api_url(publisher_id, 'offers', offer_id, 'operations', operation_id))
self._raise_for_status(response=response, message=f"Can't fetch state for transport operation {operation_id}")
... | def fetch_operation_state(self, publisher_id: str, offer_id: str, operation_id: str):
response = self._request(url=self._api_url(publisher_id, 'offers', offer_id, 'operations', operation_id))
self._raise_for_status(response=response, message=f"Can't fetch state for transport operation {operation_id}")
... |
6e7d5cdea513824efbecbe29a2481e0e7c426a3ebef10c99f719a6d36d863666 | def go_live(self, publisher_id: str, offer_id: str):
'Trigger a go live operation to transport an Azure Marketplace offer to production.'
response = self._request(method='POST', url=self._api_url(publisher_id, 'offers', offer_id, 'golive'))
self._raise_for_status(response=response, message='Go live of updat... | Trigger a go live operation to transport an Azure Marketplace offer to production. | ci/glci/az.py | go_live | clyann/gardenlinux | 69 | python | def go_live(self, publisher_id: str, offer_id: str):
response = self._request(method='POST', url=self._api_url(publisher_id, 'offers', offer_id, 'golive'))
self._raise_for_status(response=response, message='Go live of updated gardenlinux Azure Marketplace offer failed') | def go_live(self, publisher_id: str, offer_id: str):
response = self._request(method='POST', url=self._api_url(publisher_id, 'offers', offer_id, 'golive'))
self._raise_for_status(response=response, message='Go live of updated gardenlinux Azure Marketplace offer failed')<|docstring|>Trigger a go live operat... |
0ab53d7f3b8d37eb6c80ebe723cb43108f5633c426129a8ba7c2489185d424b7 | def image_upload_url(recipe_id):
'Return URL for recipe image upload'
return reverse('recipe:recipe-upload-image', args=[recipe_id]) | Return URL for recipe image upload | src/recipe/test/test_recipe_api.py | image_upload_url | devw4lL/recipe-app-api | 0 | python | def image_upload_url(recipe_id):
return reverse('recipe:recipe-upload-image', args=[recipe_id]) | def image_upload_url(recipe_id):
return reverse('recipe:recipe-upload-image', args=[recipe_id])<|docstring|>Return URL for recipe image upload<|endoftext|> |
398a9c6190156fc555b42f8aeed1a6f8eace09d935ca380418cfbb2a47f04a43 | def detail_url(recipe_id):
'Return recipe detail url'
return reverse('recipe:recipe-detail', args=[recipe_id]) | Return recipe detail url | src/recipe/test/test_recipe_api.py | detail_url | devw4lL/recipe-app-api | 0 | python | def detail_url(recipe_id):
return reverse('recipe:recipe-detail', args=[recipe_id]) | def detail_url(recipe_id):
return reverse('recipe:recipe-detail', args=[recipe_id])<|docstring|>Return recipe detail url<|endoftext|> |
0d9226ae8962fb7606071e260d3e99a76a21b3c3c949c4da57087bd4a9f23c70 | def sample_tag(user, name='Main course'):
'Create end return a sample tag'
return Tag.objects.create(user=user, name=name) | Create end return a sample tag | src/recipe/test/test_recipe_api.py | sample_tag | devw4lL/recipe-app-api | 0 | python | def sample_tag(user, name='Main course'):
return Tag.objects.create(user=user, name=name) | def sample_tag(user, name='Main course'):
return Tag.objects.create(user=user, name=name)<|docstring|>Create end return a sample tag<|endoftext|> |
b18ec5908d6fdcd110b98f8b5c95908a51deda738a174eca42230260c8ea1a8b | def sample_ingredient(user, name='Cinnamon'):
'Create and return a sample ingredient'
return Ingredient.objects.create(user=user, name=name) | Create and return a sample ingredient | src/recipe/test/test_recipe_api.py | sample_ingredient | devw4lL/recipe-app-api | 0 | python | def sample_ingredient(user, name='Cinnamon'):
return Ingredient.objects.create(user=user, name=name) | def sample_ingredient(user, name='Cinnamon'):
return Ingredient.objects.create(user=user, name=name)<|docstring|>Create and return a sample ingredient<|endoftext|> |
8fa8f1faafde2c910c642de7dd84c67725da561ce75cbe077b18adff79a8f840 | def sample_recipe(user, **params):
'Create and return a sample recipe'
defaults = {'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.0}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults) | Create and return a sample recipe | src/recipe/test/test_recipe_api.py | sample_recipe | devw4lL/recipe-app-api | 0 | python | def sample_recipe(user, **params):
defaults = {'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.0}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults) | def sample_recipe(user, **params):
defaults = {'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.0}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults)<|docstring|>Create and return a sample recipe<|endoftext|> |
187662e75f1ba2e27e68e946e1dc90e72193841c7a8096e76c87cd3c4d5a085d | def test_auth_required(self):
'Test that authentication is required'
res = self.client.get(RECIPE_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | Test that authentication is required | src/recipe/test/test_recipe_api.py | test_auth_required | devw4lL/recipe-app-api | 0 | python | def test_auth_required(self):
res = self.client.get(RECIPE_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | def test_auth_required(self):
res = self.client.get(RECIPE_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)<|docstring|>Test that authentication is required<|endoftext|> |
e7101bcab2f5f89d25594811c2dd7c484f1b8914624d65ca3123532c73d75cb8 | def test_retrieve_recipes(self):
'Test retrieving a list of recipes'
sample_recipe(user=self.user)
sample_recipe(user=self.user)
res = self.client.get(RECIPE_URL)
recipes = Recipe.objects.all().order_by('id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code,... | Test retrieving a list of recipes | src/recipe/test/test_recipe_api.py | test_retrieve_recipes | devw4lL/recipe-app-api | 0 | python | def test_retrieve_recipes(self):
sample_recipe(user=self.user)
sample_recipe(user=self.user)
res = self.client.get(RECIPE_URL)
recipes = Recipe.objects.all().order_by('id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.asser... | def test_retrieve_recipes(self):
sample_recipe(user=self.user)
sample_recipe(user=self.user)
res = self.client.get(RECIPE_URL)
recipes = Recipe.objects.all().order_by('id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.asser... |
e174408bf00070822010e10369e42d5165cfe0048a77fa2b73e2d143abbc54f2 | def test_recipes_limited_to_user(self):
'Test retrieving recipes for user'
user2 = get_user_model().objects.create_user(email='example@example.com', password='Testingpassword123')
sample_recipe(user=user2)
sample_recipe(user=self.user)
res = self.client.get(RECIPE_URL)
recipes = Recipe.objects.f... | Test retrieving recipes for user | src/recipe/test/test_recipe_api.py | test_recipes_limited_to_user | devw4lL/recipe-app-api | 0 | python | def test_recipes_limited_to_user(self):
user2 = get_user_model().objects.create_user(email='example@example.com', password='Testingpassword123')
sample_recipe(user=user2)
sample_recipe(user=self.user)
res = self.client.get(RECIPE_URL)
recipes = Recipe.objects.filter(user=self.user)
serializ... | def test_recipes_limited_to_user(self):
user2 = get_user_model().objects.create_user(email='example@example.com', password='Testingpassword123')
sample_recipe(user=user2)
sample_recipe(user=self.user)
res = self.client.get(RECIPE_URL)
recipes = Recipe.objects.filter(user=self.user)
serializ... |
c0b17a8de2e018f1b082d4d135c146c10e28a36317ce42bd903985e4031f4fbd | def test_view_recipe_detail(self):
'Test viewing a recipe detail'
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
url = detail_url(recipe.id)
res = self.client.get(url)
serializer = RecipeDetailSeria... | Test viewing a recipe detail | src/recipe/test/test_recipe_api.py | test_view_recipe_detail | devw4lL/recipe-app-api | 0 | python | def test_view_recipe_detail(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
url = detail_url(recipe.id)
res = self.client.get(url)
serializer = RecipeDetailSerializer(recipe)
self.assertE... | def test_view_recipe_detail(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
url = detail_url(recipe.id)
res = self.client.get(url)
serializer = RecipeDetailSerializer(recipe)
self.assertE... |
4a700f422ff1b52fcdf61ff487804129aef1882b29272ad2ba4be697b3870ce3 | def test_create_basic_recipe(self):
'Test creating recipe'
payload = {'title': 'Chocolate Cheesecake', 'time_minutes': 30, 'price': 5.0}
res = self.client.post(RECIPE_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
for key i... | Test creating recipe | src/recipe/test/test_recipe_api.py | test_create_basic_recipe | devw4lL/recipe-app-api | 0 | python | def test_create_basic_recipe(self):
payload = {'title': 'Chocolate Cheesecake', 'time_minutes': 30, 'price': 5.0}
res = self.client.post(RECIPE_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
for key in payload.keys():
... | def test_create_basic_recipe(self):
payload = {'title': 'Chocolate Cheesecake', 'time_minutes': 30, 'price': 5.0}
res = self.client.post(RECIPE_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
for key in payload.keys():
... |
3767e010af352dc22744f216cbe7fc03e83dab4fe8693de5ab6ba0465e5bc8b7 | def test_create_recipe_with_tag(self):
'test creating a recipe with tags'
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Dessert')
payload = {'title': 'Avocado lime cheesecake', 'tags': [tag1.id, tag2.id], 'time_minutes': 60, 'price': 20.0}
res = self.client.... | test creating a recipe with tags | src/recipe/test/test_recipe_api.py | test_create_recipe_with_tag | devw4lL/recipe-app-api | 0 | python | def test_create_recipe_with_tag(self):
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Dessert')
payload = {'title': 'Avocado lime cheesecake', 'tags': [tag1.id, tag2.id], 'time_minutes': 60, 'price': 20.0}
res = self.client.post(RECIPE_URL, payload)
self... | def test_create_recipe_with_tag(self):
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Dessert')
payload = {'title': 'Avocado lime cheesecake', 'tags': [tag1.id, tag2.id], 'time_minutes': 60, 'price': 20.0}
res = self.client.post(RECIPE_URL, payload)
self... |
e95786a19be0cb12ff3a90c0410754220b1f956bc2e4b37a22c4883e3c944616 | def test_create_recipe_with_ingredients(self):
'Test creating recipe with ingredients'
ingredients1 = sample_ingredient(user=self.user, name='Prawns')
ingredients2 = sample_ingredient(user=self.user, name='Ginger')
payload = {'title': 'Thai prawn red curry', 'ingredients': [ingredients1.id, ingredients2... | Test creating recipe with ingredients | src/recipe/test/test_recipe_api.py | test_create_recipe_with_ingredients | devw4lL/recipe-app-api | 0 | python | def test_create_recipe_with_ingredients(self):
ingredients1 = sample_ingredient(user=self.user, name='Prawns')
ingredients2 = sample_ingredient(user=self.user, name='Ginger')
payload = {'title': 'Thai prawn red curry', 'ingredients': [ingredients1.id, ingredients2.id], 'time_minutes': 20, 'price': 7.0}... | def test_create_recipe_with_ingredients(self):
ingredients1 = sample_ingredient(user=self.user, name='Prawns')
ingredients2 = sample_ingredient(user=self.user, name='Ginger')
payload = {'title': 'Thai prawn red curry', 'ingredients': [ingredients1.id, ingredients2.id], 'time_minutes': 20, 'price': 7.0}... |
ceb7bb5308b2fdc4ac618cd2ad98cf189b6d607741802fd91347a921a84166d4 | def test_partial_update_recipe(self):
'Test updating a recipe with patch'
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tags = sample_tag(user=self.user, name='Curry')
payload = {'title': 'Chicken Tikka', 'tags': [new_tags.id]}
url = detail_url(recipe.id)... | Test updating a recipe with patch | src/recipe/test/test_recipe_api.py | test_partial_update_recipe | devw4lL/recipe-app-api | 0 | python | def test_partial_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tags = sample_tag(user=self.user, name='Curry')
payload = {'title': 'Chicken Tikka', 'tags': [new_tags.id]}
url = detail_url(recipe.id)
self.client.patch(url, payload... | def test_partial_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tags = sample_tag(user=self.user, name='Curry')
payload = {'title': 'Chicken Tikka', 'tags': [new_tags.id]}
url = detail_url(recipe.id)
self.client.patch(url, payload... |
cb70d0cbdcf5926e8a17428863e4c23af1c940434eb3e15a555e9b5a7439c5f9 | def test_full_update_recipe(self):
'Test updating a recipe with put'
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
payload = {'title': 'Spaghetti carbonara', 'time_minutes': 25, 'price': 5.0}
url = detail_url(recipe.id)
self.client.put(url, payload)
recip... | Test updating a recipe with put | src/recipe/test/test_recipe_api.py | test_full_update_recipe | devw4lL/recipe-app-api | 0 | python | def test_full_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
payload = {'title': 'Spaghetti carbonara', 'time_minutes': 25, 'price': 5.0}
url = detail_url(recipe.id)
self.client.put(url, payload)
recipe.refresh_from_db()
self.asse... | def test_full_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
payload = {'title': 'Spaghetti carbonara', 'time_minutes': 25, 'price': 5.0}
url = detail_url(recipe.id)
self.client.put(url, payload)
recipe.refresh_from_db()
self.asse... |
cf9bbb8f672cb65e128e02fda336e27b9588c35a19fedf217f77360411945eff | def test_upload_image_to_recipe(self):
'Test uploading an image to recipe'
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'im... | Test uploading an image to recipe | src/recipe/test/test_recipe_api.py | test_upload_image_to_recipe | devw4lL/recipe-app-api | 0 | python | def test_upload_image_to_recipe(self):
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multipart')
... | def test_upload_image_to_recipe(self):
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multipart')
... |
f14d7690c48e639193539189b6f6dbd92590fa302acba8465aced65084426659 | def test_upload_image_bad_request(self):
'Test uploading an invalid image'
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test uploading an invalid image | src/recipe/test/test_recipe_api.py | test_upload_image_bad_request | devw4lL/recipe-app-api | 0 | python | def test_upload_image_bad_request(self):
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_upload_image_bad_request(self):
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test uploading an invalid image<|endoftext|> |
0dc41b9e72f29b771c4a3f8f0b45c375c276275bd3983cb0b6e8c28152cb1ce3 | def test_filter_recipe_by_tags(self):
'Test returning recipe with specific tags'
recipe_1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe_2 = sample_recipe(user=self.user, title='Aubergine with tahini')
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.... | Test returning recipe with specific tags | src/recipe/test/test_recipe_api.py | test_filter_recipe_by_tags | devw4lL/recipe-app-api | 0 | python | def test_filter_recipe_by_tags(self):
recipe_1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe_2 = sample_recipe(user=self.user, title='Aubergine with tahini')
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Vegetarian')
recipe_1.tags... | def test_filter_recipe_by_tags(self):
recipe_1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe_2 = sample_recipe(user=self.user, title='Aubergine with tahini')
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Vegetarian')
recipe_1.tags... |
aac40bca40efc879a8adba54d8df73ca7dfb1f6995c5ba7b9f818356a16fdfe1 | def test_filter_recipe_by_ingredients(self):
'Test returning recipes with specific ingredients'
recipe_1 = sample_recipe(user=self.user, title='Posh beans on toast')
recipe_2 = sample_recipe(user=self.user, title='Chicken cacciatore')
ingredient_1 = sample_ingredient(user=self.user, name='Feta cheese')
... | Test returning recipes with specific ingredients | src/recipe/test/test_recipe_api.py | test_filter_recipe_by_ingredients | devw4lL/recipe-app-api | 0 | python | def test_filter_recipe_by_ingredients(self):
recipe_1 = sample_recipe(user=self.user, title='Posh beans on toast')
recipe_2 = sample_recipe(user=self.user, title='Chicken cacciatore')
ingredient_1 = sample_ingredient(user=self.user, name='Feta cheese')
ingredient_2 = sample_ingredient(user=self.use... | def test_filter_recipe_by_ingredients(self):
recipe_1 = sample_recipe(user=self.user, title='Posh beans on toast')
recipe_2 = sample_recipe(user=self.user, title='Chicken cacciatore')
ingredient_1 = sample_ingredient(user=self.user, name='Feta cheese')
ingredient_2 = sample_ingredient(user=self.use... |
4b3b02268d62c8faba5a660f4edae2ec9778133f7aae18895b205480613ee23a | def load_data(database_filepath):
' Load dataset from SQLite database and split it into X (messages) and Y (category labels)\n \n Args:\n database_filepath (str): Path to the SQLite database\n\n Returns:\n X (ndarray): An array of text messages\n Y (ndarray): A two-dimensional array o... | Load dataset from SQLite database and split it into X (messages) and Y (category labels)
Args:
database_filepath (str): Path to the SQLite database
Returns:
X (ndarray): An array of text messages
Y (ndarray): A two-dimensional array of category labels
category_names: A list of category names | models/train_classifier.py | load_data | KCKhoo/disaster_response_dashboard | 0 | python | def load_data(database_filepath):
' Load dataset from SQLite database and split it into X (messages) and Y (category labels)\n \n Args:\n database_filepath (str): Path to the SQLite database\n\n Returns:\n X (ndarray): An array of text messages\n Y (ndarray): A two-dimensional array o... | def load_data(database_filepath):
' Load dataset from SQLite database and split it into X (messages) and Y (category labels)\n \n Args:\n database_filepath (str): Path to the SQLite database\n\n Returns:\n X (ndarray): An array of text messages\n Y (ndarray): A two-dimensional array o... |
1fba30666315259a32ad4669db5c6f78d756f2877c2bef6e8b0974c8761e5464 | def tokenize(text):
'\n Return a list of tokens after removing punctuation from text, followed by \n applying normalization, tokenization and lemmatization, and removing stopwords\n\n Args:\n text (str): A string literal \n\n Returns:\n tokens (list): A list of tokens\n '
text = re.... | Return a list of tokens after removing punctuation from text, followed by
applying normalization, tokenization and lemmatization, and removing stopwords
Args:
text (str): A string literal
Returns:
tokens (list): A list of tokens | models/train_classifier.py | tokenize | KCKhoo/disaster_response_dashboard | 0 | python | def tokenize(text):
'\n Return a list of tokens after removing punctuation from text, followed by \n applying normalization, tokenization and lemmatization, and removing stopwords\n\n Args:\n text (str): A string literal \n\n Returns:\n tokens (list): A list of tokens\n '
text = re.... | def tokenize(text):
'\n Return a list of tokens after removing punctuation from text, followed by \n applying normalization, tokenization and lemmatization, and removing stopwords\n\n Args:\n text (str): A string literal \n\n Returns:\n tokens (list): A list of tokens\n '
text = re.... |
505d1ebd28133e60ffa38f9740205f575a4c571d8f73c73902ead63052363e01 | def build_model():
'\n Return a machine learning pipeline that contains all the preprocessing steps and a\n multi-output classifier for training and testing. For training, hyperparameters\n tuning is also performed using grid search with cross validation\n \n Args:\n None\n\n Returns:\n ... | Return a machine learning pipeline that contains all the preprocessing steps and a
multi-output classifier for training and testing. For training, hyperparameters
tuning is also performed using grid search with cross validation
Args:
None
Returns:
cv: A machine learning pipeline for training and testing | models/train_classifier.py | build_model | KCKhoo/disaster_response_dashboard | 0 | python | def build_model():
'\n Return a machine learning pipeline that contains all the preprocessing steps and a\n multi-output classifier for training and testing. For training, hyperparameters\n tuning is also performed using grid search with cross validation\n \n Args:\n None\n\n Returns:\n ... | def build_model():
'\n Return a machine learning pipeline that contains all the preprocessing steps and a\n multi-output classifier for training and testing. For training, hyperparameters\n tuning is also performed using grid search with cross validation\n \n Args:\n None\n\n Returns:\n ... |
d2be741281abad77aba996e53ba8de47c85d501c2c1e94d4fe4786b847e95ed4 | def evaluate_model(model, X_test, Y_test, category_names):
' Evaluate model with F1 score, precision and recall\n \n Args:\n model: Trained machine learning model\n X_test (ndarray): An array of text messages\n Y_test (ndarray): A two-dimensional array of category labels\n category... | Evaluate model with F1 score, precision and recall
Args:
model: Trained machine learning model
X_test (ndarray): An array of text messages
Y_test (ndarray): A two-dimensional array of category labels
category_names: A list of category names
Returns:
None | models/train_classifier.py | evaluate_model | KCKhoo/disaster_response_dashboard | 0 | python | def evaluate_model(model, X_test, Y_test, category_names):
' Evaluate model with F1 score, precision and recall\n \n Args:\n model: Trained machine learning model\n X_test (ndarray): An array of text messages\n Y_test (ndarray): A two-dimensional array of category labels\n category... | def evaluate_model(model, X_test, Y_test, category_names):
' Evaluate model with F1 score, precision and recall\n \n Args:\n model: Trained machine learning model\n X_test (ndarray): An array of text messages\n Y_test (ndarray): A two-dimensional array of category labels\n category... |
d999e4b2ea542c7474fefb158f8e2a248963b32d88b7f3c42f9f084c143d733a | def save_model(model, model_filepath):
' Save final model as a pickle file\n \n Args:\n model: Final machine learning model with the best performance\n model_filepath (string) : Path at which the final model will be stored \n\n Returns:\n None\n '
joblib.dump(model, model_filepat... | Save final model as a pickle file
Args:
model: Final machine learning model with the best performance
model_filepath (string) : Path at which the final model will be stored
Returns:
None | models/train_classifier.py | save_model | KCKhoo/disaster_response_dashboard | 0 | python | def save_model(model, model_filepath):
' Save final model as a pickle file\n \n Args:\n model: Final machine learning model with the best performance\n model_filepath (string) : Path at which the final model will be stored \n\n Returns:\n None\n '
joblib.dump(model, model_filepat... | def save_model(model, model_filepath):
' Save final model as a pickle file\n \n Args:\n model: Final machine learning model with the best performance\n model_filepath (string) : Path at which the final model will be stored \n\n Returns:\n None\n '
joblib.dump(model, model_filepat... |
998389ec42c5498d762a430707d8839840c9ddc66ddc4b3b48392bd85162ece6 | def test_source_and_target_path(self):
'Test source and target path methods for input file handle.'
fh = FileHandle(filepath='/home/user/files/myfile.txt')
f = InputFile(f_handle=fh)
assert (f.source() == '/home/user/files/myfile.txt')
assert (f.target() == 'myfile.txt')
f = InputFile(f_handle=f... | Test source and target path methods for input file handle. | tests/filestore/test_input_file.py | test_source_and_target_path | scailfin/benchmark-templates | 0 | python | def test_source_and_target_path(self):
fh = FileHandle(filepath='/home/user/files/myfile.txt')
f = InputFile(f_handle=fh)
assert (f.source() == '/home/user/files/myfile.txt')
assert (f.target() == 'myfile.txt')
f = InputFile(f_handle=fh, target_path='data/names.txt')
assert (f.source() == '... | def test_source_and_target_path(self):
fh = FileHandle(filepath='/home/user/files/myfile.txt')
f = InputFile(f_handle=fh)
assert (f.source() == '/home/user/files/myfile.txt')
assert (f.target() == 'myfile.txt')
f = InputFile(f_handle=fh, target_path='data/names.txt')
assert (f.source() == '... |
cbc9db6e97a4249663894594299f66e7d621938ed341eeaa3e1be1100da36502 | def _test_application(self):
'Create a test application object. We must load \n dynamically as it depends on the adbapi intialisation'
return Application(appeui=int('0x0A0B0C0D0A0B0C0D', 16), name='app', domain='fluentnetworks.com.au', appnonce=int('0xC28AE9', 16), appkey=int('0x017E151638AEC2A6ABF725880... | Create a test application object. We must load
dynamically as it depends on the adbapi intialisation | floranet/test/unit/web/test_restapplication.py | _test_application | chengzhongkai/floranet | 40 | python | def _test_application(self):
'Create a test application object. We must load \n dynamically as it depends on the adbapi intialisation'
return Application(appeui=int('0x0A0B0C0D0A0B0C0D', 16), name='app', domain='fluentnetworks.com.au', appnonce=int('0xC28AE9', 16), appkey=int('0x017E151638AEC2A6ABF725880... | def _test_application(self):
'Create a test application object. We must load \n dynamically as it depends on the adbapi intialisation'
return Application(appeui=int('0x0A0B0C0D0A0B0C0D', 16), name='app', domain='fluentnetworks.com.au', appnonce=int('0xC28AE9', 16), appkey=int('0x017E151638AEC2A6ABF725880... |
ed747c6df0dee019503fa063afa3bbd142f65a940f4dd12a1875d94f85a7e0ca | @inlineCallbacks
def test_get(self):
'Test get method'
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Application, 'find', class... | Test get method | floranet/test/unit/web/test_restapplication.py | test_get | chengzhongkai/floranet | 40 | python | @inlineCallbacks
def test_get(self):
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Application, 'find', classmethod(mockDBObje... | @inlineCallbacks
def test_get(self):
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Application, 'find', classmethod(mockDBObje... |
1bb6d08c1000479084f51236e3437f77ed312066387d034685beed6eaeb8dc69 | @inlineCallbacks
def test_put(self):
'Test put method'
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Application, 'find', class... | Test put method | floranet/test/unit/web/test_restapplication.py | test_put | chengzhongkai/floranet | 40 | python | @inlineCallbacks
def test_put(self):
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Application, 'find', classmethod(mockDBObje... | @inlineCallbacks
def test_put(self):
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Application, 'find', classmethod(mockDBObje... |
39c4333c8318e5d63aef79736ff88fae054faef79dac43b79d549b908aefd7f2 | @inlineCallbacks
def test_delete(self):
'Test delete method'
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Device, 'find', clas... | Test delete method | floranet/test/unit/web/test_restapplication.py | test_delete | chengzhongkai/floranet | 40 | python | @inlineCallbacks
def test_delete(self):
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Device, 'find', classmethod(mockDBObject... | @inlineCallbacks
def test_delete(self):
app = self._test_application()
mockDBObject.return_value = app
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplication(restapi=self.restapi, server=self.server)
with patch.object(Device, 'find', classmethod(mockDBObject... |
cbc9db6e97a4249663894594299f66e7d621938ed341eeaa3e1be1100da36502 | def _test_application(self):
'Create a test application object. We must load \n dynamically as it depends on the adbapi intialisation'
return Application(appeui=int('0x0A0B0C0D0A0B0C0D', 16), name='app', domain='fluentnetworks.com.au', appnonce=int('0xC28AE9', 16), appkey=int('0x017E151638AEC2A6ABF725880... | Create a test application object. We must load
dynamically as it depends on the adbapi intialisation | floranet/test/unit/web/test_restapplication.py | _test_application | chengzhongkai/floranet | 40 | python | def _test_application(self):
'Create a test application object. We must load \n dynamically as it depends on the adbapi intialisation'
return Application(appeui=int('0x0A0B0C0D0A0B0C0D', 16), name='app', domain='fluentnetworks.com.au', appnonce=int('0xC28AE9', 16), appkey=int('0x017E151638AEC2A6ABF725880... | def _test_application(self):
'Create a test application object. We must load \n dynamically as it depends on the adbapi intialisation'
return Application(appeui=int('0x0A0B0C0D0A0B0C0D', 16), name='app', domain='fluentnetworks.com.au', appnonce=int('0xC28AE9', 16), appkey=int('0x017E151638AEC2A6ABF725880... |
7314440cde5976b5f196e6fa82caab09125a233daca4f8dfc945d0f8b5848bff | @inlineCallbacks
def test_get(self):
'Test get method'
app = self._test_application()
mockDBObject.return_value = [app, app]
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplications(restapi=self.restapi, server=self.server)
with patch.object(Application, 'all'... | Test get method | floranet/test/unit/web/test_restapplication.py | test_get | chengzhongkai/floranet | 40 | python | @inlineCallbacks
def test_get(self):
app = self._test_application()
mockDBObject.return_value = [app, app]
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplications(restapi=self.restapi, server=self.server)
with patch.object(Application, 'all', classmethod(moc... | @inlineCallbacks
def test_get(self):
app = self._test_application()
mockDBObject.return_value = [app, app]
with patch.object(reqparse.RequestParser, 'parse_args'):
resource = RestApplications(restapi=self.restapi, server=self.server)
with patch.object(Application, 'all', classmethod(moc... |
b70316d7ca83ab99b10bf115d5c8f6fc89c7dcafce1c93f04624cf44354a33ba | @inlineCallbacks
def test_post(self):
'Test post method'
app = self._test_application()
attrs = ['appeui', 'name', 'domain', 'appnonce', 'appkey', 'fport']
args = {'appinterface_id': 1}
for a in attrs:
args[a] = getattr(app, a)
with patch.object(reqparse.RequestParser, 'parse_args', Magi... | Test post method | floranet/test/unit/web/test_restapplication.py | test_post | chengzhongkai/floranet | 40 | python | @inlineCallbacks
def test_post(self):
app = self._test_application()
attrs = ['appeui', 'name', 'domain', 'appnonce', 'appkey', 'fport']
args = {'appinterface_id': 1}
for a in attrs:
args[a] = getattr(app, a)
with patch.object(reqparse.RequestParser, 'parse_args', MagicMock(return_value... | @inlineCallbacks
def test_post(self):
app = self._test_application()
attrs = ['appeui', 'name', 'domain', 'appnonce', 'appkey', 'fport']
args = {'appinterface_id': 1}
for a in attrs:
args[a] = getattr(app, a)
with patch.object(reqparse.RequestParser, 'parse_args', MagicMock(return_value... |
1c30be21d29b58ceca6cf9271aa81cbe00c4e36ae1eba7414a2e2cede726161c | def handle(method: str, path: str, optional_trail_slash=True):
'\n Register the URI handler.\n Use this as a function decorator.\n\n Example:\n ```python\n @bhh.handle("POST", "/api/foo/{var1}/bar")\n def some_api(hdlr, var1):\n # Do something...\n ```\n ... | Register the URI handler.
Use this as a function decorator.
Example:
```python
@bhh.handle("POST", "/api/foo/{var1}/bar")
def some_api(hdlr, var1):
# Do something...
``` | src/bhh.py | handle | jacky9813/bhh | 0 | python | def handle(method: str, path: str, optional_trail_slash=True):
'\n Register the URI handler.\n Use this as a function decorator.\n\n Example:\n ```python\n @bhh.handle("POST", "/api/foo/{var1}/bar")\n def some_api(hdlr, var1):\n # Do something...\n ```\n ... | def handle(method: str, path: str, optional_trail_slash=True):
'\n Register the URI handler.\n Use this as a function decorator.\n\n Example:\n ```python\n @bhh.handle("POST", "/api/foo/{var1}/bar")\n def some_api(hdlr, var1):\n # Do something...\n ```\n ... |
250fb531406b24f160e4ea8f77e67cb58a364015838f915af7589048bef6b324 | def register_handler(method: str, path: str, handler, optional_trail_slash=True):
'\n Register the URI handler.\n\n Example:\n ```python\n def some_api(hdlr, var1):\n # Do something...\n bhh.register_handler("POST", "/api/foo/{var1}/bar", some_api)\n ```\n '
... | Register the URI handler.
Example:
```python
def some_api(hdlr, var1):
# Do something...
bhh.register_handler("POST", "/api/foo/{var1}/bar", some_api)
``` | src/bhh.py | register_handler | jacky9813/bhh | 0 | python | def register_handler(method: str, path: str, handler, optional_trail_slash=True):
'\n Register the URI handler.\n\n Example:\n ```python\n def some_api(hdlr, var1):\n # Do something...\n bhh.register_handler("POST", "/api/foo/{var1}/bar", some_api)\n ```\n '
... | def register_handler(method: str, path: str, handler, optional_trail_slash=True):
'\n Register the URI handler.\n\n Example:\n ```python\n def some_api(hdlr, var1):\n # Do something...\n bhh.register_handler("POST", "/api/foo/{var1}/bar", some_api)\n ```\n '
... |
94466422dc8c7ccd4dfd3ef84b374bfa8808f1751040a58064f1a59055b48a3a | def address_string(self):
'\n Return "client IP:port"\n '
return f'{self.client_address[0]}:{self.client_address[1]}' | Return "client IP:port" | src/bhh.py | address_string | jacky9813/bhh | 0 | python | def address_string(self):
'\n \n '
return f'{self.client_address[0]}:{self.client_address[1]}' | def address_string(self):
'\n \n '
return f'{self.client_address[0]}:{self.client_address[1]}'<|docstring|>Return "client IP:port"<|endoftext|> |
4bda1d465d85f06f940f3437507305ecff4bfa54b63af03b63c0537292b60d14 | def send_response(self, code, message=None):
'Add the response header to the headers buffer and log the\n response code.\n\n Also send two standard headers with the server software\n version and the current date.\n\n '
self.log_request(code)
self.send_response_only(code, message) | Add the response header to the headers buffer and log the
response code.
Also send two standard headers with the server software
version and the current date. | src/bhh.py | send_response | jacky9813/bhh | 0 | python | def send_response(self, code, message=None):
'Add the response header to the headers buffer and log the\n response code.\n\n Also send two standard headers with the server software\n version and the current date.\n\n '
self.log_request(code)
self.send_response_only(code, message) | def send_response(self, code, message=None):
'Add the response header to the headers buffer and log the\n response code.\n\n Also send two standard headers with the server software\n version and the current date.\n\n '
self.log_request(code)
self.send_response_only(code, message)... |
e95eaaf2a78e6c08d2a5bdf139c34621bd0cf1b1991a2d5ca6a5b91e3afead33 | def handle_one_request(self):
"Handle a single HTTP request.\n\n You normally don't need to override this method; see the class\n __doc__ string for information on how to handle specific HTTP\n commands such as GET and POST.\n\n "
try:
self.raw_requestline = self.rfile.readli... | Handle a single HTTP request.
You normally don't need to override this method; see the class
__doc__ string for information on how to handle specific HTTP
commands such as GET and POST. | src/bhh.py | handle_one_request | jacky9813/bhh | 0 | python | def handle_one_request(self):
"Handle a single HTTP request.\n\n You normally don't need to override this method; see the class\n __doc__ string for information on how to handle specific HTTP\n commands such as GET and POST.\n\n "
try:
self.raw_requestline = self.rfile.readli... | def handle_one_request(self):
"Handle a single HTTP request.\n\n You normally don't need to override this method; see the class\n __doc__ string for information on how to handle specific HTTP\n commands such as GET and POST.\n\n "
try:
self.raw_requestline = self.rfile.readli... |
dd43c9a40f53c345a915abffb4a2842f52caf63df370083fe4d8ecf64e19bcba | def do_GET(self):
'\n Default GET handler for an URI.\n '
path = os.path.realpath((STATIC_PATH + self.path))
if (path[:len(STATIC_PATH)] != STATIC_PATH):
self.send_response(HTTPStatus.FORBIDDEN)
self.send_header('Content-Length', '0')
self.end_headers()
else:
... | Default GET handler for an URI. | src/bhh.py | do_GET | jacky9813/bhh | 0 | python | def do_GET(self):
'\n \n '
path = os.path.realpath((STATIC_PATH + self.path))
if (path[:len(STATIC_PATH)] != STATIC_PATH):
self.send_response(HTTPStatus.FORBIDDEN)
self.send_header('Content-Length', '0')
self.end_headers()
else:
fdesc = None
if os.pa... | def do_GET(self):
'\n \n '
path = os.path.realpath((STATIC_PATH + self.path))
if (path[:len(STATIC_PATH)] != STATIC_PATH):
self.send_response(HTTPStatus.FORBIDDEN)
self.send_header('Content-Length', '0')
self.end_headers()
else:
fdesc = None
if os.pa... |
672e4a5bc464d1e8666d70df0be45fd9ab85c5f4cf0dbd0eda1de05240ef8947 | def run(self):
'\n Display the menu and respond to choices.\n '
while True:
self.display_menu()
choice = input('Enter an option: ')
action = self.choices.get(choice)
if action:
action()
else:
print(f'{choice} is not a valid choice.') | Display the menu and respond to choices. | menu.py | run | Vihtoriaaa/Notebook | 1 | python | def run(self):
'\n \n '
while True:
self.display_menu()
choice = input('Enter an option: ')
action = self.choices.get(choice)
if action:
action()
else:
print(f'{choice} is not a valid choice.') | def run(self):
'\n \n '
while True:
self.display_menu()
choice = input('Enter an option: ')
action = self.choices.get(choice)
if action:
action()
else:
print(f'{choice} is not a valid choice.')<|docstring|>Display the menu and respond... |
f3ff994f4f6805e9d37a3c39250ff8e2a59e0e7df9af9d2fabb3f02d258451e3 | def run_nspawn(opts: _NspawnOpts, popen_args: PopenArgs, *, plugins: Iterable[NspawnPlugin]=()) -> Tuple[(subprocess.CompletedProcess, subprocess.CompletedProcess)]:
'\n The first `CompletedProcess` reflects for the user command `opts.cmd`\n that we `nsenter`ed into the `systemd-nspawn` container.\n\n The ... | The first `CompletedProcess` reflects for the user command `opts.cmd`
that we `nsenter`ed into the `systemd-nspawn` container.
The second one is for the nspawn process representing the container
console process itself. | antlir/nspawn_in_subvol/nspawn.py | run_nspawn | baioc/antlir | 28 | python | def run_nspawn(opts: _NspawnOpts, popen_args: PopenArgs, *, plugins: Iterable[NspawnPlugin]=()) -> Tuple[(subprocess.CompletedProcess, subprocess.CompletedProcess)]:
'\n The first `CompletedProcess` reflects for the user command `opts.cmd`\n that we `nsenter`ed into the `systemd-nspawn` container.\n\n The ... | def run_nspawn(opts: _NspawnOpts, popen_args: PopenArgs, *, plugins: Iterable[NspawnPlugin]=()) -> Tuple[(subprocess.CompletedProcess, subprocess.CompletedProcess)]:
'\n The first `CompletedProcess` reflects for the user command `opts.cmd`\n that we `nsenter`ed into the `systemd-nspawn` container.\n\n The ... |
bae3e1f9568f506365f452d70c4d07f335382e39df4763bed4c67884562c4b5a | @click.command()
@click.option('-d', '--data_config_file', default=None, type=click.Path(exists=True), help='path to yaml file containing data input and output parameters. See dask_data_config.yaml.template')
@click.option('-a', '--app_config_file', default='config.yaml', type=click.Path(exists=True), help='path to yam... | This module generates parquets with regional annotation pathology data
INPUT PARAMETERS
app_config_file - path to yaml file containing application runtime parameters. See config.yaml.template
data_config_file - path to yaml file containing data input and output parameters. See dask_data_config.yaml.template
TABLE S... | pyluna-pathology/luna/pathology/refined_table/regional_annotation/dask_generate.py | cli | msk-mind/data-processing | 1 | python | @click.command()
@click.option('-d', '--data_config_file', default=None, type=click.Path(exists=True), help='path to yaml file containing data input and output parameters. See dask_data_config.yaml.template')
@click.option('-a', '--app_config_file', default='config.yaml', type=click.Path(exists=True), help='path to yam... | @click.command()
@click.option('-d', '--data_config_file', default=None, type=click.Path(exists=True), help='path to yaml file containing data input and output parameters. See dask_data_config.yaml.template')
@click.option('-a', '--app_config_file', default='config.yaml', type=click.Path(exists=True), help='path to yam... |
42c5c7a24e3354d954966329fe7d47dec8c349a1f583330fa8be4ff14443a085 | def create_geojson_table():
'Vectorizes npy array annotation file into polygons and builds GeoJson with the polygon features.\n Creates a geojson file per labelset.\n Combines multiple annotations from different users for a slide.\n\n Returns:\n list: list of slide ids that failed\n '
logger ... | Vectorizes npy array annotation file into polygons and builds GeoJson with the polygon features.
Creates a geojson file per labelset.
Combines multiple annotations from different users for a slide.
Returns:
list: list of slide ids that failed | pyluna-pathology/luna/pathology/refined_table/regional_annotation/dask_generate.py | create_geojson_table | msk-mind/data-processing | 1 | python | def create_geojson_table():
'Vectorizes npy array annotation file into polygons and builds GeoJson with the polygon features.\n Creates a geojson file per labelset.\n Combines multiple annotations from different users for a slide.\n\n Returns:\n list: list of slide ids that failed\n '
logger ... | def create_geojson_table():
'Vectorizes npy array annotation file into polygons and builds GeoJson with the polygon features.\n Creates a geojson file per labelset.\n Combines multiple annotations from different users for a slide.\n\n Returns:\n list: list of slide ids that failed\n '
logger ... |
d950582ecde421e38cd147ac02761114ebd915b235190347c014bc983b8e166e | def __init__(self):
'Constructeur de la commande'
Parametre.__init__(self, 'apprendre', 'learn')
self.groupe = 'administrateur'
self.schema = '<nombre> <cle>'
self.aide_courte = 'apprend un sort'
self.aide_longue = "Cette commande force l'apprentissage d'un sort. Vous devez préciser en premier p... | Constructeur de la commande | src/secondaires/magie/commandes/sorts/apprendre.py | __init__ | vlegoff/tsunami | 14 | python | def __init__(self):
Parametre.__init__(self, 'apprendre', 'learn')
self.groupe = 'administrateur'
self.schema = '<nombre> <cle>'
self.aide_courte = 'apprend un sort'
self.aide_longue = "Cette commande force l'apprentissage d'un sort. Vous devez préciser en premier paramètre le nombre auquel vou... | def __init__(self):
Parametre.__init__(self, 'apprendre', 'learn')
self.groupe = 'administrateur'
self.schema = '<nombre> <cle>'
self.aide_courte = 'apprend un sort'
self.aide_longue = "Cette commande force l'apprentissage d'un sort. Vous devez préciser en premier paramètre le nombre auquel vou... |
60ad78f219ed073c8e747c53eb95b7a9a2623656034fe8e193ef0aaa145ca1ab | def ajouter(self):
"Méthode appelée lors de l'ajout de la commande à l'interpréteur"
nombre = self.noeud.get_masque('nombre')
nombre.proprietes['limite_inf'] = '0'
nombre.proprietes['limite_sup'] = '100' | Méthode appelée lors de l'ajout de la commande à l'interpréteur | src/secondaires/magie/commandes/sorts/apprendre.py | ajouter | vlegoff/tsunami | 14 | python | def ajouter(self):
nombre = self.noeud.get_masque('nombre')
nombre.proprietes['limite_inf'] = '0'
nombre.proprietes['limite_sup'] = '100' | def ajouter(self):
nombre = self.noeud.get_masque('nombre')
nombre.proprietes['limite_inf'] = '0'
nombre.proprietes['limite_sup'] = '100'<|docstring|>Méthode appelée lors de l'ajout de la commande à l'interpréteur<|endoftext|> |
02d587b5b85e780c6674e5b80aba185ced33e5b4159b18cfb828d3d84440e269 | def interpreter(self, personnage, dic_masques):
"Méthode d'interprétation de commande"
niveau = dic_masques['nombre'].nombre
if ((niveau < 0) or (niveau > 100)):
(personnage << '|err|Spécifiez un niveau de maîtrise entre 0 et 100.|ff|')
return
cle = dic_masques['cle'].cle
try:
... | Méthode d'interprétation de commande | src/secondaires/magie/commandes/sorts/apprendre.py | interpreter | vlegoff/tsunami | 14 | python | def interpreter(self, personnage, dic_masques):
niveau = dic_masques['nombre'].nombre
if ((niveau < 0) or (niveau > 100)):
(personnage << '|err|Spécifiez un niveau de maîtrise entre 0 et 100.|ff|')
return
cle = dic_masques['cle'].cle
try:
sort = importeur.magie.sorts[cle]
... | def interpreter(self, personnage, dic_masques):
niveau = dic_masques['nombre'].nombre
if ((niveau < 0) or (niveau > 100)):
(personnage << '|err|Spécifiez un niveau de maîtrise entre 0 et 100.|ff|')
return
cle = dic_masques['cle'].cle
try:
sort = importeur.magie.sorts[cle]
... |
824b74b8c2158a248686c246f7ff6fec7bed636c13f2a44668565315c4b976e4 | def deprecated(msg=''):
'Decorator factory to mark functions as deprecated with given message.\n\n >>> @deprecated("Enough!")\n ... def some_function():\n ... "I just print \'hello world\'."\n ... print("hello world")\n >>> some_function()\n hello world\n >>> some_function.__doc__ == "I j... | Decorator factory to mark functions as deprecated with given message.
>>> @deprecated("Enough!")
... def some_function():
... "I just print 'hello world'."
... print("hello world")
>>> some_function()
hello world
>>> some_function.__doc__ == "I just print 'hello world'."
True | Lib/fontTools/ufoLib/utils.py | deprecated | nyshadhr9/fonttools | 240 | python | def deprecated(msg=):
'Decorator factory to mark functions as deprecated with given message.\n\n >>> @deprecated("Enough!")\n ... def some_function():\n ... "I just print \'hello world\'."\n ... print("hello world")\n >>> some_function()\n hello world\n >>> some_function.__doc__ == "I jus... | def deprecated(msg=):
'Decorator factory to mark functions as deprecated with given message.\n\n >>> @deprecated("Enough!")\n ... def some_function():\n ... "I just print \'hello world\'."\n ... print("hello world")\n >>> some_function()\n hello world\n >>> some_function.__doc__ == "I jus... |
3e6a48f8e0aec2c806f79b8acf9c8cfbba1b09a6d6254f105bcad034d982c9be | def blur_pool(self, stride: int=2, overlap: int=1) -> nn.Module:
'Replacement (and generalization) for AvgPool2d(2, 2)'
kernel = self._get_k(stride, overlap)
padding = self._get_p(kernel, stride, 1)
return LazyBlurPool2d(kernel, stride, padding) | Replacement (and generalization) for AvgPool2d(2, 2) | glow/nn/modules/context.py | blur_pool | arquolo/ort | 0 | python | def blur_pool(self, stride: int=2, overlap: int=1) -> nn.Module:
kernel = self._get_k(stride, overlap)
padding = self._get_p(kernel, stride, 1)
return LazyBlurPool2d(kernel, stride, padding) | def blur_pool(self, stride: int=2, overlap: int=1) -> nn.Module:
kernel = self._get_k(stride, overlap)
padding = self._get_p(kernel, stride, 1)
return LazyBlurPool2d(kernel, stride, padding)<|docstring|>Replacement (and generalization) for AvgPool2d(2, 2)<|endoftext|> |
e4c852cce154eb0d2bbffcbcc70f7143c993ff108f4748f6c64860d321ae91c4 | def max_blur_pool(self, stride: int=2, overlap: int=1) -> nn.Module:
'\n Replacement for MaxPool2d(2, 2)\n Only for even inputs. When applied to odd inputs, loses 1 sample.\n '
assert self.even
return nn.Sequential(nn.MaxPool2d(2, 1), self._invert().blur_pool(stride, overlap)) | Replacement for MaxPool2d(2, 2)
Only for even inputs. When applied to odd inputs, loses 1 sample. | glow/nn/modules/context.py | max_blur_pool | arquolo/ort | 0 | python | def max_blur_pool(self, stride: int=2, overlap: int=1) -> nn.Module:
'\n Replacement for MaxPool2d(2, 2)\n Only for even inputs. When applied to odd inputs, loses 1 sample.\n '
assert self.even
return nn.Sequential(nn.MaxPool2d(2, 1), self._invert().blur_pool(stride, overlap)) | def max_blur_pool(self, stride: int=2, overlap: int=1) -> nn.Module:
'\n Replacement for MaxPool2d(2, 2)\n Only for even inputs. When applied to odd inputs, loses 1 sample.\n '
assert self.even
return nn.Sequential(nn.MaxPool2d(2, 1), self._invert().blur_pool(stride, overlap))<|docstrin... |
b5d16ee24ecca5d5b4cb3af617f82a1a1e55fb7bfbd73922f8fc3b11dbe390f1 | def conv_blur_pool(self, dim: int, stride: int=2, overlap: int=1) -> nn.Module:
'Replacement for [Conv2d(..., 3, 2, 1), norm, act]'
return nn.Sequential(self.conv(dim), self.norm(), self.activation(True), self.blur_pool(stride, overlap)) | Replacement for [Conv2d(..., 3, 2, 1), norm, act] | glow/nn/modules/context.py | conv_blur_pool | arquolo/ort | 0 | python | def conv_blur_pool(self, dim: int, stride: int=2, overlap: int=1) -> nn.Module:
return nn.Sequential(self.conv(dim), self.norm(), self.activation(True), self.blur_pool(stride, overlap)) | def conv_blur_pool(self, dim: int, stride: int=2, overlap: int=1) -> nn.Module:
return nn.Sequential(self.conv(dim), self.norm(), self.activation(True), self.blur_pool(stride, overlap))<|docstring|>Replacement for [Conv2d(..., 3, 2, 1), norm, act]<|endoftext|> |
dabeb213300bc49efae957c3018bde37aeba727654af68062def9f45dfd4c3e9 | def __init__(self, x_ref: Union[(np.ndarray, list)], ert: float, window_size: int, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None, n_bootstraps: int=1000, verbose: bool=True, input_shape: Optional[tuple]=None, data_type: Optional[str]=None) -> None:
"\n ... | Online maximum Mean Discrepancy (MMD) data drift detector using preconfigured thresholds.
Parameters
----------
x_ref
Data used as reference distribution.
ert
The expected run-time (ERT) in the absence of drift. For the multivariate detectors, the ERT is defined
as the expected run-time from t=0.
window_si... | alibi_detect/cd/tensorflow/mmd_online.py | __init__ | vishalbelsare/alibi-detect | 1,227 | python | def __init__(self, x_ref: Union[(np.ndarray, list)], ert: float, window_size: int, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None, n_bootstraps: int=1000, verbose: bool=True, input_shape: Optional[tuple]=None, data_type: Optional[str]=None) -> None:
"\n ... | def __init__(self, x_ref: Union[(np.ndarray, list)], ert: float, window_size: int, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None, n_bootstraps: int=1000, verbose: bool=True, input_shape: Optional[tuple]=None, data_type: Optional[str]=None) -> None:
"\n ... |
e11a26c7a8dc257b828dc2d5c855ebadf550794bb944c7dba4333d898096c96b | def score(self, x_t: Union[(np.ndarray, Any)]) -> float:
'\n Compute the test-statistic (squared MMD) between the reference window and test window.\n\n Parameters\n ----------\n x_t\n A single instance to be added to the test-window.\n\n Returns\n -------\n ... | Compute the test-statistic (squared MMD) between the reference window and test window.
Parameters
----------
x_t
A single instance to be added to the test-window.
Returns
-------
Squared MMD estimate between reference window and test window. | alibi_detect/cd/tensorflow/mmd_online.py | score | vishalbelsare/alibi-detect | 1,227 | python | def score(self, x_t: Union[(np.ndarray, Any)]) -> float:
'\n Compute the test-statistic (squared MMD) between the reference window and test window.\n\n Parameters\n ----------\n x_t\n A single instance to be added to the test-window.\n\n Returns\n -------\n ... | def score(self, x_t: Union[(np.ndarray, Any)]) -> float:
'\n Compute the test-statistic (squared MMD) between the reference window and test window.\n\n Parameters\n ----------\n x_t\n A single instance to be added to the test-window.\n\n Returns\n -------\n ... |
464dffd26bfb0f79ab1cdf385c2df440dc9a688d94b09823d20ffe1759eb9580 | def from_code(code):
'\n Return the specific exception class for the given code, or\n OpenproviderError if no specific exception class is available.\n\n @param code: The error code from Openprovider.\n '
if (code in MAPPING):
return MAPPING[code]
else:
return OpenproviderError | Return the specific exception class for the given code, or
OpenproviderError if no specific exception class is available.
@param code: The error code from Openprovider. | openprovider/data/exception_map.py | from_code | danielterhorst/openprovider.py | 11 | python | def from_code(code):
'\n Return the specific exception class for the given code, or\n OpenproviderError if no specific exception class is available.\n\n @param code: The error code from Openprovider.\n '
if (code in MAPPING):
return MAPPING[code]
else:
return OpenproviderError | def from_code(code):
'\n Return the specific exception class for the given code, or\n OpenproviderError if no specific exception class is available.\n\n @param code: The error code from Openprovider.\n '
if (code in MAPPING):
return MAPPING[code]
else:
return OpenproviderError<|d... |
c5c8b7bebe2003106d31cc678e83e0f6d41e7ed60590eca328962b948a03ebb0 | def __init__(self, filename, hyp):
'\n Args:\n filename - (string) - path+prefix of file output destination\n hyp - (dict) - algorithm hyperparameters\n '
self.filename = filename
self.p = hyp
self.elite = []
self.best = []
self.bestFitVec = []
self.spec_fit = []
s... | Args:
filename - (string) - path+prefix of file output destination
hyp - (dict) - algorithm hyperparameters | WANNRelease/WANN/wann_src/dataGatherer.py | __init__ | tressetp/brain-tokyo-workshop | 1,097 | python | def __init__(self, filename, hyp):
'\n Args:\n filename - (string) - path+prefix of file output destination\n hyp - (dict) - algorithm hyperparameters\n '
self.filename = filename
self.p = hyp
self.elite = []
self.best = []
self.bestFitVec = []
self.spec_fit = []
s... | def __init__(self, filename, hyp):
'\n Args:\n filename - (string) - path+prefix of file output destination\n hyp - (dict) - algorithm hyperparameters\n '
self.filename = filename
self.p = hyp
self.elite = []
self.best = []
self.bestFitVec = []
self.spec_fit = []
s... |
fee5c990d896f47b5a08734d9c75d751cee9d8f9499416750e5594a795e341bd | def save(self, gen=(- 1), saveFullPop=False):
' Save data to disk '
filename = self.filename
pref = ('log/' + filename)
gStatLabel = ['x_scale', 'fit_med', 'fit_max', 'fit_top', 'fit_peak', 'node_med', 'conn_med']
genStats = np.empty((len(self.x_scale), 0))
for i in range(len(gStatLabel)):
... | Save data to disk | WANNRelease/WANN/wann_src/dataGatherer.py | save | tressetp/brain-tokyo-workshop | 1,097 | python | def save(self, gen=(- 1), saveFullPop=False):
' '
filename = self.filename
pref = ('log/' + filename)
gStatLabel = ['x_scale', 'fit_med', 'fit_max', 'fit_top', 'fit_peak', 'node_med', 'conn_med']
genStats = np.empty((len(self.x_scale), 0))
for i in range(len(gStatLabel)):
evalString = (... | def save(self, gen=(- 1), saveFullPop=False):
' '
filename = self.filename
pref = ('log/' + filename)
gStatLabel = ['x_scale', 'fit_med', 'fit_max', 'fit_top', 'fit_peak', 'node_med', 'conn_med']
genStats = np.empty((len(self.x_scale), 0))
for i in range(len(gStatLabel)):
evalString = (... |
8627f7ca4c7fcb7c650477bc21714ca5bd01b5e8ce5132c7e94c952e53b3dee7 | def preprocess(self, img):
'Makes number of channels consistent'
if (img.shape[0] == 1):
img = img.repeat(3, 1, 1)
elif (img.shape[0] == 4):
img = img[(:3, :, :)]
return img | Makes number of channels consistent | src/img_datasets.py | preprocess | tremblerz/covidscanner | 0 | python | def preprocess(self, img):
if (img.shape[0] == 1):
img = img.repeat(3, 1, 1)
elif (img.shape[0] == 4):
img = img[(:3, :, :)]
return img | def preprocess(self, img):
if (img.shape[0] == 1):
img = img.repeat(3, 1, 1)
elif (img.shape[0] == 4):
img = img[(:3, :, :)]
return img<|docstring|>Makes number of channels consistent<|endoftext|> |
18ce128b4a680e3401f4238e49634856df1ee67d28cec4f924281a31087347bf | def __init__(self, capacity):
'\n :type capacity: int\n '
self.c = capacity
self.cache = []
self.d = {} | :type capacity: int | leetcode/146.LRU-Cache.py | __init__ | sogapalag/problems | 1 | python | def __init__(self, capacity):
'\n \n '
self.c = capacity
self.cache = []
self.d = {} | def __init__(self, capacity):
'\n \n '
self.c = capacity
self.cache = []
self.d = {}<|docstring|>:type capacity: int<|endoftext|> |
d60d31fce320519e7f0d6aab86cf7f9efdf7be5a0494f421978e0d0e658b0598 | def get(self, key):
'\n :rtype: int\n '
if (key not in self.cache):
return (- 1)
else:
i = self.cache.index(key)
self.cache.pop(i)
self.cache.insert(0, key)
return self.d[key] | :rtype: int | leetcode/146.LRU-Cache.py | get | sogapalag/problems | 1 | python | def get(self, key):
'\n \n '
if (key not in self.cache):
return (- 1)
else:
i = self.cache.index(key)
self.cache.pop(i)
self.cache.insert(0, key)
return self.d[key] | def get(self, key):
'\n \n '
if (key not in self.cache):
return (- 1)
else:
i = self.cache.index(key)
self.cache.pop(i)
self.cache.insert(0, key)
return self.d[key]<|docstring|>:rtype: int<|endoftext|> |
14f058db821f12ead0c54b985577d8a962cd691a687c169b8bb7f38f1d37591d | def set(self, key, value):
'\n :type key: int\n :type value: int\n :rtype: nothing\n '
if (key in self.cache):
i = self.cache.index(key)
self.cache.pop(i)
self.cache.insert(0, key)
self.d[key] = value
elif (len(self.cache) < self.c):
self.c... | :type key: int
:type value: int
:rtype: nothing | leetcode/146.LRU-Cache.py | set | sogapalag/problems | 1 | python | def set(self, key, value):
'\n :type key: int\n :type value: int\n :rtype: nothing\n '
if (key in self.cache):
i = self.cache.index(key)
self.cache.pop(i)
self.cache.insert(0, key)
self.d[key] = value
elif (len(self.cache) < self.c):
self.c... | def set(self, key, value):
'\n :type key: int\n :type value: int\n :rtype: nothing\n '
if (key in self.cache):
i = self.cache.index(key)
self.cache.pop(i)
self.cache.insert(0, key)
self.d[key] = value
elif (len(self.cache) < self.c):
self.c... |
e6b619858c403d8e3e309a3ae7f0ef0b0afdbb58bb100626a98ba368bbe0a9d4 | def is_date(self):
'\n check date : YY-MM-YY\n :return: bool\n '
try:
return re.match('([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))', self.value)
except Exception:
return False | check date : YY-MM-YY
:return: bool | src/pyvalidations/rules/datetime.py | is_date | MajAhd/py_validations | 6 | python | def is_date(self):
'\n check date : YY-MM-YY\n :return: bool\n '
try:
return re.match('([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))', self.value)
except Exception:
return False | def is_date(self):
'\n check date : YY-MM-YY\n :return: bool\n '
try:
return re.match('([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))', self.value)
except Exception:
return False<|docstring|>check date : YY-MM-YY
:return: bool<|endoftext|> |
df44eedfbbeec67e6a657a8ca1857c5b7af572034caf51c1ba6a60c912123498 | def is_time(self):
'\n check Time : HH:MM AM , HH:MM PM , HH:MM\n :return: bool\n '
try:
return re.match('^([0-1]?[0-9]|2[0-3]):[0-5][0-9]([AaPp][Mm])?$', self.value)
except Exception:
return False | check Time : HH:MM AM , HH:MM PM , HH:MM
:return: bool | src/pyvalidations/rules/datetime.py | is_time | MajAhd/py_validations | 6 | python | def is_time(self):
'\n check Time : HH:MM AM , HH:MM PM , HH:MM\n :return: bool\n '
try:
return re.match('^([0-1]?[0-9]|2[0-3]):[0-5][0-9]([AaPp][Mm])?$', self.value)
except Exception:
return False | def is_time(self):
'\n check Time : HH:MM AM , HH:MM PM , HH:MM\n :return: bool\n '
try:
return re.match('^([0-1]?[0-9]|2[0-3]):[0-5][0-9]([AaPp][Mm])?$', self.value)
except Exception:
return False<|docstring|>check Time : HH:MM AM , HH:MM PM , HH:MM
:return: bool<|endof... |
9caaff4b1051fa52e756f681e1771df105125c78f8fab577e045e39c1e4e3b85 | def is_date_time(self):
'\n check datetime : YY-MM-YY HH:MM\n :return: bool\n '
try:
return re.match('([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])) ([0-1]?[0-9]|2[0-3]):[0-5][0-9]$', self.value)
except Exception:
return False | check datetime : YY-MM-YY HH:MM
:return: bool | src/pyvalidations/rules/datetime.py | is_date_time | MajAhd/py_validations | 6 | python | def is_date_time(self):
'\n check datetime : YY-MM-YY HH:MM\n :return: bool\n '
try:
return re.match('([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])) ([0-1]?[0-9]|2[0-3]):[0-5][0-9]$', self.value)
except Exception:
return False | def is_date_time(self):
'\n check datetime : YY-MM-YY HH:MM\n :return: bool\n '
try:
return re.match('([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])) ([0-1]?[0-9]|2[0-3]):[0-5][0-9]$', self.value)
except Exception:
return False<|docstring|>check datetime : YY-MM-YY H... |
a1ae00f9bf32800e0c81b94728783287b84d38acd8ef0fbe8b4ce23482d0accb | def is_timezone(self):
'\n check timezone : +1:30 , -02:00\n :return: bool\n '
try:
return re.match('[+-][0-9]{2}:[0-9]{2}\\b', self.value)
except Exception:
return False | check timezone : +1:30 , -02:00
:return: bool | src/pyvalidations/rules/datetime.py | is_timezone | MajAhd/py_validations | 6 | python | def is_timezone(self):
'\n check timezone : +1:30 , -02:00\n :return: bool\n '
try:
return re.match('[+-][0-9]{2}:[0-9]{2}\\b', self.value)
except Exception:
return False | def is_timezone(self):
'\n check timezone : +1:30 , -02:00\n :return: bool\n '
try:
return re.match('[+-][0-9]{2}:[0-9]{2}\\b', self.value)
except Exception:
return False<|docstring|>check timezone : +1:30 , -02:00
:return: bool<|endoftext|> |
6be63e08156c17035ab3139ca3f261258e0a0281c732d2b490a24eeb3b3f8cc9 | def date_equals(self, target):
'\n check datetime : YY-MM-YY == YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 == dt2)
except Exception:
... | check datetime : YY-MM-YY == YY-MM-YY
:param target: YY-MM-YY
:return: bool | src/pyvalidations/rules/datetime.py | date_equals | MajAhd/py_validations | 6 | python | def date_equals(self, target):
'\n check datetime : YY-MM-YY == YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 == dt2)
except Exception:
... | def date_equals(self, target):
'\n check datetime : YY-MM-YY == YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 == dt2)
except Exception:
... |
711bb456dd0b2f44751e2536506eea6c1dbdc87219e681e66503d6d1c067e5ff | def is_after(self, target):
'\n check datetime : YY-MM-YY > YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 > dt2)
except Exception:
... | check datetime : YY-MM-YY > YY-MM-YY
:param target: YY-MM-YY
:return: bool | src/pyvalidations/rules/datetime.py | is_after | MajAhd/py_validations | 6 | python | def is_after(self, target):
'\n check datetime : YY-MM-YY > YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 > dt2)
except Exception:
... | def is_after(self, target):
'\n check datetime : YY-MM-YY > YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 > dt2)
except Exception:
... |
7bc0a4d006714ad18732e578ed7bc02b348654f076243d421e04c7111fce8111 | def is_after_or_equal(self, target):
'\n check datetime : YY-MM-YY >= YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 >= dt2)
except Except... | check datetime : YY-MM-YY >= YY-MM-YY
:param target: YY-MM-YY
:return: bool | src/pyvalidations/rules/datetime.py | is_after_or_equal | MajAhd/py_validations | 6 | python | def is_after_or_equal(self, target):
'\n check datetime : YY-MM-YY >= YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 >= dt2)
except Except... | def is_after_or_equal(self, target):
'\n check datetime : YY-MM-YY >= YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 >= dt2)
except Except... |
96449833e072ce2f832d15b809d569cdb1297932ba055d33e3e7b6a4d21b7d1a | def is_before(self, target):
'\n check datetime : YY-MM-YY < YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 < dt2)
except Exception:
... | check datetime : YY-MM-YY < YY-MM-YY
:param target: YY-MM-YY
:return: bool | src/pyvalidations/rules/datetime.py | is_before | MajAhd/py_validations | 6 | python | def is_before(self, target):
'\n check datetime : YY-MM-YY < YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 < dt2)
except Exception:
... | def is_before(self, target):
'\n check datetime : YY-MM-YY < YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 < dt2)
except Exception:
... |
947a44a3425411dbc0c1c93010d9c89a299499910281a39125608d05de67d556 | def is_before_or_equal(self, target):
'\n check datetime : YY-MM-YY <= YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 <= dt2)
except Excep... | check datetime : YY-MM-YY <= YY-MM-YY
:param target: YY-MM-YY
:return: bool | src/pyvalidations/rules/datetime.py | is_before_or_equal | MajAhd/py_validations | 6 | python | def is_before_or_equal(self, target):
'\n check datetime : YY-MM-YY <= YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 <= dt2)
except Excep... | def is_before_or_equal(self, target):
'\n check datetime : YY-MM-YY <= YY-MM-YY\n :param target: YY-MM-YY\n :return: bool\n '
try:
dt1 = datetime.strptime(self.value, '%Y-%M-%d')
dt2 = datetime.strptime(target, '%Y-%M-%d')
return (dt1 <= dt2)
except Excep... |
04124dba573af0236c6900c9e4b911d901e825758a765f2ee10722f1f40c4c60 | def densepose_inference(densepose_outputs: Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)], densepose_confidences: Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)], detections: List[Instances]):
'\n Infer dense pose estimate based on outputs from the DensePose head\n and detecti... | Infer dense pose estimate based on outputs from the DensePose head
and detections. The estimate for each detection instance is stored in its
"pred_densepose" attribute.
Args:
densepose_outputs (tuple(`torch.Tensor`)): iterable containing 4 elements:
- s (:obj: `torch.Tensor`): coarse segmentation tensor of... | projects/DensePose/densepose/modeling/inference.py | densepose_inference | wdsd641417025/detectron2 | 780 | python | def densepose_inference(densepose_outputs: Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)], densepose_confidences: Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)], detections: List[Instances]):
'\n Infer dense pose estimate based on outputs from the DensePose head\n and detecti... | def densepose_inference(densepose_outputs: Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)], densepose_confidences: Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)], detections: List[Instances]):
'\n Infer dense pose estimate based on outputs from the DensePose head\n and detecti... |
b41877e8258f518dd2d34558cfe11248e62d76d9b1ddc5c767d6b8379d78d0db | def transliterate(name):
'\n\tАвтор: LarsKort\n\tДата: 16/07/2011; 1:05 GMT-4;\n\tНе претендую на "хорошесть" словарика. В моем случае и такой пойдет,\n\tвы всегда сможете добавить свои символы и даже слова. Только\n\tэто нужно делать в обоих списках, иначе будет ошибка.\n\t'
slovar = {'а': 'a', 'б': 'b', 'в': ... | Автор: LarsKort
Дата: 16/07/2011; 1:05 GMT-4;
Не претендую на "хорошесть" словарика. В моем случае и такой пойдет,
вы всегда сможете добавить свои символы и даже слова. Только
это нужно делать в обоих списках, иначе будет ошибка. | school_manager/users/username_helper.py | transliterate | hungryhost/school_manager | 0 | python | def transliterate(name):
'\n\tАвтор: LarsKort\n\tДата: 16/07/2011; 1:05 GMT-4;\n\tНе претендую на "хорошесть" словарика. В моем случае и такой пойдет,\n\tвы всегда сможете добавить свои символы и даже слова. Только\n\tэто нужно делать в обоих списках, иначе будет ошибка.\n\t'
slovar = {'а': 'a', 'б': 'b', 'в': ... | def transliterate(name):
'\n\tАвтор: LarsKort\n\tДата: 16/07/2011; 1:05 GMT-4;\n\tНе претендую на "хорошесть" словарика. В моем случае и такой пойдет,\n\tвы всегда сможете добавить свои символы и даже слова. Только\n\tэто нужно делать в обоих списках, иначе будет ошибка.\n\t'
slovar = {'а': 'a', 'б': 'b', 'в': ... |
6441686609ee3ec770c6038e1ba3424a47fef3e268e81ac5fd3f4cd83a3fcdee | def __init__(self, imageName, classId, x, y, w, h, typeCoordinates=CoordinatesType.Absolute, imgSize=None, bbType=BBType.GroundTruth, classConfidence=None, format=BBFormat.XYWH):
"Constructor.\n Args:\n imageName: String representing the image name.\n classId: String value representing ... | Constructor.
Args:
imageName: String representing the image name.
classId: String value representing class id.
x: Float value representing the X upper-left coordinate of the bounding box.
y: Float value representing the Y upper-left coordinate of the bounding box.
w: Float value representing the wid... | lib/BoundingBox.py | __init__ | MinliangLin/Object-Detection-Metrics | 4,240 | python | def __init__(self, imageName, classId, x, y, w, h, typeCoordinates=CoordinatesType.Absolute, imgSize=None, bbType=BBType.GroundTruth, classConfidence=None, format=BBFormat.XYWH):
"Constructor.\n Args:\n imageName: String representing the image name.\n classId: String value representing ... | def __init__(self, imageName, classId, x, y, w, h, typeCoordinates=CoordinatesType.Absolute, imgSize=None, bbType=BBType.GroundTruth, classConfidence=None, format=BBFormat.XYWH):
"Constructor.\n Args:\n imageName: String representing the image name.\n classId: String value representing ... |
08c8e509cb6349c403fbbfe94990de9b88e9847b30eb96faed651620cd3fd7a5 | def run_vectorized(operation, *inputs, constants=None, dtype=None, batch_size=None, **kwargs):
'Run the operation as if it was vectorized over the individual runs in the batch.\n\n Helper for cases when you have an operation that does not support vector arguments.\n This tool is still experimental and may not... | Run the operation as if it was vectorized over the individual runs in the batch.
Helper for cases when you have an operation that does not support vector arguments.
This tool is still experimental and may not work in all cases.
Parameters
----------
operation : callable
Operation that will be run `batch_size` tim... | elfi/model/tools.py | run_vectorized | hpesonen/elfi | 166 | python | def run_vectorized(operation, *inputs, constants=None, dtype=None, batch_size=None, **kwargs):
'Run the operation as if it was vectorized over the individual runs in the batch.\n\n Helper for cases when you have an operation that does not support vector arguments.\n This tool is still experimental and may not... | def run_vectorized(operation, *inputs, constants=None, dtype=None, batch_size=None, **kwargs):
'Run the operation as if it was vectorized over the individual runs in the batch.\n\n Helper for cases when you have an operation that does not support vector arguments.\n This tool is still experimental and may not... |
71896d5f2eba4d8da48144d5274c5375d2a052d2b99623d7a488744ad0d4a8f8 | def vectorize(operation, constants=None, dtype=None):
'Vectorize an operation.\n\n Helper for cases when you have an operation that does not support vector arguments.\n This tool is still experimental and may not work in all cases.\n\n Parameters\n ----------\n operation : callable\n Operation... | Vectorize an operation.
Helper for cases when you have an operation that does not support vector arguments.
This tool is still experimental and may not work in all cases.
Parameters
----------
operation : callable
Operation to vectorize.
constants : tuple, list, optional
A mask for constants in inputs, e.g. (... | elfi/model/tools.py | vectorize | hpesonen/elfi | 166 | python | def vectorize(operation, constants=None, dtype=None):
'Vectorize an operation.\n\n Helper for cases when you have an operation that does not support vector arguments.\n This tool is still experimental and may not work in all cases.\n\n Parameters\n ----------\n operation : callable\n Operation... | def vectorize(operation, constants=None, dtype=None):
'Vectorize an operation.\n\n Helper for cases when you have an operation that does not support vector arguments.\n This tool is still experimental and may not work in all cases.\n\n Parameters\n ----------\n operation : callable\n Operation... |
006db07a7cde15de1f7fc7e2c868fbdbcbbcc7781313248c15bdecf8980ea9c9 | def unpack_meta(*inputs, **kwinputs):
'Update ``kwinputs`` with keys and values from its ``meta`` dictionary.'
if ('meta' in kwinputs):
new_kwinputs = kwinputs['meta'].copy()
new_kwinputs.update(kwinputs)
kwinputs = new_kwinputs
return (inputs, kwinputs) | Update ``kwinputs`` with keys and values from its ``meta`` dictionary. | elfi/model/tools.py | unpack_meta | hpesonen/elfi | 166 | python | def unpack_meta(*inputs, **kwinputs):
if ('meta' in kwinputs):
new_kwinputs = kwinputs['meta'].copy()
new_kwinputs.update(kwinputs)
kwinputs = new_kwinputs
return (inputs, kwinputs) | def unpack_meta(*inputs, **kwinputs):
if ('meta' in kwinputs):
new_kwinputs = kwinputs['meta'].copy()
new_kwinputs.update(kwinputs)
kwinputs = new_kwinputs
return (inputs, kwinputs)<|docstring|>Update ``kwinputs`` with keys and values from its ``meta`` dictionary.<|endoftext|> |
58ae308d83d1fe95c834477c0130037829e350da149b2605df3924799e34c67b | def prepare_seed(*inputs, **kwinputs):
'Update ``kwinputs`` with the seed from its value ``random_state``.'
if ('random_state' in kwinputs):
seed = kwinputs['random_state'].get_state()[1][0]
sub_seed_index = (kwinputs.get('index_in_batch') or 0)
kwinputs['seed'] = get_sub_seed(seed, sub_... | Update ``kwinputs`` with the seed from its value ``random_state``. | elfi/model/tools.py | prepare_seed | hpesonen/elfi | 166 | python | def prepare_seed(*inputs, **kwinputs):
if ('random_state' in kwinputs):
seed = kwinputs['random_state'].get_state()[1][0]
sub_seed_index = (kwinputs.get('index_in_batch') or 0)
kwinputs['seed'] = get_sub_seed(seed, sub_seed_index)
return (inputs, kwinputs) | def prepare_seed(*inputs, **kwinputs):
if ('random_state' in kwinputs):
seed = kwinputs['random_state'].get_state()[1][0]
sub_seed_index = (kwinputs.get('index_in_batch') or 0)
kwinputs['seed'] = get_sub_seed(seed, sub_seed_index)
return (inputs, kwinputs)<|docstring|>Update ``kwinp... |
77de9cf985c6fad200d275796232e6b0249b5c73a6a3a2c2f21d6509a4055eba | def stdout_to_array(stdout, *inputs, sep=' ', dtype=None, **kwinputs):
'Convert a single row from stdout to np.array.'
return np.fromstring(stdout, dtype=dtype, sep=sep) | Convert a single row from stdout to np.array. | elfi/model/tools.py | stdout_to_array | hpesonen/elfi | 166 | python | def stdout_to_array(stdout, *inputs, sep=' ', dtype=None, **kwinputs):
return np.fromstring(stdout, dtype=dtype, sep=sep) | def stdout_to_array(stdout, *inputs, sep=' ', dtype=None, **kwinputs):
return np.fromstring(stdout, dtype=dtype, sep=sep)<|docstring|>Convert a single row from stdout to np.array.<|endoftext|> |
fcae1eff9e3bc9510e3cadb3d11ae186b53291878a640587abef95441623b18e | def run_external(command, *inputs, process_result=None, prepare_inputs=None, stdout=True, subprocess_kwargs=None, **kwinputs):
'Run an external commmand (e.g. shell script, or executable) on a subprocess.\n\n See external_operation below for parameter descriptions.\n\n Returns\n -------\n output\n\n ... | Run an external commmand (e.g. shell script, or executable) on a subprocess.
See external_operation below for parameter descriptions.
Returns
-------
output | elfi/model/tools.py | run_external | hpesonen/elfi | 166 | python | def run_external(command, *inputs, process_result=None, prepare_inputs=None, stdout=True, subprocess_kwargs=None, **kwinputs):
'Run an external commmand (e.g. shell script, or executable) on a subprocess.\n\n See external_operation below for parameter descriptions.\n\n Returns\n -------\n output\n\n ... | def run_external(command, *inputs, process_result=None, prepare_inputs=None, stdout=True, subprocess_kwargs=None, **kwinputs):
'Run an external commmand (e.g. shell script, or executable) on a subprocess.\n\n See external_operation below for parameter descriptions.\n\n Returns\n -------\n output\n\n ... |
2a2150d233f5ddcc8abba61f4ce5738be61fc0a42ef2591eb5ebfaa54c928ae0 | def external_operation(command, process_result=None, prepare_inputs=None, sep=' ', stdout=True, subprocess_kwargs=None):
'Wrap an external command as a Python callable (function).\n\n The external command can be e.g. a shell script, or an executable file.\n\n Parameters\n ----------\n command : str\n ... | Wrap an external command as a Python callable (function).
The external command can be e.g. a shell script, or an executable file.
Parameters
----------
command : str
Command to execute. Arguments can be passed to the executable by using Python's
format strings, e.g. `"myscript.sh {0} {batch_size} --seed {seed... | elfi/model/tools.py | external_operation | hpesonen/elfi | 166 | python | def external_operation(command, process_result=None, prepare_inputs=None, sep=' ', stdout=True, subprocess_kwargs=None):
'Wrap an external command as a Python callable (function).\n\n The external command can be e.g. a shell script, or an executable file.\n\n Parameters\n ----------\n command : str\n ... | def external_operation(command, process_result=None, prepare_inputs=None, sep=' ', stdout=True, subprocess_kwargs=None):
'Wrap an external command as a Python callable (function).\n\n The external command can be e.g. a shell script, or an executable file.\n\n Parameters\n ----------\n command : str\n ... |
363b226c937a7214ac05999a22e74f1600887e1ecef5f319ce0989b0935a8350 | def create_user(username, password):
'\n Function to create a new user\n '
new_user = User(username, password)
return new_user | Function to create a new user | run.py | create_user | TERESIA012/My-password-locker | 0 | python | def create_user(username, password):
'\n \n '
new_user = User(username, password)
return new_user | def create_user(username, password):
'\n \n '
new_user = User(username, password)
return new_user<|docstring|>Function to create a new user<|endoftext|> |
de8fc859360158bb3cff9bd81bfd2f669f999572bd4b7f42cd74bb2155af7022 | def save_user(user):
'\n Function to save user \n '
user.save_user() | Function to save user | run.py | save_user | TERESIA012/My-password-locker | 0 | python | def save_user(user):
'\n \n '
user.save_user() | def save_user(user):
'\n \n '
user.save_user()<|docstring|>Function to save user<|endoftext|> |
1bb65219c19ec8ab65628df4b1e9af05d71f9c5c7dff67df1e62d4d812147cd6 | def delete_user(username):
'\n Function delete user\n '
User.delete_user(username) | Function delete user | run.py | delete_user | TERESIA012/My-password-locker | 0 | python | def delete_user(username):
'\n \n '
User.delete_user(username) | def delete_user(username):
'\n \n '
User.delete_user(username)<|docstring|>Function delete user<|endoftext|> |
733302e40a4a3510bf494bb4be11acd2ac6fa3df86455a23521db2121dd207ba | def check_user(username):
'\n Function to check if user exists\n '
return User.check_user(username) | Function to check if user exists | run.py | check_user | TERESIA012/My-password-locker | 0 | python | def check_user(username):
'\n \n '
return User.check_user(username) | def check_user(username):
'\n \n '
return User.check_user(username)<|docstring|>Function to check if user exists<|endoftext|> |
fdc59c37f9d01a239f4f12ac4372dfd09fee74e309e2fb543a58da9ff6fe6603 | def check_user_exist(username, password):
'\n function that checks the username and confirms the password\n '
return User.check_user_exists(username, password) | function that checks the username and confirms the password | run.py | check_user_exist | TERESIA012/My-password-locker | 0 | python | def check_user_exist(username, password):
'\n \n '
return User.check_user_exists(username, password) | def check_user_exist(username, password):
'\n \n '
return User.check_user_exists(username, password)<|docstring|>function that checks the username and confirms the password<|endoftext|> |
df3f8383a0f4776a81c196f75672d833ccda64ca8eae5f6a1719447f93c9aac2 | def create_credentials(account, username, password):
'\n Function to create a new credentials\n '
new_credentials = Credentials(account, username, password)
return new_credentials | Function to create a new credentials | run.py | create_credentials | TERESIA012/My-password-locker | 0 | python | def create_credentials(account, username, password):
'\n \n '
new_credentials = Credentials(account, username, password)
return new_credentials | def create_credentials(account, username, password):
'\n \n '
new_credentials = Credentials(account, username, password)
return new_credentials<|docstring|>Function to create a new credentials<|endoftext|> |
dea824537bdde49fa3b6318398a7de25cba6c480881e76303eb9f55fa927a6c9 | def save_credentials(credentials):
'\n Function to save credentials \n '
Credentials.save_credentials(credentials) | Function to save credentials | run.py | save_credentials | TERESIA012/My-password-locker | 0 | python | def save_credentials(credentials):
'\n \n '
Credentials.save_credentials(credentials) | def save_credentials(credentials):
'\n \n '
Credentials.save_credentials(credentials)<|docstring|>Function to save credentials<|endoftext|> |
647b75452f23c4714f7dd1f5cf81ff5211bb87c5cb3e65af53c5d1769f178047 | def delete_credentials(account):
'\n Function to delete account credentials\n '
return Credentials.delete_credentials(account) | Function to delete account credentials | run.py | delete_credentials | TERESIA012/My-password-locker | 0 | python | def delete_credentials(account):
'\n \n '
return Credentials.delete_credentials(account) | def delete_credentials(account):
'\n \n '
return Credentials.delete_credentials(account)<|docstring|>Function to delete account credentials<|endoftext|> |
3091b3fca3a2b45a05bfa9852cbaafd99f2b1b22c8629784eba0160d3026bd6e | def find_by_acc(account):
'\n Function to search for an account\n '
return Credentials.find_by_acc(account) | Function to search for an account | run.py | find_by_acc | TERESIA012/My-password-locker | 0 | python | def find_by_acc(account):
'\n \n '
return Credentials.find_by_acc(account) | def find_by_acc(account):
'\n \n '
return Credentials.find_by_acc(account)<|docstring|>Function to search for an account<|endoftext|> |
d78c73e6530336b6f28798dab7204ad47564c5cf4341aa2397df27a667bc85fa | def display_credentials():
'\n Funtion to display credentials\n '
return Credentials.display_credentials() | Funtion to display credentials | run.py | display_credentials | TERESIA012/My-password-locker | 0 | python | def display_credentials():
'\n \n '
return Credentials.display_credentials() | def display_credentials():
'\n \n '
return Credentials.display_credentials()<|docstring|>Funtion to display credentials<|endoftext|> |
d6e5dd1d25a12368597afe7388dfb769acb80b5cc9169a580eba51064a8934c3 | def test_network_build():
'\n check whether the network is built sucessfully or not \n '
x = np.float32(np.random.random((3, 128, 128, 3)))
blazeface_extractor = network((128, 128, 3))
feature = blazeface_extractor(x)
print(feature)
assert ((feature[0].shape == (3, 16, 16, 96)) or (feature... | check whether the network is built sucessfully or not | implementation/test_network_build.py | test_network_build | minus31/BlazeFace | 44 | python | def test_network_build():
'\n \n '
x = np.float32(np.random.random((3, 128, 128, 3)))
blazeface_extractor = network((128, 128, 3))
feature = blazeface_extractor(x)
print(feature)
assert ((feature[0].shape == (3, 16, 16, 96)) or (feature[1].shape == (3, 8, 8, 96))) | def test_network_build():
'\n \n '
x = np.float32(np.random.random((3, 128, 128, 3)))
blazeface_extractor = network((128, 128, 3))
feature = blazeface_extractor(x)
print(feature)
assert ((feature[0].shape == (3, 16, 16, 96)) or (feature[1].shape == (3, 8, 8, 96)))<|docstring|>check whethe... |
fcdc962161a67f13046ac58209f85acce79e46cecadf005642a3d5b4f3c5857a | def square(n):
"\n Returns the input number, squared\n\n >>> square(0)\n 0\n >>> square(1)\n 1\n >>> square(2)\n 4\n >>> square(3)\n 9\n >>> square()\n Traceback (most recent call last):\n ...\n TypeError: square() missing 1 required positional argument: 'n'\n >>> square('x... | Returns the input number, squared
>>> square(0)
0
>>> square(1)
1
>>> square(2)
4
>>> square(3)
9
>>> square()
Traceback (most recent call last):
...
TypeError: square() missing 1 required positional argument: 'n'
>>> square('x')
Traceback (most recent call last):
...
TypeError: can't multiply sequence by non-int of t... | 10_testing_and_logging/01_simple_doctest.py | square | varshashivhare/Mastering-Python | 30 | python | def square(n):
"\n Returns the input number, squared\n\n >>> square(0)\n 0\n >>> square(1)\n 1\n >>> square(2)\n 4\n >>> square(3)\n 9\n >>> square()\n Traceback (most recent call last):\n ...\n TypeError: square() missing 1 required positional argument: 'n'\n >>> square('x... | def square(n):
"\n Returns the input number, squared\n\n >>> square(0)\n 0\n >>> square(1)\n 1\n >>> square(2)\n 4\n >>> square(3)\n 9\n >>> square()\n Traceback (most recent call last):\n ...\n TypeError: square() missing 1 required positional argument: 'n'\n >>> square('x... |
32b3ab78ffad416aea11b4bcb2bfc9d339a792262224f16095101e3a32871432 | def reverse_integer(x):
'Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside\n the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0.\n :type x: int\n :rtype: int\n '
x_string = str(x)
if (x_string[0] == '-'):
x_... | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside
the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0.
:type x: int
:rtype: int | LeetCode/reverse-integer.py | reverse_integer | amgad01/algorithms | 1 | python | def reverse_integer(x):
'Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside\n the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0.\n :type x: int\n :rtype: int\n '
x_string = str(x)
if (x_string[0] == '-'):
x_... | def reverse_integer(x):
'Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside\n the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0.\n :type x: int\n :rtype: int\n '
x_string = str(x)
if (x_string[0] == '-'):
x_... |
611266dfa24b4ff34b9db711f336c3a65cf7c307cac76ff450ddc072f235a3e1 | def get_arguments(self):
'\n Extracts the specific arguments of this CLI\n '
ApiCli.get_arguments(self)
if (self.args.metric_name is not None):
self._metric_name = self.args.metric_name
self.path = 'v1/metrics/{0}'.format(self._metric_name) | Extracts the specific arguments of this CLI | boundary/metric_delete.py | get_arguments | jdgwartney/pulse-api-cli | 0 | python | def get_arguments(self):
'\n \n '
ApiCli.get_arguments(self)
if (self.args.metric_name is not None):
self._metric_name = self.args.metric_name
self.path = 'v1/metrics/{0}'.format(self._metric_name) | def get_arguments(self):
'\n \n '
ApiCli.get_arguments(self)
if (self.args.metric_name is not None):
self._metric_name = self.args.metric_name
self.path = 'v1/metrics/{0}'.format(self._metric_name)<|docstring|>Extracts the specific arguments of this CLI<|endoftext|> |
d9ad74df56db3a8cab4d7be768e3803c937690c91c39eb58e781bc1755d5929c | def __len__(self):
'文件个数'
return len(self.names) | 文件个数 | apps/tools/crop.py | __len__ | SanstyleLab/pytorch-book | 1 | python | def __len__(self):
return len(self.names) | def __len__(self):
return len(self.names)<|docstring|>文件个数<|endoftext|> |
b6452845179d25ebfc47697cd8b4baabc9e140781fdf856a74b5e51d5eac45db | def __len__(self):
'图片个数'
return len(self.dataset) | 图片个数 | apps/tools/crop.py | __len__ | SanstyleLab/pytorch-book | 1 | python | def __len__(self):
return len(self.dataset) | def __len__(self):
return len(self.dataset)<|docstring|>图片个数<|endoftext|> |
1154b808a62afd4f28b50154e7cd2fec887f771cd76c9c883293af0d3670f541 | def create_output(predictions_dict, output_folder, tag):
'Custom output generation function'
directory = f'{output_folder}/{tag}'
if (not os.path.exists(directory)):
os.makedirs(directory)
d = {}
for inner in ['variable_param_ranges', 'best_params', 'beta_loss']:
if (inner in predict... | Custom output generation function | utils/generic/create_report.py | create_output | WadhwaniAI/covid-modelling | 3 | python | def create_output(predictions_dict, output_folder, tag):
directory = f'{output_folder}/{tag}'
if (not os.path.exists(directory)):
os.makedirs(directory)
d = {}
for inner in ['variable_param_ranges', 'best_params', 'beta_loss']:
if (inner in predictions_dict):
with open(f... | def create_output(predictions_dict, output_folder, tag):
directory = f'{output_folder}/{tag}'
if (not os.path.exists(directory)):
os.makedirs(directory)
d = {}
for inner in ['variable_param_ranges', 'best_params', 'beta_loss']:
if (inner in predictions_dict):
with open(f... |
0a3179d2f1ac2334c28b436be7a1533d1cb1ee44367246d746938cdb532cb3a5 | def save_dict_and_create_report(predictions_dict, config, ROOT_DIR='../../misc/reports/', config_filename='default.yaml', config_ROOT_DIR='../../configs/seir'):
"Creates report (BOTH MD and DOCX) for an input of a dict of predictions for a particular district/region\n The DOCX file can directly be uploaded to Go... | Creates report (BOTH MD and DOCX) for an input of a dict of predictions for a particular district/region
The DOCX file can directly be uploaded to Google Drive and shared with the people who have to review
Arguments:
predictions_dict {dict} -- Dict of predictions for a particual district/region [NOT ALL Districts]... | utils/generic/create_report.py | save_dict_and_create_report | WadhwaniAI/covid-modelling | 3 | python | def save_dict_and_create_report(predictions_dict, config, ROOT_DIR='../../misc/reports/', config_filename='default.yaml', config_ROOT_DIR='../../configs/seir'):
"Creates report (BOTH MD and DOCX) for an input of a dict of predictions for a particular district/region\n The DOCX file can directly be uploaded to Go... | def save_dict_and_create_report(predictions_dict, config, ROOT_DIR='../../misc/reports/', config_filename='default.yaml', config_ROOT_DIR='../../configs/seir'):
"Creates report (BOTH MD and DOCX) for an input of a dict of predictions for a particular district/region\n The DOCX file can directly be uploaded to Go... |
31ffaa2a25be33307877cf5a631c0ef0a927eb619014e6ff01ffda94985ade04 | def asset_name(asset: str, subset: str, namespace: Optional[str]=None) -> str:
'Return a consistent name for an asset.'
name = f'{asset}_{subset}'
if namespace:
name = f'{namespace}:{name}'
return name | Return a consistent name for an asset. | pype/blender/plugin.py | asset_name | tokejepsen/pype | 0 | python | def asset_name(asset: str, subset: str, namespace: Optional[str]=None) -> str:
name = f'{asset}_{subset}'
if namespace:
name = f'{namespace}:{name}'
return name | def asset_name(asset: str, subset: str, namespace: Optional[str]=None) -> str:
name = f'{asset}_{subset}'
if namespace:
name = f'{namespace}:{name}'
return name<|docstring|>Return a consistent name for an asset.<|endoftext|> |
9c5264a23128a880689f1f6e858e8a9573c55c36c39657f2d071de65e041fb50 | def create_blender_context(active: Optional[bpy.types.Object]=None, selected: Optional[bpy.types.Object]=None):
'Create a new Blender context. If an object is passed as\n parameter, it is set as selected and active.\n '
if (not isinstance(selected, list)):
selected = [selected]
for win in bpy.... | Create a new Blender context. If an object is passed as
parameter, it is set as selected and active. | pype/blender/plugin.py | create_blender_context | tokejepsen/pype | 0 | python | def create_blender_context(active: Optional[bpy.types.Object]=None, selected: Optional[bpy.types.Object]=None):
'Create a new Blender context. If an object is passed as\n parameter, it is set as selected and active.\n '
if (not isinstance(selected, list)):
selected = [selected]
for win in bpy.... | def create_blender_context(active: Optional[bpy.types.Object]=None, selected: Optional[bpy.types.Object]=None):
'Create a new Blender context. If an object is passed as\n parameter, it is set as selected and active.\n '
if (not isinstance(selected, list)):
selected = [selected]
for win in bpy.... |
ed763bcc7856dab07dd39e0000643f082ea53902c5b369594de0d4665f7d7261 | @staticmethod
def _get_instance_empty(instance_name: str, nodes: List) -> Optional[bpy.types.Object]:
"Get the 'instance empty' that holds the collection instance."
for node in nodes:
if (not isinstance(node, bpy.types.Object)):
continue
if ((node.type == 'EMPTY') and (node.instance_... | Get the 'instance empty' that holds the collection instance. | pype/blender/plugin.py | _get_instance_empty | tokejepsen/pype | 0 | python | @staticmethod
def _get_instance_empty(instance_name: str, nodes: List) -> Optional[bpy.types.Object]:
for node in nodes:
if (not isinstance(node, bpy.types.Object)):
continue
if ((node.type == 'EMPTY') and (node.instance_type == 'COLLECTION') and node.instance_collection and (node.n... | @staticmethod
def _get_instance_empty(instance_name: str, nodes: List) -> Optional[bpy.types.Object]:
for node in nodes:
if (not isinstance(node, bpy.types.Object)):
continue
if ((node.type == 'EMPTY') and (node.instance_type == 'COLLECTION') and node.instance_collection and (node.n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.