uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
992fee620636b7e596727a8a
train
function
def normalize(xs): min_xs = np.min(xs) max_xs = np.max(xs) return (xs-min_xs)/(max_xs-min_xs)
def normalize(xs):
min_xs = np.min(xs) max_xs = np.max(xs) return (xs-min_xs)/(max_xs-min_xs)
def ncr(n, r): r = min(r, n-r) numer = reduce(op.mul, range(n, n-r, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer / denom def normalize(xs):
64
64
37
4
59
BeatrizRubio/Article_Mathematics_2020
Experiments_table/Cycloid/Basis2/basis2.py
Python
normalize
normalize
20
23
20
20
b919d4a41cd3f96a4427f9a13fea43fc549aeac6
bigcode/the-stack
train
9ff83771e040eb165fcc4d3f
train
class
class TesseractConan(ConanFile): name = "tesseract" description = "Tesseract Open Source OCR Engine" url = "https://github.com/conan-io/conan-center-index" topics = ("conan", "ocr", "image", "multimedia", "graphics") license = "Apache-2.0" homepage = "https://github.com/tesseract-ocr/tesseract" ...
class TesseractConan(ConanFile):
name = "tesseract" description = "Tesseract Open Source OCR Engine" url = "https://github.com/conan-io/conan-center-index" topics = ("conan", "ocr", "image", "multimedia", "graphics") license = "Apache-2.0" homepage = "https://github.com/tesseract-ocr/tesseract" exports_sources = ["CMakeList...
import os from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration class TesseractConan(ConanFile):
35
256
1,052
11
23
hoxnox/conan-center-index
recipes/tesseract/all/conanfile.py
Python
TesseractConan
TesseractConan
6
104
6
6
87c3d1184da0f85a068cdff0452714f8f19f2c46
bigcode/the-stack
train
662501b16d3ad36809018319
train
function
def test_dirpath(thepath: str): import pathlib path_obj = pathlib.Path(thepath).resolve() path_exists = path_obj.exists() path_isdir = path_obj.is_dir() if path_exists and path_isdir: return True else: print(f"The path is a directory: {path_isdir}") print(f"The path exis...
def test_dirpath(thepath: str):
import pathlib path_obj = pathlib.Path(thepath).resolve() path_exists = path_obj.exists() path_isdir = path_obj.is_dir() if path_exists and path_isdir: return True else: print(f"The path is a directory: {path_isdir}") print(f"The path exists: {path_exists}")
# %% ####################################### def test_dirpath(thepath: str):
14
64
83
9
5
SecTraversl/python_file-and-folder_Tools
test_dirpath.py
Python
test_dirpath
test_dirpath
3
13
3
3
58053c3c6d2d208bcf92f1274febbebe0c6e9973
bigcode/the-stack
train
c282c1db5fb0c08444bc0f23
train
function
def FloppyImageFileInfo(vim, *args, **kwargs): '''This data object type describes a file that is a floppy disk image.''' obj = vim.client.factory.create('{urn:vim25}FloppyImageFileInfo') # do some validation checking... if (len(args) + len(kwargs)) < 1: raise IndexError('Expected at least 2 ar...
def FloppyImageFileInfo(vim, *args, **kwargs):
'''This data object type describes a file that is a floppy disk image.''' obj = vim.client.factory.create('{urn:vim25}FloppyImageFileInfo') # do some validation checking... if (len(args) + len(kwargs)) < 1: raise IndexError('Expected at least 2 arguments got: %d' % len(args)) required = [...
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def FloppyImageFileInfo(vim, *args, **kwargs):
51
64
207
15
36
Infinidat/pyvisdk
pyvisdk/do/floppy_image_file_info.py
Python
FloppyImageFileInfo
FloppyImageFileInfo
11
32
11
11
fc72e9302b01e91c81b824f1d2758d1f40235130
bigcode/the-stack
train
bea46314181ed9691c2bb0b9
train
function
def main (): yaml_file = 'ex6_test.yml' json_file = 'ex6_test.json' my_dict = { 'ip_addr': '1.1.1.1', 'platform': 'cisco_ios', 'vendor': 'cisco', 'model': '2800' } my_list = [ 'some string', 99, 100, my_dict, 'test1', ...
def main ():
yaml_file = 'ex6_test.yml' json_file = 'ex6_test.json' my_dict = { 'ip_addr': '1.1.1.1', 'platform': 'cisco_ios', 'vendor': 'cisco', 'model': '2800' } my_list = [ 'some string', 99, 100, my_dict, 'test1', 'test2' ]...
#!/usr/bin/env python from __future__ import unicode_literals, print_function import yaml import json def main ():
27
64
151
4
22
smlandreth/pynet_week1
ex6.py
Python
main
main
8
32
8
8
434e890b2f9d16d36cd2d3f143cdeb2de8e22f7b
bigcode/the-stack
train
da4c30ad7d3a17024f1d8fc5
train
function
def _find_how_to_resize(i3, win=None): if win is None: win = i3.get_tree().find_focused() win_h = win.rect.height win_w = win.rect.width win_x = win.rect.x win_y = win.rect.y ws = win.workspace() max_h = ws.rect.height max_w = ws.rect.width max_x = ws.rect.x max_y = ws.r...
def _find_how_to_resize(i3, win=None):
if win is None: win = i3.get_tree().find_focused() win_h = win.rect.height win_w = win.rect.width win_x = win.rect.x win_y = win.rect.y ws = win.workspace() max_h = ws.rect.height max_w = ws.rect.width max_x = ws.rect.x max_y = ws.rect.y w = round(win_w / max_w, 2) ...
the other monitor/s are # hidpi or not other_output_width = next( o.rect.width for o in outputs if o.name != ws.ipc_data['output'] ) return current_output_width, other_output_width, outputs def _find_how_to_resize(i3, win=None):
66
66
220
13
52
petobens/dotfiles
arch/config/i3/multimon_move.py
Python
_find_how_to_resize
_find_how_to_resize
97
120
97
97
d8c10693afbafd6019f64d58c3574d0c3db16aa3
bigcode/the-stack
train
18378679fb0276b5fa3d0007
train
function
def _get_resize_map(i3): res_map = {} ws = i3.get_tree().find_focused().workspace() output_width, _, __ = get_output_width(i3, ws) for w in ws.leaves(): res_map[w.id] = { 'win': w, 'focused': w.focused, 'how': _find_how_to_resize(i3, w), 'fullscree...
def _get_resize_map(i3):
res_map = {} ws = i3.get_tree().find_focused().workspace() output_width, _, __ = get_output_width(i3, ws) for w in ws.leaves(): res_map[w.id] = { 'win': w, 'focused': w.focused, 'how': _find_how_to_resize(i3, w), 'fullscreen': w.fullscreen_mode, ...
Brave-browser', 'firefox') ): # Note: firefox meta key not working zoom_dir = 'u' if new_output_width > win_output_width else 'd' sh(f'xdotool key Super+{zoom_dir}') return def _get_resize_map(i3):
64
64
119
8
55
petobens/dotfiles
arch/config/i3/multimon_move.py
Python
_get_resize_map
_get_resize_map
63
76
63
63
bda341066fdfcad1da6af6eb8f7f95842af36a22
bigcode/the-stack
train
5e0eefff7a7284ffa9d3a974
train
function
def move_and_resize(i3, direction=None, move_win=True, workspace=None): """Move windows and container between monitors resizing/rescaling appropiately.""" resize_map = _get_resize_map(i3) cmd = 'fullscreen disable, ' if direction is not None: cmd += ( f'move {"container" if move_win...
def move_and_resize(i3, direction=None, move_win=True, workspace=None):
"""Move windows and container between monitors resizing/rescaling appropiately.""" resize_map = _get_resize_map(i3) cmd = 'fullscreen disable, ' if direction is not None: cmd += ( f'move {"container" if move_win else "workspace"} to ' f'output {direction}, focus output {...
#!/usr/bin/env python3 """Move containers and workspaces between monitors (i.e outputs).""" import sys from time import sleep import i3ipc from i3_helpers import sh from resize import resize_win def move_and_resize(i3, direction=None, move_win=True, workspace=None):
64
139
464
17
46
petobens/dotfiles
arch/config/i3/multimon_move.py
Python
move_and_resize
move_and_resize
13
60
13
13
8cc571fa865f913793701600ca24554e8fd86bf5
bigcode/the-stack
train
245232def710abb71388a279
train
function
def get_output_width(i3, ws=None): """Get current workspace output width (and list of outputs).""" if ws is None: ws = i3.get_tree().find_focused().workspace() outputs = [i for i in i3.get_outputs() if i.active] current_output_width = next( o.rect.width for o in outputs if o.name == ws.i...
def get_output_width(i3, ws=None):
"""Get current workspace output width (and list of outputs).""" if ws is None: ws = i3.get_tree().find_focused().workspace() outputs = [i for i in i3.get_outputs() if i.active] current_output_width = next( o.rect.width for o in outputs if o.name == ws.ipc_data['output'] ) other_o...
'focused': w.focused, 'how': _find_how_to_resize(i3, w), 'fullscreen': w.fullscreen_mode, 'class': w.window_class, 'output_width': output_width, } return res_map def get_output_width(i3, ws=None):
64
64
173
10
53
petobens/dotfiles
arch/config/i3/multimon_move.py
Python
get_output_width
get_output_width
79
94
79
79
47e8332239e7c9db85eb1f4c422d2a0d42b154fc
bigcode/the-stack
train
4d500d85ca2e040f0777b8ed
train
class
class ContactAdmin(admin.ModelAdmin): list_display = ('name','age', 'email') # list search_fields = ('name',) inlines = [TagInline] # Inline fieldsets = ( ['Main',{ 'fields':('name','email'), }], ['Advance',{ 'classes': ('collapse',), 'fields'...
class ContactAdmin(admin.ModelAdmin):
list_display = ('name','age', 'email') # list search_fields = ('name',) inlines = [TagInline] # Inline fieldsets = ( ['Main',{ 'fields':('name','email'), }], ['Advance',{ 'classes': ('collapse',), 'fields': ('age',), }] )
from django.contrib import admin from west.models import Character,Contact,Tag #vamei,vameiisgood # Register your models here. # admin.site.register([Character, Contact, Tag]) class TagInline(admin.TabularInline): model = Tag class ContactAdmin(admin.ModelAdmin):
62
64
87
7
54
qingyunwhu/DjangoApp
west/admin.py
Python
ContactAdmin
ContactAdmin
12
25
12
12
fa000e46ebe325fdf4db064c0054fa06d3c8259a
bigcode/the-stack
train
9db8dd3bbb6225d9853a516c
train
class
class TagInline(admin.TabularInline): model = Tag
class TagInline(admin.TabularInline):
model = Tag
from django.contrib import admin from west.models import Character,Contact,Tag #vamei,vameiisgood # Register your models here. # admin.site.register([Character, Contact, Tag]) class TagInline(admin.TabularInline):
50
64
13
8
42
qingyunwhu/DjangoApp
west/admin.py
Python
TagInline
TagInline
9
10
9
9
a003f1a572b778b39d3eb5e097fb4951c67f06ee
bigcode/the-stack
train
d4aa77ce906284e1376dee85
train
class
class Item(Resource): parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, help="This field cannot be left blank!" ) parser.add_argument('store_id', ty...
class Item(Resource):
parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, help="This field cannot be left blank!" ) parser.add_argument('store_id', type=int, ...
from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from models.item import ItemModel class Item(Resource):
30
96
320
4
25
tomgoral/Udemy-REST-API-FLASK-PYTHON
section11/146_AddingClaims/start/resources/item.py
Python
Item
Item
6
60
6
6
e6c9533bfe16f85807be4a16f2e968bb255ba915
bigcode/the-stack
train
8859d08abcf1c78c5648d8a0
train
class
class ItemList(Resource): def get(self): return {'items': [x.json() for x in ItemModel.find_all()]}
class ItemList(Resource):
def get(self): return {'items': [x.json() for x in ItemModel.find_all()]}
put(self, name): data = Item.parser.parse_args() item = ItemModel.find_by_name(name) if item: item.price = data['price'] else: item = ItemModel(name, **data) item.save_to_db() return item.json() class ItemList(Resource):
64
64
28
5
59
tomgoral/Udemy-REST-API-FLASK-PYTHON
section11/146_AddingClaims/start/resources/item.py
Python
ItemList
ItemList
63
65
63
63
2504c33c85f235b524ffae38b8825fcda7cc8e71
bigcode/the-stack
train
bd6bc1eecbf4ad6ba24bf03f
train
function
def orb(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) orb = cv2.ORB_create(nfeatures=1500) keypoints_orb, descriptors = orb.detectAndCompute(gray, None) return cv2.drawKeypoints(img, keypoints_orb, img)
def orb(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) orb = cv2.ORB_create(nfeatures=1500) keypoints_orb, descriptors = orb.detectAndCompute(gray, None) return cv2.drawKeypoints(img, keypoints_orb, img)
import cv2 def orb(img):
8
64
66
4
3
chandniagarwal/image_analyser
algorithms/orb.py
Python
orb
orb
4
8
4
4
be381f371c0f5a360364e8e26529bef419dc1fc3
bigcode/the-stack
train
fafabdd8152fcfcc245be5ec
train
class
class Customer(Model): def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('role', ndb.EnumProperty, enum = User.Status, default = User.Status.L0, repeated = True)
class Customer(Model):
def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('role', ndb.EnumProperty, enum = User.Status, default = User.Status.L0, repeated = True)
'), email = fire_user.get( 'email')) _user.put() if _user.email != fire_user.get('email'): _user.email = fire_user.get('email') _user.put() _user.name = fire_user.get('name') return _user class Customer(Model):
64
64
53
4
59
LiSe-Team/LiSe
data.py
Python
Customer
Customer
45
51
45
46
6e8d6c0669d0dc69a19122647a84ca47879b5258
bigcode/the-stack
train
27e12ccdfab56e1b126ec481
train
class
class Usage(Model): """ Entity that represents one usage of a licence """ def schema(self): super().schema() # the key that this is a usage of self.Property('licence', ndb.KeyProperty, kind = Licence) # local copy of the key access_level self.Property('access_lev...
class Usage(Model):
""" Entity that represents one usage of a licence """ def schema(self): super().schema() # the key that this is a usage of self.Property('licence', ndb.KeyProperty, kind = Licence) # local copy of the key access_level self.Property('access_level', ndb.IntegerProp...
generate_keys(self): """ Generate a new set of RSA keys. """ (public_key, private_key) = rsa.newkeys(1024) self.public = public_key.save_pkcs1() self.private = private_key.save_pkcs1() class Product(Model): """ Entitiy that represents the Product. """ ...
256
256
897
4
252
LiSe-Team/LiSe
data.py
Python
Usage
Usage
105
226
105
105
438156085dba80356772dd50623d21bf18f3faf9
bigcode/the-stack
train
fa5d84297ecacfcafa4a0b2d
train
class
class Organization(Model): """ Entity that represents the ISV """ def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('owner', ndb.KeyProperty, kind = User) self.Property('private', ndb.PickleProperty) self.Property('public'...
class Organization(Model):
""" Entity that represents the ISV """ def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('owner', ndb.KeyProperty, kind = User) self.Property('private', ndb.PickleProperty) self.Property('public', ndb.PickleProperty) ...
name') return _user class Customer(Model): def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('role', ndb.EnumProperty, enum = User.Status, default = User.Status.L0, repeated = True) class Organization(Model):
64
64
133
4
60
LiSe-Team/LiSe
data.py
Python
Organization
Organization
54
72
54
54
1efd9a78628d8f5c729619380e0f238f59ac1e4a
bigcode/the-stack
train
a8f28567c14396bd1505dfb5
train
class
class Licence(Model): """ Entity that represents that grant of a licence to access the Product. """ def schema(self): super().schema() # produt for which this is a licence key self.Property('product', ndb.KeyProperty, kind = Product) # Integer showing the licence type ...
class Licence(Model):
""" Entity that represents that grant of a licence to access the Product. """ def schema(self): super().schema() # produt for which this is a licence key self.Property('product', ndb.KeyProperty, kind = Product) # Integer showing the licence type self.Property('a...
""" def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('organization', ndb.KeyProperty, kind = Organization) # Is this product a freemium product self.Property('allows_free', ndb.BooleanProperty) class Licence(Model):
64
64
121
4
60
LiSe-Team/LiSe
data.py
Python
Licence
Licence
88
102
88
88
92a56a0f87184fccb388e38763f72522ff3ef9a2
bigcode/the-stack
train
0b78accfbba08e151b83eee3
train
class
class Product(Model): """ Entitiy that represents the Product. """ def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('organization', ndb.KeyProperty, kind = Organization) # Is this product a freemium product self.Property(...
class Product(Model):
""" Entitiy that represents the Product. """ def schema(self): super().schema() self.Property('name', ndb.StringProperty) self.Property('organization', ndb.KeyProperty, kind = Organization) # Is this product a freemium product self.Property('allows_free', ndb.Boo...
ickleProperty) def generate_keys(self): """ Generate a new set of RSA keys. """ (public_key, private_key) = rsa.newkeys(1024) self.public = public_key.save_pkcs1() self.private = private_key.save_pkcs1() class Product(Model):
64
64
76
4
60
LiSe-Team/LiSe
data.py
Python
Product
Product
75
85
75
75
f454620f02b1098cbf4fe3d4316f4fd4ddd22f10
bigcode/the-stack
train
c5307130cef6435e89872f4a
train
class
class User(Model): class Status(Enum): L0 = 0 L1 = 1 L2 = 2 L3 = 3 L4 = 4 def schema(self): super().schema() self.Property("user_id", ndb.StringProperty) self.Property('email', ndb.StringProperty) self.Property('name', ndb.StringProperty)...
class User(Model):
class Status(Enum): L0 = 0 L1 = 1 L2 = 2 L3 = 3 L4 = 4 def schema(self): super().schema() self.Property("user_id", ndb.StringProperty) self.Property('email', ndb.StringProperty) self.Property('name', ndb.StringProperty) @classmethod ...
from simplendb.ndb import Model, ndb from enum import Enum import logging from datetime import datetime import rsa import json from base64 import b64encode, b64decode class User(Model):
47
72
242
4
42
LiSe-Team/LiSe
data.py
Python
User
User
10
43
10
11
ec3bec74915e9ec7aa7bd8762bf134d7e68d2ec9
bigcode/the-stack
train
b67b7275a9f390a7a3ae10a1
train
function
def get_next_target(page): start_link = page.find('<a href=') if start_link == -1: return None, 0 start_quote = page.find('"', start_link) end_quote = page.find('"', start_quote + 1) url = page[start_quote + 1:end_quote] return url, end_quote
def get_next_target(page):
start_link = page.find('<a href=') if start_link == -1: return None, 0 start_quote = page.find('"', start_link) end_quote = page.find('"', start_quote + 1) url = page[start_quote + 1:end_quote] return url, end_quote
1> <p> <ol> <li> Go to the store and buy a container of hummus. <li> Open it. </ol> </body> </html> """, } def get_page(url): if url in cache: return cache[url] return "" def get_next_target(page):
63
64
76
6
57
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
get_next_target
get_next_target
196
203
196
196
c3003398a83e01ab4cf0d13f8e5d747ee27aa56e
bigcode/the-stack
train
c691f0e8e9557b5c8835cfd7
train
function
def get_all_links(page): links = [] while True: url, endpos = get_next_target(page) if url: links.append(url) page = page[endpos:] else: break return links
def get_all_links(page):
links = [] while True: url, endpos = get_next_target(page) if url: links.append(url) page = page[endpos:] else: break return links
if start_link == -1: return None, 0 start_quote = page.find('"', start_link) end_quote = page.find('"', start_quote + 1) url = page[start_quote + 1:end_quote] return url, end_quote def get_all_links(page):
64
64
51
6
57
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
get_all_links
get_all_links
205
214
205
205
f6540b3d2b74a76df1f51149d7621677f6d36edd
bigcode/the-stack
train
85ad5443e7073f1d24cc17b0
train
function
def lookup(index, keyword): if keyword in index: return index[keyword] else: return None
def lookup(index, keyword):
if keyword in index: return index[keyword] else: return None
words = content.split() for word in words: add_to_index(index, word, url) def add_to_index(index, keyword, url): if keyword in index: index[keyword].append(url) else: index[keyword] = [url] def lookup(index, keyword):
64
64
25
6
58
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
lookup
lookup
233
237
233
233
be0b1d56226127d15b6fc2c50e18f7ec367babfc
bigcode/the-stack
train
f4299b9642409968bb2fd9ad
train
function
def add_page_to_index(index, url, content): words = content.split() for word in words: add_to_index(index, word, url)
def add_page_to_index(index, url, content):
words = content.split() for word in words: add_to_index(index, word, url)
_target(page) if url: links.append(url) page = page[endpos:] else: break return links def union(a, b): for e in b: if e not in a: a.append(e) def add_page_to_index(index, url, content):
64
64
33
11
53
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
add_page_to_index
add_page_to_index
222
225
222
222
4e91393d54a55f51870002e350d2bda118a19e14
bigcode/the-stack
train
12ad870fb88e2060398e24df
train
function
def quicksort(l): if not l or len(l) <= 1: return l else: bigger = [] less = [] pivot = l[0] for i in l[1:]: if i > pivot: bigger.append(i) else: less.append(i) return quicksort(bigger) + [pivot] + quicksort(less...
def quicksort(l):
if not l or len(l) <= 1: return l else: bigger = [] less = [] pivot = l[0] for i in l[1:]: if i > pivot: bigger.append(i) else: less.append(i) return quicksort(bigger) + [pivot] + quicksort(less)
dict[ranks[url]] = url lranks = [] for i in dict.keys(): lranks.append(i) lranks = quicksort(lranks) res = [] for rank in lranks: res.append(dict[rank]) return res def quicksort(l):
64
64
84
5
58
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
quicksort
quicksort
58
70
58
58
84ddf4691a88de36b8005821b1e0b360647e105d
bigcode/the-stack
train
43a57309713c84785c449e14
train
function
def get_page(url): if url in cache: return cache[url] return ""
def get_page(url):
if url in cache: return cache[url] return ""
/hummus.html': """<html> <body> <h1> Hummus Recipe </h1> <p> <ol> <li> Go to the store and buy a container of hummus. <li> Open it. </ol> </body> </html> """, } def get_page(url):
64
64
19
5
59
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
get_page
get_page
190
193
190
190
60b8d3b45c680866cb25d1b2ae4eee268ed6676b
bigcode/the-stack
train
560fbf2ba34db9df7f4b4ceb
train
function
def add_to_index(index, keyword, url): if keyword in index: index[keyword].append(url) else: index[keyword] = [url]
def add_to_index(index, keyword, url):
if keyword in index: index[keyword].append(url) else: index[keyword] = [url]
, b): for e in b: if e not in a: a.append(e) def add_page_to_index(index, url, content): words = content.split() for word in words: add_to_index(index, word, url) def add_to_index(index, keyword, url):
64
64
36
10
54
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
add_to_index
add_to_index
227
231
227
227
ca2b2067f8026241c0a70d71bcf0883b42c18b9f
bigcode/the-stack
train
99a8f92358dfcf65970f6053
train
function
def ordered_search(index, ranks, keyword): urls = lookup(index, keyword) if not urls: return None dict = {} for url in urls: dict[ranks[url]] = url lranks = [] for i in dict.keys(): lranks.append(i) lranks = quicksort(lranks) res = [] for rank in lranks: ...
def ordered_search(index, ranks, keyword):
urls = lookup(index, keyword) if not urls: return None dict = {} for url in urls: dict[ranks[url]] = url lranks = [] for i in dict.keys(): lranks.append(i) lranks = quicksort(lranks) res = [] for rank in lranks: res.append(dict[rank]) return re...
sorted right sub-list. # For simplicity, use the first element in the list as your pivot element (this # is not usually a good choice, since it means if the input list is already # nearly sorted, the actual work will be much worse than expected). def ordered_search(index, ranks, keyword):
64
64
95
9
55
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
ordered_search
ordered_search
38
56
38
38
b0ada1b923d2a610effee4926a7c10a9e502ad73
bigcode/the-stack
train
1df5cc2635bd075645a5ed9c
train
function
def compute_ranks(graph): d = 0.8 # damping factor numloops = 10 ranks = {} npages = len(graph) for page in graph: ranks[page] = 1.0 / npages for i in range(0, numloops): newranks = {} for page in graph: newrank = (1 - d) / npages for node in gra...
def compute_ranks(graph):
d = 0.8 # damping factor numloops = 10 ranks = {} npages = len(graph) for page in graph: ranks[page] = 1.0 / npages for i in range(0, numloops): newranks = {} for page in graph: newrank = (1 - d) / npages for node in graph: if pag...
: content = get_page(page) add_page_to_index(index, page, content) outlinks = get_all_links(content) graph[page] = outlinks union(tocrawl, outlinks) crawled.append(page) return index, graph def compute_ranks(graph):
64
64
145
6
57
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
compute_ranks
compute_ranks
255
273
255
255
08accf0a050a0934e8fdfab8a54a91e3f60258f1
bigcode/the-stack
train
707f4cc3367bc83387f3024e
train
function
def union(a, b): for e in b: if e not in a: a.append(e)
def union(a, b):
for e in b: if e not in a: a.append(e)
return url, end_quote def get_all_links(page): links = [] while True: url, endpos = get_next_target(page) if url: links.append(url) page = page[endpos:] else: break return links def union(a, b):
64
64
24
6
57
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
union
union
217
220
217
217
6b6e30db40956c79ac861a058740a99b84e9293b
bigcode/the-stack
train
c3f5c732fd3faa006441da14
train
function
def crawl_web(seed): # returns index, graph of inlinks tocrawl = [seed] crawled = [] graph = {} # <url>, [list of pages it links to] index = {} while tocrawl: page = tocrawl.pop() if page not in crawled: content = get_page(page) add_page_to_index(index, page,...
def crawl_web(seed): # returns index, graph of inlinks
tocrawl = [seed] crawled = [] graph = {} # <url>, [list of pages it links to] index = {} while tocrawl: page = tocrawl.pop() if page not in crawled: content = get_page(page) add_page_to_index(index, page, content) outlinks = get_all_links(content)...
if keyword in index: index[keyword].append(url) else: index[keyword] = [url] def lookup(index, keyword): if keyword in index: return index[keyword] else: return None def crawl_web(seed): # returns index, graph of inlinks
64
64
124
14
49
dmitry-izmerov/Udacity-Intro-to-computer-science
Lesson06/Only a Little Lucky.py
Python
crawl_web
crawl_web
239
253
239
239
eb5a0519f0572a07419213ed88fe4d9a8f6e84f2
bigcode/the-stack
train
02f4f211dee5446672d27d7b
train
class
class TestPagination: def test_pagination_no_limit_raises_error(self, session): with pytest.raises(RQLQueryError): session.query(User).rql("").rql_paginate() def test_pagination_no_filter(self, session): res = session.query(User).rql("limit(10)").rql_paginate() page, previou...
class TestPagination:
def test_pagination_no_limit_raises_error(self, session): with pytest.raises(RQLQueryError): session.query(User).rql("").rql_paginate() def test_pagination_no_filter(self, session): res = session.query(User).rql("limit(10)").rql_paginate() page, previous_page, next_page, tot...
import pytest from fixtures import User from rqlalchemy import RQLQueryError class TestPagination:
22
256
915
4
17
pjwerneck/rqlalchemy
tests/test_pagination.py
Python
TestPagination
TestPagination
7
110
7
7
e666704e6ec074796f17489f115a50a2cae6215d
bigcode/the-stack
train
65cbd486712cff6a0b2d5c35
train
function
def covid19(): res = requests.get('https://api.covid19india.org/data.json') result = res.json() data = result['statewise'] for stateinfo in data: if stateinfo['state'] == 'Maharashtra': return stateinfo
def covid19():
res = requests.get('https://api.covid19india.org/data.json') result = res.json() data = result['statewise'] for stateinfo in data: if stateinfo['state'] == 'Maharashtra': return stateinfo
er_io_api_key}&symbols=USD,INR&format=1') result = res.json() inr = result['rates']['INR'] usd = result['rates']['USD'] usd_to_inr = inr/usd return usd_to_inr def covid19():
64
64
60
4
59
vinodnimbalkar/BotMarathi
data.py
Python
covid19
covid19
63
69
63
63
6792514c15d0a797f42c747b7d2817e1147ffb05
bigcode/the-stack
train
6daeb35676ef8370fd689889
train
function
def marathiNews(): #specify the url of marathi news website url = "http://lokmat.com/" soup = get_source_code(url) news = soup.find('ul', class_='live-news-list') for i in news.findAll('li'): data = i.text return data
def marathiNews(): #specify the url of marathi news website
url = "http://lokmat.com/" soup = get_source_code(url) news = soup.find('ul', class_='live-news-list') for i in news.findAll('li'): data = i.text return data
import requests from bs4 import BeautifulSoup from datetime import date import pandas as pd import random from credentials import fixer_io_api_key def marathiNews(): #specify the url of marathi news website
48
64
70
17
30
vinodnimbalkar/BotMarathi
data.py
Python
marathiNews
marathiNews
8
16
8
9
947a297ac26ba8c2c9ca59625666beca4d01b187
bigcode/the-stack
train
e9efe4f1cafa9965badb9294
train
function
def dinVishesh(): d = date.today().strftime('%d-%B').lstrip("0").replace(" 0", " ").lower() #specify the url of dinvishesh website url = f"http://www.dinvishesh.com/{d}-janm/" #जन्म तारखे नुसार soup = get_source_code(url) vishesh_content = soup.find('div', class_='td-post-content') vishesh = vis...
def dinVishesh():
d = date.today().strftime('%d-%B').lstrip("0").replace(" 0", " ").lower() #specify the url of dinvishesh website url = f"http://www.dinvishesh.com/{d}-janm/" #जन्म तारखे नुसार soup = get_source_code(url) vishesh_content = soup.find('div', class_='td-post-content') vishesh = vishesh_content.find_...
.csv", "r") data = df.iloc[num,0] return data def graffiti(): num = random.randrange(1,365) df = pd.read_csv("graffiti.csv", "r") data = df.iloc[num,0] return data def dinVishesh():
64
64
124
6
57
vinodnimbalkar/BotMarathi
data.py
Python
dinVishesh
dinVishesh
37
45
37
37
3313b620497da70856dd5605444811d1e0d21e1b
bigcode/the-stack
train
8adeb5c6b445d007714b321d
train
function
def suvichar(): num = random.randrange(1,365) df = pd.read_csv("suvichar.csv", "r") data = df.iloc[num,0] return data
def suvichar():
num = random.randrange(1,365) df = pd.read_csv("suvichar.csv", "r") data = df.iloc[num,0] return data
return data def tarikh(): #specify the url of marathi date website url = "http://lokmat.com/" soup = get_source_code(url) tdate = soup.find('p', class_='today-date') return tdate.text def suvichar():
64
64
44
5
58
vinodnimbalkar/BotMarathi
data.py
Python
suvichar
suvichar
25
29
25
25
62adbb12862cb47f9b7972bc8614e895865d730d
bigcode/the-stack
train
ae47ff2574f0199e1059e00c
train
function
def bazar(): url = "http://marathi.webdunia.com/" soup = get_source_code(url) business = soup.find('div', class_='business') for i in business.findAll('span'): data = i.text return data
def bazar():
url = "http://marathi.webdunia.com/" soup = get_source_code(url) business = soup.find('div', class_='business') for i in business.findAll('span'): data = i.text return data
जन्म तारखे नुसार soup = get_source_code(url) vishesh_content = soup.find('div', class_='td-post-content') vishesh = vishesh_content.find_all('p') for data in vishesh: yield data.text def bazar():
64
64
58
4
59
vinodnimbalkar/BotMarathi
data.py
Python
bazar
bazar
47
53
47
47
75505f5429a36b1cd2cf0f0fbb5c3723a24cf24e
bigcode/the-stack
train
1042e3a841898b81ec74234f
train
function
def tarikh(): #specify the url of marathi date website url = "http://lokmat.com/" soup = get_source_code(url) tdate = soup.find('p', class_='today-date') return tdate.text
def tarikh(): #specify the url of marathi date website
url = "http://lokmat.com/" soup = get_source_code(url) tdate = soup.find('p', class_='today-date') return tdate.text
://lokmat.com/" soup = get_source_code(url) news = soup.find('ul', class_='live-news-list') for i in news.findAll('li'): data = i.text return data def tarikh(): #specify the url of marathi date website
64
64
55
16
47
vinodnimbalkar/BotMarathi
data.py
Python
tarikh
tarikh
18
23
18
19
5ce4988151f7d5470b8a8d0b081e21019cdf7e37
bigcode/the-stack
train
905a1ce50bd978a7ae39d1da
train
function
def get_source_code(url): page = requests.get(url) result = BeautifulSoup(page.text, 'html.parser') return result
def get_source_code(url):
page = requests.get(url) result = BeautifulSoup(page.text, 'html.parser') return result
19(): res = requests.get('https://api.covid19india.org/data.json') result = res.json() data = result['statewise'] for stateinfo in data: if stateinfo['state'] == 'Maharashtra': return stateinfo def get_source_code(url):
64
64
29
6
57
vinodnimbalkar/BotMarathi
data.py
Python
get_source_code
get_source_code
71
74
71
71
dfcd533458b001c05d2405a2073064c43f8136a2
bigcode/the-stack
train
d212777e49802ca3a271ae91
train
function
def euro_to_inr(): res = requests.get(f'http://data.fixer.io/api/latest?access_key={fixer_io_api_key}&symbols=USD,INR&format=1') result = res.json() inr = result['rates']['INR'] usd = result['rates']['USD'] usd_to_inr = inr/usd return usd_to_inr
def euro_to_inr():
res = requests.get(f'http://data.fixer.io/api/latest?access_key={fixer_io_api_key}&symbols=USD,INR&format=1') result = res.json() inr = result['rates']['INR'] usd = result['rates']['USD'] usd_to_inr = inr/usd return usd_to_inr
def bazar(): url = "http://marathi.webdunia.com/" soup = get_source_code(url) business = soup.find('div', class_='business') for i in business.findAll('span'): data = i.text return data def euro_to_inr():
64
64
86
6
57
vinodnimbalkar/BotMarathi
data.py
Python
euro_to_inr
euro_to_inr
55
61
55
55
4bc8a4d8d579353728e4da8f8131d03778cf9bb0
bigcode/the-stack
train
3ed38337c325d6d8dd552a37
train
function
def graffiti(): num = random.randrange(1,365) df = pd.read_csv("graffiti.csv", "r") data = df.iloc[num,0] return data
def graffiti():
num = random.randrange(1,365) df = pd.read_csv("graffiti.csv", "r") data = df.iloc[num,0] return data
soup.find('p', class_='today-date') return tdate.text def suvichar(): num = random.randrange(1,365) df = pd.read_csv("suvichar.csv", "r") data = df.iloc[num,0] return data def graffiti():
64
64
40
3
60
vinodnimbalkar/BotMarathi
data.py
Python
graffiti
graffiti
31
35
31
31
a7d5e8ed3bd47355f082857822971e76a2328505
bigcode/the-stack
train
077b46406213da5574598dc5
train
function
def greeting(msg): print(str(msg))
def greeting(msg):
print(str(msg))
__author__ = "dmm7aj" def greeting(msg):
14
64
9
4
10
DerekMcMahon/cs3240-labdemo
helper.py
Python
greeting
greeting
3
4
3
3
9b71bc413c544beb1ed755b181cc60875cda8538
bigcode/the-stack
train
9fe5a8f6eaa3d56cf3ba72ff
train
class
class Migration(migrations.Migration): dependencies = [ ('converter', '0002_auto_20150608_1943'), ] operations = [ migrations.AlterField( model_name='transformation', name='arguments', field=models.TextField( default='', help_tex...
class Migration(migrations.Migration):
dependencies = [ ('converter', '0002_auto_20150608_1943'), ] operations = [ migrations.AlterField( model_name='transformation', name='arguments', field=models.TextField( default='', help_text='Enter the arguments for the ' ...
from django.db import models, migrations import mayan.apps.common.validators class Migration(migrations.Migration):
22
81
271
7
14
CMU-313/fall-2021-hw2-451-unavailable-for-legal-reasons
mayan/apps/converter/migrations/0003_auto_20150704_0731.py
Python
Migration
Migration
6
45
6
6
cf4f72c84a3c2624c918d39aa99e5ba42f8bf7a1
bigcode/the-stack
train
70123688cad4b13b6b67057c
train
function
def testConnection(): try: mydb = mysql.connector.connect( host="scaler-db-mysql.submit-scaler.svc.cluster.local", #port="3306", user=os.environ['SCALER_MYSQL_USER'], passwd=os.environ['SCALER_MYSQL_PASSWORD'] , database="scalerdb" ) print(mydb) mycursor = mydb.cursor() ...
def testConnection():
try: mydb = mysql.connector.connect( host="scaler-db-mysql.submit-scaler.svc.cluster.local", #port="3306", user=os.environ['SCALER_MYSQL_USER'], passwd=os.environ['SCALER_MYSQL_PASSWORD'] , database="scalerdb" ) print(mydb) mycursor = mydb.cursor() mycursor.execute("...
host="scaler-db-mysql.submit-scaler.svc.cluster.local", #port='3306', user=os.environ['SCALER_MYSQL_USER'], passwd=os.environ['SCALER_MYSQL_PASSWORD'], database="scalerdb" ) return mydb def testConnection():
64
64
154
4
59
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
testConnection
testConnection
16
43
16
16
86476eaaf78f93820e3c5d769e1d11cc413fa6d0
bigcode/the-stack
train
8d80414597f606eac494f8a6
train
function
def isRemovable(machineId): mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("SELECT removable FROM ClusterInfo WHERE machineId = %s") val = (machineId,) mycursor.execute(sql, val) for (removable) in mycursor: mycursor.close() mydb.close() return int(removable[0]) == 1 mycursor.cl...
def isRemovable(machineId):
mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("SELECT removable FROM ClusterInfo WHERE machineId = %s") val = (machineId,) mycursor.execute(sql, val) for (removable) in mycursor: mycursor.close() mydb.close() return int(removable[0]) == 1 mycursor.close() mydb.close() retur...
) VALUES (%s, %s, %s, %s, %s)' val = (machineId, unitId, nodeName, removable, active) mycursor.execute(sql, val) mydb.commit() mycursor.close() mydb.close() def isRemovable(machineId):
64
64
100
7
57
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
isRemovable
isRemovable
59
73
59
59
89e2ff688328668d13ecdb3e173c527132d7b9de
bigcode/the-stack
train
157bb3da1d6546613c6a33a5
train
function
def addMetadata(machineId, instanceId, addresses): mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("UPDATE ClusterInfo SET instanceId=%s, addresses=%s WHERE machineId = %s") val = (instanceId, addresses, machineId) mycursor.execute(sql, val) mydb.commit() mycursor.close() mydb.close()
def addMetadata(machineId, instanceId, addresses):
mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("UPDATE ClusterInfo SET instanceId=%s, addresses=%s WHERE machineId = %s") val = (instanceId, addresses, machineId) mycursor.execute(sql, val) mydb.commit() mycursor.close() mydb.close()
val = (machineId,) mycursor.execute(sql, val) for (removable) in mycursor: mycursor.close() mydb.close() return True mycursor.close() mydb.close() return False def addMetadata(machineId, instanceId, addresses):
64
64
85
11
52
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
addMetadata
addMetadata
125
135
125
125
e70e07d49031f4f1ffeb8bd59919df84289bfa3c
bigcode/the-stack
train
7b2d5a345cdd770fdb16a449
train
function
def updateMachineMetadata(machineId, addresses, instanceId): if exists(machineId): addMetadata(machineId, instanceId, addresses) else: insertCreatedWorker(machineId, "", "", 0, 1)
def updateMachineMetadata(machineId, addresses, instanceId):
if exists(machineId): addMetadata(machineId, instanceId, addresses) else: insertCreatedWorker(machineId, "", "", 0, 1)
() ret = "" for x in myresult: for value in x: ret = ret + " " + str(value) ret = ret + "\n" mycursor.close() mydb.close() return ret def updateMachineMetadata(machineId, addresses, instanceId):
64
64
47
12
51
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
updateMachineMetadata
updateMachineMetadata
103
107
103
103
4bc6191607589319957493e79abb1eb2a5834504
bigcode/the-stack
train
58e0d832120ef95072999695
train
function
def listClusterInfo(): mydb = getMysqlConnection() print(mydb) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM ClusterInfo") myresult = mycursor.fetchall() ret = "" for x in myresult: for value in x: ret = ret + " " + str(value) ret = ret + "\n" mycursor.close() mydb.close(...
def listClusterInfo():
mydb = getMysqlConnection() print(mydb) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM ClusterInfo") myresult = mycursor.fetchall() ret = "" for x in myresult: for value in x: ret = ret + " " + str(value) ret = ret + "\n" mycursor.close() mydb.close() return ret
db = getMysqlConnection() mycursor = mydb.cursor() sql = ("DELETE FROM ClusterInfo WHERE machineId = %s") val = (machineId,) mycursor.execute(sql, val) mydb.commit() mycursor.close() mydb.close() def listClusterInfo():
64
64
96
5
59
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
listClusterInfo
listClusterInfo
85
101
85
85
50dd5d0bbb1d1d3606ff5c825afea499aa3621ab
bigcode/the-stack
train
8f9b3fb73568734e10157903
train
function
def getMysqlConnection(): mydb = mysql.connector.connect( host="scaler-db-mysql.submit-scaler.svc.cluster.local", #port='3306', user=os.environ['SCALER_MYSQL_USER'], passwd=os.environ['SCALER_MYSQL_PASSWORD'], database="scalerdb" ) return mydb
def getMysqlConnection():
mydb = mysql.connector.connect( host="scaler-db-mysql.submit-scaler.svc.cluster.local", #port='3306', user=os.environ['SCALER_MYSQL_USER'], passwd=os.environ['SCALER_MYSQL_PASSWORD'], database="scalerdb" ) return mydb
import mysql.connector import os #scaler-db-mysql.submit-scaler.svc.cluster.local def getMysqlConnection():
26
64
74
5
20
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
getMysqlConnection
getMysqlConnection
5
14
5
5
3dbc9da8b78b5d9dbc657388462fcd2853fc70d3
bigcode/the-stack
train
e233f07b9370be1b4876287d
train
function
def deleteMachine(machineId): mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("DELETE FROM ClusterInfo WHERE machineId = %s") val = (machineId,) mycursor.execute(sql, val) mydb.commit() mycursor.close() mydb.close()
def deleteMachine(machineId):
mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("DELETE FROM ClusterInfo WHERE machineId = %s") val = (machineId,) mycursor.execute(sql, val) mydb.commit() mycursor.close() mydb.close()
(machineId,) mycursor.execute(sql, val) for (removable) in mycursor: mycursor.close() mydb.close() return int(removable[0]) == 1 mycursor.close() mydb.close() return False def deleteMachine(machineId):
64
64
67
6
57
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
deleteMachine
deleteMachine
75
83
75
75
f6ce528ad7dc5e00dae4730a5e21305a677bd5b8
bigcode/the-stack
train
cff785581c0cd11a476a04e8
train
function
def exists(machineId): mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("SELECT machineId FROM ClusterInfo WHERE machineId = %s") val = (machineId,) mycursor.execute(sql, val) for (removable) in mycursor: mycursor.close() mydb.close() return True mycursor.close() mydb.close() ...
def exists(machineId):
mydb = getMysqlConnection() mycursor = mydb.cursor() sql = ("SELECT machineId FROM ClusterInfo WHERE machineId = %s") val = (machineId,) mycursor.execute(sql, val) for (removable) in mycursor: mycursor.close() mydb.close() return True mycursor.close() mydb.close() return False
cursor.close() mydb.close() return ret def updateMachineMetadata(machineId, addresses, instanceId): if exists(machineId): addMetadata(machineId, instanceId, addresses) else: insertCreatedWorker(machineId, "", "", 0, 1) def exists(machineId):
64
64
91
5
59
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
exists
exists
109
123
109
109
a532cd3336677bfefa96a8e00325cd875572f3c7
bigcode/the-stack
train
14a355493eb64e572c4b4cb1
train
function
def insertCreatedWorker(machineId, unitId, nodeName, removable, active): mydb = getMysqlConnection() print(mydb) mycursor = mydb.cursor() sql = 'INSERT INTO ClusterInfo (machineId, unitId, nodeName, removable, active) VALUES (%s, %s, %s, %s, %s)' val = (machineId, unitId, nodeName, removable, active) mycur...
def insertCreatedWorker(machineId, unitId, nodeName, removable, active):
mydb = getMysqlConnection() print(mydb) mycursor = mydb.cursor() sql = 'INSERT INTO ClusterInfo (machineId, unitId, nodeName, removable, active) VALUES (%s, %s, %s, %s, %s)' val = (machineId, unitId, nodeName, removable, active) mycursor.execute(sql, val) mydb.commit() mycursor.close() mydb.close()
print(x) count = count + 1 mycursor.close() mydb.close() if count == 0: return False else: return True except: return False def insertCreatedWorker(machineId, unitId, nodeName, removable, active):
64
64
116
17
46
leanaiorg/leanaistack
modules/PythonScaler/ScalerDbConnector.py
Python
insertCreatedWorker
insertCreatedWorker
46
57
46
46
834971a349b96b2ca3926dcc9154bb011554eba9
bigcode/the-stack
train
0ff0d82f9c93077ea6e51141
train
function
def invert_array_input(in_ar, nan_value, max_value=None): """ DO NOT USE AS THIS DOES NOT PROPERLY SCALE FLIPPED VALUES: OLD VALUES 2,3 WOULD BECOME 2,1 WITH THIS METHOD. WHERE 2,3 IMPLICATE THAT CELLS WITH 2 ARE FLIPPED 1.5x LESS THAN THOSE WITH VALUE 3, THE NEW 2, 1 WOULD FLIP IT 2x AS OFT...
def invert_array_input(in_ar, nan_value, max_value=None):
""" DO NOT USE AS THIS DOES NOT PROPERLY SCALE FLIPPED VALUES: OLD VALUES 2,3 WOULD BECOME 2,1 WITH THIS METHOD. WHERE 2,3 IMPLICATE THAT CELLS WITH 2 ARE FLIPPED 1.5x LESS THAN THOSE WITH VALUE 3, THE NEW 2, 1 WOULD FLIP IT 2x AS OFTEN Input arrays :in_ar: higher numbers me...
# -*- coding: utf-8 -*- import numpy as np import math import datetime def invert_array_input(in_ar, nan_value, max_value=None):
33
116
389
14
18
jdegene/GridGrowth
gridgrowth.py
Python
invert_array_input
invert_array_input
7
46
7
7
e00b3281b361e872cbec93b9299c50c0790d90ce
bigcode/the-stack
train
cc4fdb496eb28a3e56df0a7f
train
function
def falloff(func_type, dist, value, func_weight=None): """ If called, will reduce an input :val: depending on its distance from original kernel Args: :func_type: function name by which to reduce input value. Can be linear, exp, log :func_weight: optional value if func_ty...
def falloff(func_type, dist, value, func_weight=None):
""" If called, will reduce an input :val: depending on its distance from original kernel Args: :func_type: function name by which to reduce input value. Can be linear, exp, log :func_weight: optional value if func_type accepts one (eg 2 for linear i...
] + in_coord[1]-1 # only return valid coordinates, do nothing if coordinates would be negative if new_coord_0 >= 0 and new_coord_1 >= 0 and new_coord_0 <= max_x and new_coord_1 <= max_y: return (new_coord_0, new_coord_1) def falloff(func_type, dist, value, func_weight=None):
86
86
287
14
72
jdegene/GridGrowth
gridgrowth.py
Python
falloff
falloff
499
535
499
499
f6895c82ccdcee84d3321d017a74621f402f6495
bigcode/the-stack
train
9c5c3fe7a7d3ffa600034979
train
function
def local_coord_to_global(in_coord, center_coord, max_x, max_y): """ Converts a coordinate from a 3x3 grid into coordinate from large grid Args: :in_coord: tuple of local coordinates to convert to global :center:coord: center coordinate of 3x3 grid cell in global coordinate system ...
def local_coord_to_global(in_coord, center_coord, max_x, max_y):
""" Converts a coordinate from a 3x3 grid into coordinate from large grid Args: :in_coord: tuple of local coordinates to convert to global :center:coord: center coordinate of 3x3 grid cell in global coordinate system :max_x/y: maxium x / y value the global coordinates c...
return allowed_list[0] elif len(allowed_list) > 1: min_val_index = allowed_weights_list.index(min(allowed_weights_list)) return allowed_list[min_val_index] else: return def local_coord_to_global(in_coord, center_coord, max_x, max_y):
63
64
213
17
45
jdegene/GridGrowth
gridgrowth.py
Python
local_coord_to_global
local_coord_to_global
476
496
476
476
1ee2e34299e37f7039d0559a8a3cb315efc20dca
bigcode/the-stack
train
d489153ba4b3a56f88a9169b
train
function
def buffer_kernels(in_ar, org_ar, nan_value, in_name_ar, in_dist_ar, by=None, falloff_type=None, falloff_weight=None, in_inherit_ar=None): """ Add a buffer around initial kernels to force immediate vicinty to belong to kernels Args: :by: number of pixels to buffer in e...
def buffer_kernels(in_ar, org_ar, nan_value, in_name_ar, in_dist_ar, by=None, falloff_type=None, falloff_weight=None, in_inherit_ar=None):
""" Add a buffer around initial kernels to force immediate vicinty to belong to kernels Args: :by: number of pixels to buffer in each directions :in_ar: input array to write buffers to :org_ar: array that tracks original kernel strength :nan_value: ...
a 3x3 grid that have a specific value Args: :in_3x3_ar: Input 3x3 array :val: Value to check locations for :include_center: if false, center coordinate is omitted even if it has :val: Returns: list of tuples. Each tuple is a coordinate pair Raises: "...
220
220
736
41
178
jdegene/GridGrowth
gridgrowth.py
Python
buffer_kernels
buffer_kernels
564
644
564
565
5de53776c0b34810e4077de52e2c26bb3a94a689
bigcode/the-stack
train
20b1e4e41321b1be30adbeef
train
class
class GridBuilder(): """ Main class to handle initiation of the grid and stepping through the epochs """ def __init__(self, t_ar, t_names_ar=None, cost_ar=None, terrain_ar=None, weight_ar=None, terrain_rules_dict = None, nan_value=None, weight_method = "add", cost_method = "add", ...
class GridBuilder():
""" Main class to handle initiation of the grid and stepping through the epochs """ def __init__(self, t_ar, t_names_ar=None, cost_ar=None, terrain_ar=None, weight_ar=None, terrain_rules_dict = None, nan_value=None, weight_method = "add", cost_method = "add", buffer_k...
)) # only set if distance within set limit if dist <= by: #only set values if no other value has been set in place # OR if value already present, set value with smaller dist ...
256
256
3,060
4
251
jdegene/GridGrowth
gridgrowth.py
Python
GridBuilder
GridBuilder
652
952
652
652
727122146b6e1fdfcf7e9123e8724c50f8ea316d
bigcode/the-stack
train
78bc5edf835c310638343b79
train
function
def get_value_locs_in_3x3(in_3x3_ar, val, include_center = False): """ Returns a list of tuple coordintaes in a 3x3 grid that have a specific value Args: :in_3x3_ar: Input 3x3 array :val: Value to check locations for :include_center: if false, center coordinate is omitted even...
def get_value_locs_in_3x3(in_3x3_ar, val, include_center = False):
""" Returns a list of tuple coordintaes in a 3x3 grid that have a specific value Args: :in_3x3_ar: Input 3x3 array :val: Value to check locations for :include_center: if false, center coordinate is omitted even if it has :val: Returns: list of tuples. Each tup...
_weight) else: raise ValueError(f"Falloff function must be linear, exp or log but was {func_type}") return max(0, round(ret_val) ) def get_value_locs_in_3x3(in_3x3_ar, val, include_center = False):
64
64
214
24
40
jdegene/GridGrowth
gridgrowth.py
Python
get_value_locs_in_3x3
get_value_locs_in_3x3
538
561
538
538
79d17b4c5e4f7c604a2f96ac9e157258575e5271
bigcode/the-stack
train
527abb0400e5b81493f670ce
train
function
def build_transition_rules_full(trans_rules_dict=None, terrain_ar=None): """ Takes handwritten small dictionary of rules as input and generates complete dictionary of all possible transitions and their validity Args: :trans_rules_dict: small dictionary of 'only_allowed', 'never_allowed', '...
def build_transition_rules_full(trans_rules_dict=None, terrain_ar=None):
""" Takes handwritten small dictionary of rules as input and generates complete dictionary of all possible transitions and their validity Args: :trans_rules_dict: small dictionary of 'only_allowed', 'never_allowed', 'takes_precedence' :terrain_ar: terrain_array with all valid...
max_in = np.nanmax(in_ar) max_cost = 0 if in_cost_ar is None else np.nanmax(in_cost_ar) max_weight = 0 if in_weight_ar is None else np.nanmax(in_weight_ar) if cost_method == "add": if weight_method == "add": max_val = max_in + max_cost + max_weight elif weight_method == "mu...
243
243
813
14
229
jdegene/GridGrowth
gridgrowth.py
Python
build_transition_rules_full
build_transition_rules_full
254
330
254
254
ef32f8826b832c500db0b6ebb11d8a92af64befb
bigcode/the-stack
train
b739f2e5e9d41dbbf1eddd79
train
class
class GeoGridBuilder(GridBuilder): """ Inherits from main class but can handle initiation and output of georeferenced rasters. All inputs are expected to be GeoTiffs if used (= no mixing between arrays & geotiffs) OSGEO / GDAL libraries must be installed to use this. """ def __in...
class GeoGridBuilder(GridBuilder):
""" Inherits from main class but can handle initiation and output of georeferenced rasters. All inputs are expected to be GeoTiffs if used (= no mixing between arrays & geotiffs) OSGEO / GDAL libraries must be installed to use this. """ def __init__(self, t_ar_tiff_fp, t_names_ti...
.num_last_done_coords_list)) == 1: break_bc_no_change = True if how == 'full': if len(self.current_coords_set) == 0 or break_bc_no_change is True: break elif how == 'iteration': if (self.iterati...
255
256
867
7
249
jdegene/GridGrowth
gridgrowth.py
Python
GeoGridBuilder
GeoGridBuilder
955
1,027
955
955
65f7e3bbc5bdf0645bdd7baf1209701fd60a48d7
bigcode/the-stack
train
f2899c0de9e71c2b8c541224
train
function
def get_possible_max_value(in_ar, nan_val, in_cost_ar=None, in_weight_ar=None, cost_method="add", weight_method="add"): """ Calculate the maximum value possbile when all weights are combined. Necessary to correctly scale all values for steps. Args: :i...
def get_possible_max_value(in_ar, nan_val, in_cost_ar=None, in_weight_ar=None, cost_method="add", weight_method="add"):
""" Calculate the maximum value possbile when all weights are combined. Necessary to correctly scale all values for steps. Args: :in_ar: initial array with initial central kernels :in_cost_ar: cost array :in_weight_ar: weights array ...
: for i, loc in enumerate(direction_list): ar[loc_swap_dict[loc]] = ar[loc_swap_dict[loc]] + weights[i] else: for loc in direction_list: ar[loc_swap_dict[loc]] = ar[loc_swap_dict[loc]] + weights # reshape to 2D and return ar2D = ar.reshape((3,3)) re...
127
127
424
33
93
jdegene/GridGrowth
gridgrowth.py
Python
get_possible_max_value
get_possible_max_value
203
251
203
204
b5cb1dedc3ff9289f8baf55c46a446b9e906fc12
bigcode/the-stack
train
5dde147057596babc69d72f7
train
function
def create_flip_dict(vals_list): """ Flip values in a list highest to 1 and lowest to former max value while retaining their relative scale Due to required INT as outputs, 1 is scaled up by order of max value, so correct nuances are accounted for If values [2,3,20] occur in an array, they are invert...
def create_flip_dict(vals_list):
""" Flip values in a list highest to 1 and lowest to former max value while retaining their relative scale Due to required INT as outputs, 1 is scaled up by order of max value, so correct nuances are accounted for If values [2,3,20] occur in an array, they are invert scaled to [1000, 666, 100] ...
be of integer type but {in_ar.dtype} was given") out_ar = np.ma.masked_equal(in_ar, nan_value) if max_value is None: max_value = out_ar.max() out_ar = abs(out_ar - max_value) + 1 out_ar = out_ar.filled(nan_value) return out_ar def create_flip_dict(vals_list):
86
86
288
7
78
jdegene/GridGrowth
gridgrowth.py
Python
create_flip_dict
create_flip_dict
48
75
48
48
ec983f41128b25299c90934dfe44ca54fa68016f
bigcode/the-stack
train
3baca3671cbaf2030481681c
train
function
def create_3x3_weights(direction_list=[], weights=1, neutral_value=0): """ Creates a 3x3 matrix of the direction to push into. Imagine this as giving a wind direction. If wind is blowing North, upper cells should populated with a higher chance from the South. -> Direction ...
def create_3x3_weights(direction_list=[], weights=1, neutral_value=0):
""" Creates a 3x3 matrix of the direction to push into. Imagine this as giving a wind direction. If wind is blowing North, upper cells should populated with a higher chance from the South. -> Direction gives the wind direction BUT the weight is increased on the ...
are nan, return None if np.all(np.isnan(null_ar)): return coord_list= [] # fetch max values, set max values to nan until all of array is nan while not np.all(np.isnan(null_ar)): max_value = np.nanmax(null_ar) # returns 2 arrays, each array represents ...
183
183
610
19
163
jdegene/GridGrowth
gridgrowth.py
Python
create_3x3_weights
create_3x3_weights
141
200
141
141
08f5260ab52d9df7ac5cbdcaa26807bd61f81c4e
bigcode/the-stack
train
60c85d375e8a93dda8a2d47d
train
function
def get_3x3_array(in_array, in_coords, nan_value): """ Get smaller 3x3 array from larger array. Takes care of edge cases (literally) where normal slicing would not yield a 3x3 array when center coord is on the edge Args: :in_array: array to slice 3x3 array from :in_coords: coords f...
def get_3x3_array(in_array, in_coords, nan_value):
""" Get smaller 3x3 array from larger array. Takes care of edge cases (literally) where normal slicing would not yield a 3x3 array when center coord is on the edge Args: :in_array: array to slice 3x3 array from :in_coords: coords from large array :nan_value: used to pad sma...
to_terrain in trans_rules_dict['limit_into']: out_dict[from_terrain][to_terrain] = 0 else: out_dict[from_terrain][to_terrain] = 1 # check if never_allowed exist. Can be single value or list of values. If single value ...
256
256
873
16
239
jdegene/GridGrowth
gridgrowth.py
Python
get_3x3_array
get_3x3_array
332
388
332
332
df529f56284a642d54ffb9883a75aff674b52e26
bigcode/the-stack
train
bf15917759887cff74e183c0
train
function
def determine_center_values(in_3x3_ar, step, nan_value): """ Determines which values in the 3x3 grid will set the center value. Only values that are not :nan_value: and are >= :step: are eligible. Center value is explicitely left included to to allow cases when a value can be altered ag...
def determine_center_values(in_3x3_ar, step, nan_value):
""" Determines which values in the 3x3 grid will set the center value. Only values that are not :nan_value: and are >= :step: are eligible. Center value is explicitely left included to to allow cases when a value can be altered again after being set. If two or more possible outp...
e.g. converting numbers 1...20 will lead to # 20=1, 19=1.0526.... As INT are needed, the order determines by how much the values # must be shifted so they are unique: 20 is order 2 -> shift by 2 decimmal places -> 1.0526 = 105 order = len(str(max_val)) correct_fact = 10**order for val in vals...
165
165
550
16
148
jdegene/GridGrowth
gridgrowth.py
Python
determine_center_values
determine_center_values
77
138
77
77
dd786a92c3991d5bb8ed6113a434f10b5baa4874
bigcode/the-stack
train
25f3776aac11502f0cdbd667
train
function
def transition_rules_outcome(full_rules_dict=None, strength_3x3_ar=None, terrain_ar=None, pos_coords_list=[], glob_center_coord=None, max_distance=None, ...
def transition_rules_outcome(full_rules_dict=None, strength_3x3_ar=None, terrain_ar=None, pos_coords_list=[], glob_center_coord=None, max_distance=None, ...
""" Checks if transition in full_rules_dict is 0 (not allowed), 1 (allowed) or 2 (give precedence) 0 transitions are never returned 1 transitions only if no 2 exists 2 transitions always take precedence If several 1s or severl 2s exist, the one with greater strength is chosen (or simply first ...
top elif in_coords[0] == 0 and in_coords[1] == in_array.shape[1]-1: out_arr = np.pad(out_arr, pad_width=[(1,0),(0,1)], mode='constant', constant_values=nan_value) # lower left corner, pad left and below elif in_coords[0] == in_array.shape[0]-1 and in_coords[1] == 0: out_...
253
253
846
50
202
jdegene/GridGrowth
gridgrowth.py
Python
transition_rules_outcome
transition_rules_outcome
390
473
390
396
41eeb6b07f59be27dcd7909581e0eb19acdb7d2d
bigcode/the-stack
train
497ac202a92bb691feb36807
train
function
def calculate_distance(coords1, coords2): """ Calulates distance in cells between two coordinate pairs """ dist = math.sqrt(abs(coords1[0] - coords2[0])**2 + abs(coords1[1] - coords2[1])**2) return dist
def calculate_distance(coords1, coords2):
""" Calulates distance in cells between two coordinate pairs """ dist = math.sqrt(abs(coords1[0] - coords2[0])**2 + abs(coords1[1] - coords2[1])**2) return dist
name in_dist_ar[x,y] = dist buffered_coords_set.add( (x,y) ) in_inherit_ar[x,y] = coords return out_ar, org_ar, in_name_ar, in_dist_ar, buffered_coords_set def calculate_distance(coords1, coords2):
63
64
61
9
53
jdegene/GridGrowth
gridgrowth.py
Python
calculate_distance
calculate_distance
646
650
646
646
fd906b944fd6b8c8d7c1dbf274d7bd05b7e1002b
bigcode/the-stack
train
d8b6bb7967b298adf3daa7e1
train
function
def parse_description(s, value_type, description=None): """ s can be an int or a string """ if value_type != "string" and isinstance(s, str) and DESCRIPTION_SEPARATOR in s: if description: raise InvalidRule( 'unexpected value: "%s", only one description allowed (inlin...
def parse_description(s, value_type, description=None):
""" s can be an int or a string """ if value_type != "string" and isinstance(s, str) and DESCRIPTION_SEPARATOR in s: if description: raise InvalidRule( 'unexpected value: "%s", only one description allowed (inline description with `%s`)' % (s, DESCRIPT...
elif key == "match": return capa.features.MatchedRule else: raise InvalidRule("unexpected statement: %s" % key) # this is the separator between a feature value and its description # when using the inline description syntax, like: # # number: 42 = ENUM_FAVORITE_NUMBER DESCRIPTION_SEPARATOR ...
86
87
293
11
75
Ana06-test/capa
capa/rules.py
Python
parse_description
parse_description
244
277
244
244
ed55ba0db3ad6cc6fb707af66de3e05f89905493
bigcode/the-stack
train
e52d5c35774b1aeeb7ce54a8
train
function
def get_rules_and_dependencies(rules, rule_name): """ from the given collection of rules, select a rule and its dependencies (transitively). args: rules (List[Rule]): rule_name (str): yields: Rule: """ # we evaluate `rules` multiple times, so if its a generator, realize it in...
def get_rules_and_dependencies(rules, rule_name):
""" from the given collection of rules, select a rule and its dependencies (transitively). args: rules (List[Rule]): rule_name (str): yields: Rule: """ # we evaluate `rules` multiple times, so if its a generator, realize it into a list. rules = list(rules) namespaces ...
args: rules (List[capa.rules.Rule]): scope (str): one of the capa.rules.*_SCOPE constants. returns: List[capa.rules.Rule]: """ return list(rule for rule in rules if rule.scope == scope) def get_rules_and_dependencies(rules, rule_name):
64
64
170
11
53
Ana06-test/capa
capa/rules.py
Python
get_rules_and_dependencies
get_rules_and_dependencies
758
784
758
758
402af8b4b4aebdd3622b04380b0bd9bf810a0a5d
bigcode/the-stack
train
010d9a41387f256afc71ebd8
train
function
def ensure_rule_dependencies_are_met(rules): """ raise an exception if a rule dependency does not exist. raises: InvalidRule: if a dependency is not met. """ # we evaluate `rules` multiple times, so if its a generator, realize it into a list. rules = list(rules) namespaces = index_rul...
def ensure_rule_dependencies_are_met(rules):
""" raise an exception if a rule dependency does not exist. raises: InvalidRule: if a dependency is not met. """ # we evaluate `rules` multiple times, so if its a generator, realize it into a list. rules = list(rules) namespaces = index_rules_by_namespace(rules) rules = {rule.name...
rule.name in wanted: yield rule def ensure_rules_are_unique(rules): seen = set([]) for rule in rules: if rule.name in seen: raise InvalidRule("duplicate rule name: " + rule.name) seen.add(rule.name) def ensure_rule_dependencies_are_met(rules):
64
64
138
9
55
Ana06-test/capa
capa/rules.py
Python
ensure_rule_dependencies_are_met
ensure_rule_dependencies_are_met
795
809
795
795
52575305dd9bf152b9fdd1ee13acc756fe5fa426
bigcode/the-stack
train
ea787a4feb55dbb05cdd2b2f
train
function
def index_rules_by_namespace(rules): """ compute the rules that fit into each namespace found within the given rules. for example, given: - c2/shell :: create reverse shell - c2/file-transfer :: download and write a file return the index: c2/shell: [create reverse shell] c2/f...
def index_rules_by_namespace(rules):
""" compute the rules that fit into each namespace found within the given rules. for example, given: - c2/shell :: create reverse shell - c2/file-transfer :: download and write a file return the index: c2/shell: [create reverse shell] c2/file-transfer: [download and write a f...
rule.name: rule for rule in rules} for rule in rules.values(): for dep in rule.get_dependencies(namespaces): if dep not in rules: raise InvalidRule('rule "%s" depends on missing rule "%s"' % (rule.name, dep)) def index_rules_by_namespace(rules):
64
64
182
8
56
Ana06-test/capa
capa/rules.py
Python
index_rules_by_namespace
index_rules_by_namespace
812
843
812
812
6d7eb835708f9a355f83cc0d328af2c73a302c3b
bigcode/the-stack
train
e2f3d94e5969c49fa5b9821b
train
function
def pop_statement_description_entry(d): """ extracts the description for statements and removes the description entry from the document a statement can only have one description example: the features definition - or: - description: statement description - number: 1 d...
def pop_statement_description_entry(d):
""" extracts the description for statements and removes the description entry from the document a statement can only have one description example: the features definition - or: - description: statement description - number: 1 description: feature description bec...
", "offset") or value_type.startswith(("number/", "offset/")): try: value = parse_int(value) except ValueError: raise InvalidRule('unexpected value: "%s", must begin with numerical value' % value) return value, description def pop_statement_description_entry(...
64
64
214
7
56
Ana06-test/capa
capa/rules.py
Python
pop_statement_description_entry
pop_statement_description_entry
280
312
280
280
89b7e97366e9b08e6e6221c53c90a5bc0a0e87f9
bigcode/the-stack
train
662bf09c0e198cc69672dd75
train
function
def parse_range(s): """ parse a string "(0, 1)" into a range (min, max). min and/or max may by None to indicate an unbound range. """ # we want to use `{` characters, but this is a dict in yaml. if not s.startswith("("): raise InvalidRule("invalid range: %s" % (s)) if not s.endswith...
def parse_range(s):
""" parse a string "(0, 1)" into a range (min, max). min and/or max may by None to indicate an unbound range. """ # we want to use `{` characters, but this is a dict in yaml. if not s.startswith("("): raise InvalidRule("invalid range: %s" % (s)) if not s.endswith(")"): raise...
t: isinstance(t, type), SUPPORTED_FEATURES[scope]))): raise InvalidRule("feature %s not support for scope %s" % (feature, scope)) def parse_int(s): if s.startswith("0x"): return int(s, 0x10) else: return int(s, 10) def parse_range(s):
75
75
251
5
70
Ana06-test/capa
capa/rules.py
Python
parse_range
parse_range
157
192
157
157
f7601c3e313db4b5804f0c5a6048a06cdfafd090
bigcode/the-stack
train
97ef3119963f48a31c8b7aa2
train
function
def ensure_rules_are_unique(rules): seen = set([]) for rule in rules: if rule.name in seen: raise InvalidRule("duplicate rule name: " + rule.name) seen.add(rule.name)
def ensure_rules_are_unique(rules):
seen = set([]) for rule in rules: if rule.name in seen: raise InvalidRule("duplicate rule name: " + rule.name) seen.add(rule.name)
_name]) def rec(rule): wanted.add(rule.name) for dep in rule.get_dependencies(namespaces): rec(rules[dep]) rec(rules[rule_name]) for rule in rules.values(): if rule.name in wanted: yield rule def ensure_rules_are_unique(rules):
64
64
46
8
55
Ana06-test/capa
capa/rules.py
Python
ensure_rules_are_unique
ensure_rules_are_unique
787
792
787
787
80686539f96e4715e3df9e570c0b5b28b822999a
bigcode/the-stack
train
b122ed1f97f86a37450cdcaa
train
class
class InvalidRuleWithPath(InvalidRule): def __init__(self, path, msg): super(InvalidRuleWithPath, self).__init__(msg) self.path = path self.msg = msg self.__cause__ = None def __str__(self): return "invalid rule: %s: %s" % (self.path, self.msg)
class InvalidRuleWithPath(InvalidRule):
def __init__(self, path, msg): super(InvalidRuleWithPath, self).__init__(msg) self.path = path self.msg = msg self.__cause__ = None def __str__(self): return "invalid rule: %s: %s" % (self.path, self.msg)
init__(self, msg): super(InvalidRule, self).__init__() self.msg = msg def __str__(self): return "invalid rule: %s" % (self.msg) def __repr__(self): return str(self) class InvalidRuleWithPath(InvalidRule):
64
64
81
9
55
Ana06-test/capa
capa/rules.py
Python
InvalidRuleWithPath
InvalidRuleWithPath
119
127
119
119
de8964610cc8f941f28e167c0460c6871b5b2bc3
bigcode/the-stack
train
d1d73a71f70918320de0229d
train
function
def get_rules_with_scope(rules, scope): """ from the given collection of rules, select those with the given scope. args: rules (List[capa.rules.Rule]): scope (str): one of the capa.rules.*_SCOPE constants. returns: List[capa.rules.Rule]: """ return list(rule for rule in rules...
def get_rules_with_scope(rules, scope):
""" from the given collection of rules, select those with the given scope. args: rules (List[capa.rules.Rule]): scope (str): one of the capa.rules.*_SCOPE constants. returns: List[capa.rules.Rule]: """ return list(rule for rule in rules if rule.scope == scope)
re.sub(r"!!int '0x-([0-9a-fA-F]+)'", r"-0x\1", doc) # normalize CRLF to LF doc = doc.replace("\r\n", "\n") return doc def get_rules_with_scope(rules, scope):
64
64
81
10
53
Ana06-test/capa
capa/rules.py
Python
get_rules_with_scope
get_rules_with_scope
744
755
744
744
5f3568cab3da15f01bda8802614130bac7ac847b
bigcode/the-stack
train
1cf006773b5c699876175448
train
class
class InvalidRule(ValueError): def __init__(self, msg): super(InvalidRule, self).__init__() self.msg = msg def __str__(self): return "invalid rule: %s" % (self.msg) def __repr__(self): return str(self)
class InvalidRule(ValueError):
def __init__(self, msg): super(InvalidRule, self).__init__() self.msg = msg def __str__(self): return "invalid rule: %s" % (self.msg) def __repr__(self): return str(self)
.Characteristic("tight loop"), capa.features.Characteristic("stack string"), capa.features.Characteristic("indirect call"), }, } # all basic block scope features are also function scope features SUPPORTED_FEATURES[FUNCTION_SCOPE].update(SUPPORTED_FEATURES[BASIC_BLOCK_SCOPE]) class InvalidRule(Value...
64
64
64
6
58
Ana06-test/capa
capa/rules.py
Python
InvalidRule
InvalidRule
107
116
107
107
fd5e76ed0ac85417d12d94ce998702cffd420b68
bigcode/the-stack
train
4b1a8361f5733c10f9038410
train
function
def parse_int(s): if s.startswith("0x"): return int(s, 0x10) else: return int(s, 10)
def parse_int(s):
if s.startswith("0x"): return int(s, 0x10) else: return int(s, 10)
s not support for scope %s" % (feature, scope)) elif not isinstance(feature, tuple(filter(lambda t: isinstance(t, type), SUPPORTED_FEATURES[scope]))): raise InvalidRule("feature %s not support for scope %s" % (feature, scope)) def parse_int(s):
64
64
34
5
59
Ana06-test/capa
capa/rules.py
Python
parse_int
parse_int
150
154
150
150
66d1e385f1f125107dff0a0f0a3d4343e841a0e9
bigcode/the-stack
train
ca6f49e527b3ee87782e6086
train
class
class RuleSet(object): """ a ruleset is initialized with a collection of rules, which it verifies and sorts into scopes. each set of scoped rules is sorted topologically, which enables rules to match on past rule matches. example: ruleset = RuleSet([ Rule(...), Rule(...), ...
class RuleSet(object):
""" a ruleset is initialized with a collection of rules, which it verifies and sorts into scopes. each set of scoped rules is sorted topologically, which enables rules to match on past rule matches. example: ruleset = RuleSet([ Rule(...), Rule(...), ... ])...
{rule.name: rule for rule in rules} for rule in rules.values(): for dep in rule.get_dependencies(namespaces): if dep not in rules: raise InvalidRule('rule "%s" depends on missing rule "%s"' % (rule.name, dep)) def index_rules_by_namespace(rules): """ compute the rules ...
244
244
814
5
239
Ana06-test/capa
capa/rules.py
Python
RuleSet
RuleSet
846
945
846
846
4adc113476bd13193922d51f9577a660f98434cc
bigcode/the-stack
train
aea69e2c25f8cb82ef2d8632
train
function
def parse_feature(key): # keep this in sync with supported features if key == "api": return capa.features.insn.API elif key == "string": return capa.features.StringFactory elif key == "bytes": return capa.features.Bytes elif key == "number": return capa.features.insn....
def parse_feature(key): # keep this in sync with supported features
if key == "api": return capa.features.insn.API elif key == "string": return capa.features.StringFactory elif key == "bytes": return capa.features.Bytes elif key == "number": return capa.features.insn.Number elif key.startswith("number/"): arch = key.partition(...
raise InvalidRule("range min less than zero") else: min = None if max: max = parse_int(max.strip()) if max < 0: raise InvalidRule("range max less than zero") else: max = None if min is not None and max is not None: if max < min: raise In...
106
106
354
15
90
Ana06-test/capa
capa/rules.py
Python
parse_feature
parse_feature
195
234
195
196
0df2c7c9e01e175679fcf70752a20f024883408c
bigcode/the-stack
train
1501af5cb7d327075289e096
train
function
def first(s): return s[0]
def first(s):
return s[0]
(key) value, description = parse_description(d[key], key, d.get("description")) try: feature = Feature(value, description=description) except ValueError as e: raise InvalidRule(str(e)) ensure_feature_valid_for_scope(scope, feature) return feature def first...
64
64
10
4
59
Ana06-test/capa
capa/rules.py
Python
first
first
422
423
422
422
2c1e9dbd89ae67325a7ca9753cdd465c60064551
bigcode/the-stack
train
a72d501f9808730d4c827561
train
function
def second(s): return s[1]
def second(s):
return s[1]
[key], key, d.get("description")) try: feature = Feature(value, description=description) except ValueError as e: raise InvalidRule(str(e)) ensure_feature_valid_for_scope(scope, feature) return feature def first(s): return s[0] def second(s):
64
64
10
4
60
Ana06-test/capa
capa/rules.py
Python
second
second
426
427
426
426
e3e1160d47579c294ee6b1a249bfc42c679dfb88
bigcode/the-stack
train
9c9d36b50b5b45a1682cff1b
train
class
class Rule(object): def __init__(self, name, scope, statement, meta, definition=""): super(Rule, self).__init__() self.name = name self.scope = scope self.statement = statement self.meta = meta self.definition = definition def __str__(self): return "Rule(...
class Rule(object):
def __init__(self, name, scope, statement, meta, definition=""): super(Rule, self).__init__() self.name = name self.scope = scope self.statement = statement self.meta = meta self.definition = definition def __str__(self): return "Rule(name=%s)" % (self.na...
more"): min = parse_int(count[: -len(" or more")]) max = None return Range(feature, min=min, max=max, description=description) elif count.endswith(" or fewer"): min = None max = parse_int(count[: -len(" or fewer")]) return Range(feature, m...
256
256
2,548
4
252
Ana06-test/capa
capa/rules.py
Python
Rule
Rule
430
741
430
430
11f19239fb5acb9ab43e342503590ba8e3f93967
bigcode/the-stack
train
4bd80d66de444e646bdf2b37
train
function
def ensure_feature_valid_for_scope(scope, feature): if isinstance(feature, capa.features.Characteristic): if capa.features.Characteristic(feature.value) not in SUPPORTED_FEATURES[scope]: raise InvalidRule("feature %s not support for scope %s" % (feature, scope)) elif not isinstance(feature, ...
def ensure_feature_valid_for_scope(scope, feature):
if isinstance(feature, capa.features.Characteristic): if capa.features.Characteristic(feature.value) not in SUPPORTED_FEATURES[scope]: raise InvalidRule("feature %s not support for scope %s" % (feature, scope)) elif not isinstance(feature, tuple(filter(lambda t: isinstance(t, type), SUPPORTE...
, msg): super(InvalidRuleSet, self).__init__() self.msg = msg def __str__(self): return "invalid rule set: %s" % (self.msg) def __repr__(self): return str(self) def ensure_feature_valid_for_scope(scope, feature):
64
64
104
10
54
Ana06-test/capa
capa/rules.py
Python
ensure_feature_valid_for_scope
ensure_feature_valid_for_scope
142
147
142
142
20da55664d5e5ffb7d63903f450b0d950caf9a38
bigcode/the-stack
train
cc4b6113fc27dbfcd44ba7e7
train
function
def build_statements(d, scope): if len(d.keys()) > 2: raise InvalidRule("too many statements") key = list(d.keys())[0] description = pop_statement_description_entry(d[key]) if key == "and": return And([build_statements(dd, scope) for dd in d[key]], description=description) elif key ...
def build_statements(d, scope):
if len(d.keys()) > 2: raise InvalidRule("too many statements") key = list(d.keys())[0] description = pop_statement_description_entry(d[key]) if key == "and": return And([build_statements(dd, scope) for dd in d[key]], description=description) elif key == "or": return Or([buil...
(value) except ValueError: raise InvalidRule('unexpected value: "%s", must begin with numerical value' % value) return value, description def pop_statement_description_entry(d): """ extracts the description for statements and removes the description entry from the document ...
255
256
966
8
247
Ana06-test/capa
capa/rules.py
Python
build_statements
build_statements
315
419
315
315
a8c770a55559f529e0ef501420fcc683f5f3eac7
bigcode/the-stack
train
b136d862d5d7249a8e07bdcd
train
class
class InvalidRuleSet(ValueError): def __init__(self, msg): super(InvalidRuleSet, self).__init__() self.msg = msg def __str__(self): return "invalid rule set: %s" % (self.msg) def __repr__(self): return str(self)
class InvalidRuleSet(ValueError):
def __init__(self, msg): super(InvalidRuleSet, self).__init__() self.msg = msg def __str__(self): return "invalid rule set: %s" % (self.msg) def __repr__(self): return str(self)
RuleWithPath, self).__init__(msg) self.path = path self.msg = msg self.__cause__ = None def __str__(self): return "invalid rule: %s: %s" % (self.path, self.msg) class InvalidRuleSet(ValueError):
64
64
67
7
57
Ana06-test/capa
capa/rules.py
Python
InvalidRuleSet
InvalidRuleSet
130
139
130
130
c0c58f31985146c66594e3d413bc03b02e625418
bigcode/the-stack
train
473a8f2009f1867bb111ed2d
train
class
class Scoreboard(): """A class to report scoring information.""" def __init__(self, ai_settings, screen, stats): """Initialize scorekeeping attributes.""" self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats ...
class Scoreboard():
"""A class to report scoring information.""" def __init__(self, ai_settings, screen, stats): """Initialize scorekeeping attributes.""" self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats # ...
import pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard():
19
181
605
4
14
jhcgt4869/alien_invasion
alien_invasion/scoreboard.py
Python
Scoreboard
Scoreboard
6
75
6
6
67c5ccd82922bd44d02c4cb8666d85097a400cbe
bigcode/the-stack
train
b83c73bf404762eff0ced555
train
function
def get_pcap_file(path): """ get pcap file :param path: path. """ if isinstance(path, bytes): path = from_c_str(path) return ( os.path.join(directory, file) for directory, dirs, files in os.walk(path) for file in files if ".pcap" in file )
def get_pcap_file(path):
""" get pcap file :param path: path. """ if isinstance(path, bytes): path = from_c_str(path) return ( os.path.join(directory, file) for directory, dirs, files in os.walk(path) for file in files if ".pcap" in file )
("utf-8") except Exception: pass return b"" def from_c_str(v): """ C str to Python str """ try: return v.decode("utf-8") except Exception: pass return "" def get_pcap_file(path):
63
64
77
7
56
drewp/python-libpcap
pylibpcap/utils.py
Python
get_pcap_file
get_pcap_file
35
49
35
35
7a1d84104184642cfdd1aaa7674a22a75c27324a
bigcode/the-stack
train
b13ba7879ce073171cc9c63f
train
function
def to_c_str(v): """ Python str to C str """ try: return v.encode("utf-8") except Exception: pass return b""
def to_c_str(v):
""" Python str to C str """ try: return v.encode("utf-8") except Exception: pass return b""
# @Date: 2019-09-04 23:19:03 # @Last Modified by: jankincai12@gmail.com # @Last Modified time: 2019-09-24 09:49:13 import os def to_c_str(v):
64
64
41
6
57
drewp/python-libpcap
pylibpcap/utils.py
Python
to_c_str
to_c_str
9
19
9
9
64c4327e283c932b5b98f916f77ed4680a967790
bigcode/the-stack
train
c4e489e99fdc0d3ecbb19329
train
function
def from_c_str(v): """ C str to Python str """ try: return v.decode("utf-8") except Exception: pass return ""
def from_c_str(v):
""" C str to Python str """ try: return v.decode("utf-8") except Exception: pass return ""
2019-09-24 09:49:13 import os def to_c_str(v): """ Python str to C str """ try: return v.encode("utf-8") except Exception: pass return b"" def from_c_str(v):
64
64
39
6
57
drewp/python-libpcap
pylibpcap/utils.py
Python
from_c_str
from_c_str
22
32
22
22
a577627251a3e3e87d0193fa16234b7846697305
bigcode/the-stack
train
1fbda4c78e8d8f731669ebc2
train
class
class User(AbstractUser): first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) username = models.CharField(max_length=200, blank=False, unique=True) email = models.EmailField(max_length=255, blank=False, unique=True) updated = models.Dat...
class User(AbstractUser):
first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) username = models.CharField(max_length=200, blank=False, unique=True) email = models.EmailField(max_length=255, blank=False, unique=True) updated = models.DateTimeField(auto_now=True) ...
from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser):
20
64
138
5
14
mjay0100/quiz-app
api/accounts/models.py
Python
User
User
5
22
5
6
a5c1477b27985314e15c2395b54d77a719b75dd7
bigcode/the-stack
train
f5cfd1be2967e9f809b1030d
train
function
def get_dbase_query_pairs(all_mol2s): q_list, d_list = [], [] for m in all_mol2s: if m.endswith(('_query.mol2.gz', '_query.mol2')): q_list.append(m) elif m.endswith(('_dbase.mol2.gz', '_dbase.mol2')): d_list.append(m) if len(q_list) != len(q_list): raise Value...
def get_dbase_query_pairs(all_mol2s):
q_list, d_list = [], [] for m in all_mol2s: if m.endswith(('_query.mol2.gz', '_query.mol2')): q_list.append(m) elif m.endswith(('_dbase.mol2.gz', '_dbase.mol2')): d_list.append(m) if len(q_list) != len(q_list): raise ValueError('The input directory contains an...
_path = os.path.join(dir_path, f) files.append(file_path) elif (os.path.isfile(dir_path) and dir_path.endswith(('.mol2', 'mol2.gz'))): files.append(dir_path) return files def get_dbase_query_pairs(all_mol2s):
64
64
126
12
51
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
get_dbase_query_pairs
get_dbase_query_pairs
59
69
59
59
4a04a34efd9ab885127e09683926dd03901f7857
bigcode/the-stack
train
898f67d013a3af73dc8367ff
train
function
def data_processor_gz(mol2s_gz): q_pdmol = PandasMol2() d_pdmol = PandasMol2() d_pdmol.read_mol2_from_list(mol2_code=mol2s_gz[0][0], mol2_lines=mol2s_gz[0][1]) q_pdmol.read_mol2_from_list(mol2_code=mol2s_gz[1][0], mol2_lines=mol2s_gz[1][...
def data_processor_gz(mol2s_gz):
q_pdmol = PandasMol2() d_pdmol = PandasMol2() d_pdmol.read_mol2_from_list(mol2_code=mol2s_gz[0][0], mol2_lines=mol2s_gz[0][1]) q_pdmol.read_mol2_from_list(mol2_code=mol2s_gz[1][0], mol2_lines=mol2s_gz[1][1]) atoms, charges = get_atom...
mol2_lines=mol2s[1][1]) atoms, charges = get_atom_matches(q_pdmol, d_pdmol) return mol2s[0][0], mol2s[1][0], atoms, charges def data_processor_gz(mol2s_gz):
64
64
175
12
51
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
data_processor_gz
data_processor_gz
102
116
102
103
811f63f97204047da5e9c66f70ded2bb19f5e6c2
bigcode/the-stack
train
d1eb27bd1fc645a5f6dda578
train
function
def main(input_dir, output_dir, verbose, n_cpus): n_cpus = get_num_cpus(n_cpus) if not os.path.exists(output_dir): os.mkdir(output_dir) mol2_in_files = get_mol2_files(input_dir) q_list, d_list = get_dbase_query_pairs(mol2_in_files) csv_out_bases = [os.path.join(output_dir, ...
def main(input_dir, output_dir, verbose, n_cpus):
n_cpus = get_num_cpus(n_cpus) if not os.path.exists(output_dir): os.mkdir(output_dir) mol2_in_files = get_mol2_files(input_dir) q_list, d_list = get_dbase_query_pairs(mol2_in_files) csv_out_bases = [os.path.join(output_dir, os.path.basename(mol2).replace...
_num_cpus(n_cpus): if not n_cpus: n_cpus = cpu_count() elif n_cpus < 0: n_cpus = cpu_count() - n_cpus return n_cpus def main(input_dir, output_dir, verbose, n_cpus):
64
64
187
14
49
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
main
main
214
238
214
215
1d20088211473f11fe7d61931ee604260c693f3c
bigcode/the-stack
train
fc07080063613490b1d9d7cc
train
function
def get_mol2_files(dir_path): files = [] if os.path.isdir(dir_path): for f in os.listdir(dir_path): if f.endswith(('.mol2', 'mol2.gz')): file_path = os.path.join(dir_path, f) files.append(file_path) elif (os.path.isfile(dir_path) and dir_path.e...
def get_mol2_files(dir_path):
files = [] if os.path.isdir(dir_path): for f in os.listdir(dir_path): if f.endswith(('.mol2', 'mol2.gz')): file_path = os.path.join(dir_path, f) files.append(file_path) elif (os.path.isfile(dir_path) and dir_path.endswith(('.mol2', 'mol2.gz'))):...
sys import time from multiprocessing import cpu_count from numpy import nan as np_nan from mputil import lazy_imap from biopandas.mol2 import PandasMol2 from biopandas.mol2 import split_multimol2 def get_mol2_files(dir_path):
64
64
98
9
54
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
get_mol2_files
get_mol2_files
43
56
43
44
fbe0ab4ab08406d1e2b5a78c58cd04a0c8533a97
bigcode/the-stack
train
df9a8ecfa590e2e71b46bcaa
train
function
def get_atom_matches(q_pdmol, d_pdmol): atoms, charges = [], [] for xyz in q_pdmol.df[['x', 'y', 'z']].iterrows(): distances = d_pdmol.distance(xyz=xyz[1].values) nearest_idx = distances.argmin() columns = ['atom_type', 'charge'] if distances.iloc[nearest_idx] > THRESHOLD: ...
def get_atom_matches(q_pdmol, d_pdmol):
atoms, charges = [], [] for xyz in q_pdmol.df[['x', 'y', 'z']].iterrows(): distances = d_pdmol.distance(xyz=xyz[1].values) nearest_idx = distances.argmin() columns = ['atom_type', 'charge'] if distances.iloc[nearest_idx] > THRESHOLD: atom, charge = '', np_nan ...
d_list.append(m) if len(q_list) != len(q_list): raise ValueError('The input directory contains an unequal number of' '*_dbase* and *_query* files.') return q_list, d_list def get_atom_matches(q_pdmol, d_pdmol):
64
64
140
14
49
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
get_atom_matches
get_atom_matches
72
84
72
72
431f0c51bf4a662fa6c1d390531bd80c512e0820
bigcode/the-stack
train
a2fc70a208549a6959e98efe
train
function
def read_and_write(q_path, d_path, verbose, cache, output_file, n_cpus): dct_results = {'dbase': [], 'query': [], 'atoms': [], 'charges': []} d_base = os.path.basename(d_path) q_base = os.path.basename(q_path) if verbose: start = time.time() sys.stdout.write('Proces...
def read_and_write(q_path, d_path, verbose, cache, output_file, n_cpus):
dct_results = {'dbase': [], 'query': [], 'atoms': [], 'charges': []} d_base = os.path.basename(d_path) q_base = os.path.basename(q_path) if verbose: start = time.time() sys.stdout.write('Processing %s/%s' % (d_base, q_base)) sys.stdout.flush() cnt = 0 if q_path.endswi...
2_lines=mol2s[1][1]) atoms, charges = get_atom_matches(q_pdmol, d_pdmol) return mol2s[0][0], mol2s[1][0], atoms, charges def data_processor_gz(mol2s_gz): q_pdmol = PandasMol2() d_pdmol = PandasMol2() d_pdmol.read_mol2_from_list(mol2_code=mol2s_gz[0][0], mol2_line...
248
248
827
22
226
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
read_and_write
read_and_write
119
203
119
121
635c42f0bd46a7c27f2cfbc9a2d657533f9801ce
bigcode/the-stack
train
37e0a6abf53a070a50ea9f34
train
function
def get_num_cpus(n_cpus): if not n_cpus: n_cpus = cpu_count() elif n_cpus < 0: n_cpus = cpu_count() - n_cpus return n_cpus
def get_num_cpus(n_cpus):
if not n_cpus: n_cpus = cpu_count() elif n_cpus < 0: n_cpus = cpu_count() - n_cpus return n_cpus
: elapsed = time.time() - start n_molecules = cnt + 1 sys.stdout.write(' | scanned %d molecules | %d mol/sec\n' % (n_molecules, n_molecules / elapsed)) sys.stdout.flush() def get_num_cpus(n_cpus):
64
64
52
9
55
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
get_num_cpus
get_num_cpus
206
211
206
206
f252ab884cbf4dff38d93eb23c145e7d3fa6cbd5
bigcode/the-stack
train
ba3002864489edcfefcc2435
train
function
def data_processor(mol2s): q_pdmol = PandasMol2() d_pdmol = PandasMol2() d_pdmol.read_mol2_from_list(mol2_code=mol2s[0][0], mol2_lines=mol2s[0][1]) q_pdmol.read_mol2_from_list(mol2_code=mol2s[1][0], mol2_lines=mol2s[1][1]) atoms, ch...
def data_processor(mol2s):
q_pdmol = PandasMol2() d_pdmol = PandasMol2() d_pdmol.read_mol2_from_list(mol2_code=mol2s[0][0], mol2_lines=mol2s[0][1]) q_pdmol.read_mol2_from_list(mol2_code=mol2s[1][0], mol2_lines=mol2s[1][1]) atoms, charges = get_atom_matches(q_p...
_idx] > THRESHOLD: atom, charge = '', np_nan else: atom, charge = d_pdmol.df[columns].iloc[nearest_idx].values atoms.append(atom) charges.append(charge) return atoms, charges def data_processor(mol2s):
64
64
144
8
55
tahmidbintaslim/screenlamp
tools/funcgroup_matching.py
Python
data_processor
data_processor
87
99
87
88
e7a1b4a9e2d7654c2cb3681797be2769260cb557
bigcode/the-stack
train
7107c9f46b91ce1aa38f48f9
train
function
def ReadAndUpdateVersion(version_filename, update_position=None): """Takes given filename containing version, optionally updates the version and saves it, and returns the version.""" if os.path.exists(version_filename): current_version = open(version_filename).readlines()[0] numbers = current_version.split(...
def ReadAndUpdateVersion(version_filename, update_position=None):
"""Takes given filename containing version, optionally updates the version and saves it, and returns the version.""" if os.path.exists(version_filename): current_version = open(version_filename).readlines()[0] numbers = current_version.split('.') if update_position: numbers[update_position] = '%02...
import os FIRST_VERSION = '1.00.00.00' def ReadVersion(version_filename): if os.path.exists(version_filename): return open(version_filename).readlines()[0] else: return FIRST_VERSION def ReadAndUpdateVersion(version_filename, update_position=None):
60
64
172
12
47
igushev/fase_lib
tools/version_util.py
Python
ReadAndUpdateVersion
ReadAndUpdateVersion
13
28
13
13
768511eb831cca482e59770f2720e948a8b17be3
bigcode/the-stack
train