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
72421e5a4b4e663514d7be93
train
class
class Node(Object3D, W.PsNode): pass
class Node(Object3D, W.PsNode):
pass
from .__base__ import * from ..qtqml import QtObject from ..qtquick import PropertyAnimation class Object3D(QtObject, W.PsObject3D): pass class Node(Object3D, W.PsNode):
51
64
14
11
39
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Node
Node
10
11
10
10
8773390a219b2659f28a0a3ce5fd6da1880f872c
bigcode/the-stack
train
459a27bb242821e4884df5f0
train
class
class Material(Object3D, W.PsMaterial): pass
class Material(Object3D, W.PsMaterial):
pass
3D(QtObject, W.PsObject3D): pass class Node(Object3D, W.PsNode): pass class Camera(Node, W.PsCamera): pass class Light(Node, W.PsLight): pass class Material(Object3D, W.PsMaterial):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Material
Material
22
23
22
22
4ff7a0507753121e423f86909af1184798077501
bigcode/the-stack
train
02517cb2a6a6610f08959e5f
train
class
class Light(Node, W.PsLight): pass
class Light(Node, W.PsLight):
pass
import QtObject from ..qtquick import PropertyAnimation class Object3D(QtObject, W.PsObject3D): pass class Node(Object3D, W.PsNode): pass class Camera(Node, W.PsCamera): pass class Light(Node, W.PsLight):
64
64
12
9
54
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Light
Light
18
19
18
18
92f49356bf4ed4a4eaa3f3ef1ac253b29417c045
bigcode/the-stack
train
6738b5c8309c24936b70c62f
train
class
class InstanceListEntry(Object3D, W.PsInstanceListEntry): pass
class InstanceListEntry(Object3D, W.PsInstanceListEntry):
pass
class FrustumCamera(PerspectiveCamera, W.PsFrustumCamera): pass class Geometry(Object3D, W.PsGeometry): pass class InstanceList(Instancing, W.PsInstanceList): pass class InstanceListEntry(Object3D, W.PsInstanceListEntry):
64
64
18
15
48
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
InstanceListEntry
InstanceListEntry
82
83
82
82
e04844eea70709d27d5140e88f529f8ab054f741
bigcode/the-stack
train
95182f7ce276a0c4cabf247c
train
class
class Joint(Node, W.PsJoint): pass
class Joint(Node, W.PsJoint):
pass
FrustumCamera): pass class Geometry(Object3D, W.PsGeometry): pass class InstanceList(Instancing, W.PsInstanceList): pass class InstanceListEntry(Object3D, W.PsInstanceListEntry): pass class Joint(Node, W.PsJoint):
64
64
12
9
54
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Joint
Joint
86
87
86
86
a42d319b8fa566d96f1f28dd576884d73a43abf7
bigcode/the-stack
train
05611546700205e43b10ee78
train
class
class View3D(C, W.PsView3D): pass
class View3D(C, W.PsView3D):
pass
sSpotLight): pass class Texture(Object3D, W.PsTexture): pass class TextureData(Object3D, W.PsTextureData): pass class TextureInput(C, W.PsTextureInput): pass class View3D(C, W.PsView3D):
64
64
16
13
50
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
View3D
View3D
166
167
166
166
826d57f2c46637865355d311b8195fb4c67f0e05
bigcode/the-stack
train
6246e62e39e5e430192a937e
train
class
class Camera(Node, W.PsCamera): pass
class Camera(Node, W.PsCamera):
pass
from .__base__ import * from ..qtqml import QtObject from ..qtquick import PropertyAnimation class Object3D(QtObject, W.PsObject3D): pass class Node(Object3D, W.PsNode): pass class Camera(Node, W.PsCamera):
63
64
12
9
53
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Camera
Camera
14
15
14
14
aa0971131c80f8f62e1ed1eb1a0a510621f272e7
bigcode/the-stack
train
82f921b3faa4d66207966478
train
class
class MorphTarget(C, W.PsMorphTarget): pass
class MorphTarget(C, W.PsMorphTarget):
pass
3D, W.PsInstanceListEntry): pass class Joint(Node, W.PsJoint): pass class Loader3D(Node, W.PsLoader3D): pass class Model(Node, W.PsModel): pass class MorphTarget(C, W.PsMorphTarget):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
MorphTarget
MorphTarget
98
99
98
98
7566a9dc7631d27b2bf1289759590501c661529e
bigcode/the-stack
train
5a2a27f4435a6d314a0de64a
train
class
class TextureInput(C, W.PsTextureInput): pass
class TextureInput(C, W.PsTextureInput):
pass
W.PsSkeleton): pass class SpotLight(Light, W.PsSpotLight): pass class Texture(Object3D, W.PsTexture): pass class TextureData(Object3D, W.PsTextureData): pass class TextureInput(C, W.PsTextureInput):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
TextureInput
TextureInput
162
163
162
162
025be2efda0c8e9d492581c06719d0d9aaadb09f
bigcode/the-stack
train
0f9cba79ab6d448bb28f5bfd
train
class
class SpotLight(Light, W.PsSpotLight): pass
class SpotLight(Light, W.PsSpotLight):
pass
3D, W.PsSceneEnvironment): pass class SetUniformValue(Command, W.PsSetUniformValue): pass class Shader(C, W.PsShader): pass class Skeleton(Node, W.PsSkeleton): pass class SpotLight(Light, W.PsSpotLight):
64
64
15
12
51
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
SpotLight
SpotLight
150
151
150
150
a1f91a79d312bce019f775ad317838e0a1e5f25b
bigcode/the-stack
train
d868e7ba51bf8a3ffe6d113d
train
class
class Pass(C, W.PsPass): pass
class Pass(C, W.PsPass):
pass
D(Node, W.PsLoader3D): pass class Model(Node, W.PsModel): pass class MorphTarget(C, W.PsMorphTarget): pass class OrthographicCamera(Camera, W.PsOrthographicCamera): pass class Pass(C, W.PsPass):
64
64
12
9
54
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Pass
Pass
106
107
106
106
763cfae2d53762ef7e5753e382705ea201b22e9b
bigcode/the-stack
train
1195d7ccd9dff9a81f54c3c3
train
class
class Loader3D(Node, W.PsLoader3D): pass
class Loader3D(Node, W.PsLoader3D):
pass
Geometry): pass class InstanceList(Instancing, W.PsInstanceList): pass class InstanceListEntry(Object3D, W.PsInstanceListEntry): pass class Joint(Node, W.PsJoint): pass class Loader3D(Node, W.PsLoader3D):
64
64
16
13
50
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Loader3D
Loader3D
90
91
90
90
97a136f28a9dc45020dd24148efd395343cb857d
bigcode/the-stack
train
c6f523ae1258949cb84fc397
train
class
class CustomMaterial(Material, W.PsCustomMaterial): pass
class CustomMaterial(Material, W.PsCustomMaterial):
pass
class Bounds(C, W.PsBounds): pass class Buffer(C, W.PsBuffer): pass class BufferInput(Command, W.PsBufferInput): pass class CustomCamera(Camera, W.PsCustomCamera): pass class CustomMaterial(Material, W.PsCustomMaterial):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
CustomMaterial
CustomMaterial
54
55
54
54
08f672f63d458eacce2f452ffa5a244d23c7be55
bigcode/the-stack
train
be839a8ce36ab309417ab664
train
class
class Skeleton(Node, W.PsSkeleton): pass
class Skeleton(Node, W.PsSkeleton):
pass
W.PsRepeater3D): pass class SceneEnvironment(Object3D, W.PsSceneEnvironment): pass class SetUniformValue(Command, W.PsSetUniformValue): pass class Shader(C, W.PsShader): pass class Skeleton(Node, W.PsSkeleton):
64
64
12
9
54
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Skeleton
Skeleton
146
147
146
146
82cefde08e6b43117bfb361f93a7fcbd00476162
bigcode/the-stack
train
1d5556442fad9bcc7711e809
train
class
class Bounds(C, W.PsBounds): pass
class Bounds(C, W.PsBounds):
pass
Material(Object3D, W.PsMaterial): pass class Command(C, W.PsCommand): pass class Instancing(Object3D, W.PsInstancing): pass class PerspectiveCamera(Camera, W.PsPerspectiveCamera): pass class Bounds(C, W.PsBounds):
64
64
12
9
54
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Bounds
Bounds
38
39
38
38
a833b07fc221f6619b70eef94021d94fa3079afc
bigcode/the-stack
train
9fa49bf6599b9b510ec67b05
train
class
class PrincipledMaterial(Material, W.PsPrincipledMaterial): pass
class PrincipledMaterial(Material, W.PsPrincipledMaterial):
pass
W.PsOrthographicCamera): pass class Pass(C, W.PsPass): pass class PickResult(C, W.PsPickResult): pass class PointLight(Light, W.PsPointLight): pass class PrincipledMaterial(Material, W.PsPrincipledMaterial):
64
64
16
13
50
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
PrincipledMaterial
PrincipledMaterial
118
119
118
118
695575bf11dbb995ddb8472710e5378fa45f66e5
bigcode/the-stack
train
019d82e580e75067277ff20e
train
class
class Shader(C, W.PsShader): pass
class Shader(C, W.PsShader):
pass
Stats): pass class Repeater3D(Node, W.PsRepeater3D): pass class SceneEnvironment(Object3D, W.PsSceneEnvironment): pass class SetUniformValue(Command, W.PsSetUniformValue): pass class Shader(C, W.PsShader):
64
64
12
9
54
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Shader
Shader
142
143
142
142
ec4a44a0a7c4c736f8abb851ea62f723558bffba
bigcode/the-stack
train
389d859de48cc29d0dbf62fd
train
class
class PointLight(Light, W.PsPointLight): pass
class PointLight(Light, W.PsPointLight):
pass
, W.PsMorphTarget): pass class OrthographicCamera(Camera, W.PsOrthographicCamera): pass class Pass(C, W.PsPass): pass class PickResult(C, W.PsPickResult): pass class PointLight(Light, W.PsPointLight):
64
64
15
12
51
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
PointLight
PointLight
114
115
114
114
60a3cdbde2b33b833340fe9f032627852653a1d4
bigcode/the-stack
train
c4ba38c6092deb0796e32a15
train
class
class InstanceList(Instancing, W.PsInstanceList): pass
class InstanceList(Instancing, W.PsInstanceList):
pass
): pass class Effect(Object3D, W.PsEffect): pass class FrustumCamera(PerspectiveCamera, W.PsFrustumCamera): pass class Geometry(Object3D, W.PsGeometry): pass class InstanceList(Instancing, W.PsInstanceList):
64
64
16
13
50
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
InstanceList
InstanceList
78
79
78
78
2c0f49dfd128a2e675a6a5527e0bc329b77f1480
bigcode/the-stack
train
1de6b6f5048ac2a6218cad78
train
class
class QuaternionAnimation(PropertyAnimation, W.PsQuaternionAnimation): pass
class QuaternionAnimation(PropertyAnimation, W.PsQuaternionAnimation):
pass
.PsPass): pass class PickResult(C, W.PsPickResult): pass class PointLight(Light, W.PsPointLight): pass class PrincipledMaterial(Material, W.PsPrincipledMaterial): pass class QuaternionAnimation(PropertyAnimation, W.PsQuaternionAnimation):
64
64
15
12
51
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
QuaternionAnimation
QuaternionAnimation
122
123
122
122
4a634736994ed11d327fb0e694d212ff8da31afc
bigcode/the-stack
train
9ad74b25f45a321b71092263
train
class
class Geometry(Object3D, W.PsGeometry): pass
class Geometry(Object3D, W.PsGeometry):
pass
): pass class DirectionalLight(Light, W.PsDirectionalLight): pass class Effect(Object3D, W.PsEffect): pass class FrustumCamera(PerspectiveCamera, W.PsFrustumCamera): pass class Geometry(Object3D, W.PsGeometry):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Geometry
Geometry
74
75
74
74
80393bd798cefdf16563bbcb3de193a023fd9456
bigcode/the-stack
train
24527b284a55fad2b2b19cfe
train
class
class PerspectiveCamera(Camera, W.PsPerspectiveCamera): pass
class PerspectiveCamera(Camera, W.PsPerspectiveCamera):
pass
Light(Node, W.PsLight): pass class Material(Object3D, W.PsMaterial): pass class Command(C, W.PsCommand): pass class Instancing(Object3D, W.PsInstancing): pass class PerspectiveCamera(Camera, W.PsPerspectiveCamera):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
PerspectiveCamera
PerspectiveCamera
34
35
34
34
00154383c84aefa776f7b6368077d91e0373ae1f
bigcode/the-stack
train
e84eab68f43ee570b97ae645
train
class
class RenderStats(C, W.PsRenderStats): pass
class RenderStats(C, W.PsRenderStats):
pass
sPickResult): pass class PointLight(Light, W.PsPointLight): pass class PrincipledMaterial(Material, W.PsPrincipledMaterial): pass class QuaternionAnimation(PropertyAnimation, W.PsQuaternionAnimation): pass class RenderStats(C, W.PsRenderStats):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
RenderStats
RenderStats
126
127
126
126
6234b870e79c8b60593a3cb7160bc34e658a72c7
bigcode/the-stack
train
4d6af51988422b8e67c26c78
train
class
class Instancing(Object3D, W.PsInstancing): pass
class Instancing(Object3D, W.PsInstancing):
pass
class Camera(Node, W.PsCamera): pass class Light(Node, W.PsLight): pass class Material(Object3D, W.PsMaterial): pass class Command(C, W.PsCommand): pass class Instancing(Object3D, W.PsInstancing):
64
64
16
13
50
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
Instancing
Instancing
30
31
30
30
a63757297c8f3fbcfb3ef1786b5558fc8c16b4d1
bigcode/the-stack
train
c77c67c0fc6ff99fbed1a1ec
train
class
class CustomCamera(Camera, W.PsCustomCamera): pass
class CustomCamera(Camera, W.PsCustomCamera):
pass
class PerspectiveCamera(Camera, W.PsPerspectiveCamera): pass class Bounds(C, W.PsBounds): pass class Buffer(C, W.PsBuffer): pass class BufferInput(Command, W.PsBufferInput): pass class CustomCamera(Camera, W.PsCustomCamera):
64
64
14
11
52
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
CustomCamera
CustomCamera
50
51
50
50
45eb47bb064e1df4054c5e67a84f0ad408a3ae09
bigcode/the-stack
train
29b246f408c85eb6321f13f5
train
class
class TextureData(Object3D, W.PsTextureData): pass
class TextureData(Object3D, W.PsTextureData):
pass
(C, W.PsShader): pass class Skeleton(Node, W.PsSkeleton): pass class SpotLight(Light, W.PsSpotLight): pass class Texture(Object3D, W.PsTexture): pass class TextureData(Object3D, W.PsTextureData):
64
64
16
13
50
likianta/declare-qtquick
declare_qtquick/widgets/api/qtquick3d/__list__.py
Python
TextureData
TextureData
158
159
158
158
c32be4228c21e48b4ce10d954e49c874c38aef72
bigcode/the-stack
train
1093257243c67b6b39e74c6c
train
function
def func_retry_decorator(worker_task): # type: (WorkerTask) -> (tuple, dict) def wrapper(*args, **kwargs): # type: (tuple, dict) -> Any execute_inline = _get_kwarg_val(kwargs, 'execute_inline', False) or settings.EXECUTE_INLINE delay = _get_kwarg_val(kwargs, 'delay', settings.DEFAULT_DEL...
def func_retry_decorator(worker_task): # type: (WorkerTask) -> (tuple, dict)
def wrapper(*args, **kwargs): # type: (tuple, dict) -> Any execute_inline = _get_kwarg_val(kwargs, 'execute_inline', False) or settings.EXECUTE_INLINE delay = _get_kwarg_val(kwargs, 'delay', settings.DEFAULT_DELAY) count_retries = _get_kwarg_val(kwargs, 'count_retries', settings.DEFA...
.DEFAULT_DELAY) worker = WorkerFactory.default().create() return worker.delay(group_id, queue, func, args, kwargs, max_retries, pickle, delay, execute_inline) return wrapper def func_retry_decorator(worker_task): # type: (WorkerTask) -> (tuple, dict)
64
64
136
22
41
Modern-Fertility/django-eb-sqs
eb_sqs/decorators.py
Python
func_retry_decorator
func_retry_decorator
30
40
30
31
8df5779d447a67ee4a3c77d28447486222f72d47
bigcode/the-stack
train
a0dc0dff06454054845e401d
train
function
def _get_kwarg_val(kwargs, key, default): # type: (dict, str, Any) -> Any return kwargs.pop(key, default) if kwargs else default
def _get_kwarg_val(kwargs, key, default): # type: (dict, str, Any) -> Any
return kwargs.pop(key, default) if kwargs else default
future__ import absolute_import, unicode_literals from eb_sqs import settings from eb_sqs.worker.worker_factory import WorkerFactory from eb_sqs.worker.worker_task import WorkerTask def _get_kwarg_val(kwargs, key, default): # type: (dict, str, Any) -> Any
64
64
39
26
37
Modern-Fertility/django-eb-sqs
eb_sqs/decorators.py
Python
_get_kwarg_val
_get_kwarg_val
8
10
8
9
566932bef3732732e6fda1d053a8fb7961f73f41
bigcode/the-stack
train
6e3c382f3953df88e4c1706a
train
class
class task(object): def __init__(self, queue_name=None, group_id=None, max_retries=None, use_pickle=None): # type: (str, int, bool) -> None self.queue_name = queue_name self.max_retries = max_retries self.use_pickle = use_pickle self.group_id = group_id def __call__(self...
class task(object):
def __init__(self, queue_name=None, group_id=None, max_retries=None, use_pickle=None): # type: (str, int, bool) -> None self.queue_name = queue_name self.max_retries = max_retries self.use_pickle = use_pickle self.group_id = group_id def __call__(self, *args, **kwargs): ...
, 'delay', settings.DEFAULT_DELAY) count_retries = _get_kwarg_val(kwargs, 'count_retries', settings.DEFAULT_COUNT_RETRIES) worker = WorkerFactory.default().create() return worker.retry(worker_task, delay, execute_inline, count_retries) return wrapper class task(object):
64
64
147
4
59
Modern-Fertility/django-eb-sqs
eb_sqs/decorators.py
Python
task
task
43
56
43
43
5b993112ec1235f3e5106dc03369eddc0d1a41e8
bigcode/the-stack
train
a6858eebaaba26fdffd811b9
train
function
def func_delay_decorator(func, queue_name, group_id, max_retries_count, use_pickle): # type: (Any, str, int, bool) -> (tuple, dict) def wrapper(*args, **kwargs): # type: (tuple, dict) -> Any queue = _get_kwarg_val(kwargs, 'queue_name', queue_name if queue_name else settings.DEFAULT_QUEUE) ...
def func_delay_decorator(func, queue_name, group_id, max_retries_count, use_pickle): # type: (Any, str, int, bool) -> (tuple, dict)
def wrapper(*args, **kwargs): # type: (tuple, dict) -> Any queue = _get_kwarg_val(kwargs, 'queue_name', queue_name if queue_name else settings.DEFAULT_QUEUE) max_retries = _get_kwarg_val(kwargs, 'max_retries', max_retries_count if max_retries_count else settings.DEFAULT_MAX_RETRIES) ...
# type: (dict, str, Any) -> Any return kwargs.pop(key, default) if kwargs else default def func_delay_decorator(func, queue_name, group_id, max_retries_count, use_pickle): # type: (Any, str, int, bool) -> (tuple, dict)
67
67
225
40
26
Modern-Fertility/django-eb-sqs
eb_sqs/decorators.py
Python
func_delay_decorator
func_delay_decorator
13
27
13
14
33c975c19dd392294d7fe4d153a3f96912086dc6
bigcode/the-stack
train
40e98ae4bdb29cd7c849eb3b
train
class
class Ponto(): def __init__(self, x, y, caracter): self.caracter = caracter self.x = round(x) self.y = round(y) def __eq__(self, other): return self.x == other.x and self.y == other.y and self.caracter == other.caracter def __hash__(self): return hash(self.x) ^ hash...
class Ponto():
def __init__(self, x, y, caracter): self.caracter = caracter self.x = round(x) self.y = round(y) def __eq__(self, other): return self.x == other.x and self.y == other.y and self.caracter == other.caracter def __hash__(self): return hash(self.x) ^ hash(self.y) d...
# -*- coding: utf-8 -*- from itertools import chain from atores import ATIVO VITORIA = 'VITORIA' DERROTA = 'DERROTA' EM_ANDAMENTO = 'EM_ANDAMENTO' class Ponto():
50
64
124
4
46
fsfranciscoanalistagit/pythonbirds
fase.py
Python
Ponto
Ponto
11
24
11
11
27494821163c576c32909ee00a193b773f74e8c3
bigcode/the-stack
train
9321286c6dd9f44512618faf
train
class
class Fase(): def __init__(self, intervalo_de_colisao=1): """ Método que inicializa uma fase. :param intervalo_de_colisao: """ self.intervalo_de_colisao = intervalo_de_colisao self._passaros = [] self._porcos = [] self._obstaculos = [] def adici...
class Fase():
def __init__(self, intervalo_de_colisao=1): """ Método que inicializa uma fase. :param intervalo_de_colisao: """ self.intervalo_de_colisao = intervalo_de_colisao self._passaros = [] self._porcos = [] self._obstaculos = [] def adicionar_obstaculo...
# -*- coding: utf-8 -*- from itertools import chain from atores import ATIVO VITORIA = 'VITORIA' DERROTA = 'DERROTA' EM_ANDAMENTO = 'EM_ANDAMENTO' class Ponto(): def __init__(self, x, y, caracter): self.caracter = caracter self.x = round(x) self.y = round(y) def __eq__(self, other):...
174
212
709
4
170
fsfranciscoanalistagit/pythonbirds
fase.py
Python
Fase
Fase
27
130
27
27
c01e4ee3814ff8e5acf31673fe2712c9b0f8908e
bigcode/the-stack
train
4efaf2d0dea64d6a14120fbd
train
function
def skip_items_keys(items, keys=tuple()): """ >>> skip_items_keys({'fo': 1}.items()) [('fo', 1)] """ return [x for x in items if x[0] not in keys]
def skip_items_keys(items, keys=tuple()):
""" >>> skip_items_keys({'fo': 1}.items()) [('fo', 1)] """ return [x for x in items if x[0] not in keys]
def skip_items_keys(items, keys=tuple()):
10
64
51
10
0
martbln/django-service-boilerplate
lib/codegen/utils.py
Python
skip_items_keys
skip_items_keys
1
6
1
1
687ae70802a4b149089ce1c84ed3a34aeda787ee
bigcode/the-stack
train
a114f0043b87402d2ed6ba48
train
function
def to_model_field_name(name): return name.lstrip('_').replace('-', '_')
def to_model_field_name(name):
return name.lstrip('_').replace('-', '_')
def skip_items_keys(items, keys=tuple()): """ >>> skip_items_keys({'fo': 1}.items()) [('fo', 1)] """ return [x for x in items if x[0] not in keys] def to_model_field_name(name):
58
64
18
7
51
martbln/django-service-boilerplate
lib/codegen/utils.py
Python
to_model_field_name
to_model_field_name
9
10
9
9
5f712aeef535f298fdeed23204b3274e1caa66f7
bigcode/the-stack
train
032521ea0ee6f9f466123a71
train
function
def ok(data=None, paginator=None): msg = OrderedDict() msg['meta'] = OrderedDict() msg['meta']["code"] = OK["code"] msg['meta']["message"] = OK["message"] if data: msg['data'] = data if paginator: msg['pagination'] = { "num_pages": paginator.num_pages, "cu...
def ok(data=None, paginator=None):
msg = OrderedDict() msg['meta'] = OrderedDict() msg['meta']["code"] = OK["code"] msg['meta']["message"] = OK["message"] if data: msg['data'] = data if paginator: msg['pagination'] = { "num_pages": paginator.num_pages, "current_page": paginator.current_page...
_page end = start + item_per_page paginator = EsPaging() data = es_query[start:end].execute().hits paginator.data = data.hits paginator.num_pages = data.total paginator.current_page = page return paginator def ok(data=None, paginator=None):
64
64
97
8
55
cloudcomputinghust/IoT
platform_manager/api/utils.py
Python
ok
ok
29
41
29
29
37c4087d728dd654a06d10a59e5740b44c516257
bigcode/the-stack
train
fea4285e6ed171f676d34969
train
function
def restrict_search(request, key, es_query): paginator = es_paging(es_query, request) serialization = serializers.es_serialize(paginator.data) return ok({key: serialization}, paginator)
def restrict_search(request, key, es_query):
paginator = es_paging(es_query, request) serialization = serializers.es_serialize(paginator.data) return ok({key: serialization}, paginator)
"] = OK["message"] if data: msg['data'] = data if paginator: msg['pagination'] = { "num_pages": paginator.num_pages, "current_page": paginator.current_page, } return Response(msg) def restrict_search(request, key, es_query):
64
64
42
10
54
cloudcomputinghust/IoT
platform_manager/api/utils.py
Python
restrict_search
restrict_search
43
46
43
43
f06e94d4fcfc9da8da85f810db4504b686a0380f
bigcode/the-stack
train
335504fa6c977200f224fcc9
train
function
def es_paging(es_query, request, page=None, item_per_page=None): if not page: page = int(request.GET.get("page", "1")) if not item_per_page: item_per_page = int(request.GET.get("perPage", 10)) start = (page - 1) * item_per_page end = start + item_per_page paginator = EsPaging() d...
def es_paging(es_query, request, page=None, item_per_page=None):
if not page: page = int(request.GET.get("page", "1")) if not item_per_page: item_per_page = int(request.GET.get("perPage", 10)) start = (page - 1) * item_per_page end = start + item_per_page paginator = EsPaging() data = es_query[start:end].execute().hits paginator.data = dat...
rest_framework.response import Response from collections import OrderedDict from django.utils.translation import ugettext as _ OK = { "code": "OK", "message": _("Success") } class EsPaging: pass def es_paging(es_query, request, page=None, item_per_page=None):
64
64
126
17
46
cloudcomputinghust/IoT
platform_manager/api/utils.py
Python
es_paging
es_paging
15
27
15
15
ebe8e9415ae40d2e487832a02f88e34b12461765
bigcode/the-stack
train
f03a69a128ff9ff42e108153
train
class
class EsPaging: pass
class EsPaging:
pass
from . import serializers from rest_framework.response import Response from collections import OrderedDict from django.utils.translation import ugettext as _ OK = { "code": "OK", "message": _("Success") } class EsPaging:
50
64
7
4
46
cloudcomputinghust/IoT
platform_manager/api/utils.py
Python
EsPaging
EsPaging
11
12
11
11
5c3d5d9b62f915f2d7494d3d519b663983ba7ca3
bigcode/the-stack
train
12f0e6f3220ebc4bbc44b1a5
train
function
def spatial_inertia_of_cylinder(mass, length, radius): I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2 I_zz = 0.5 * mass * radius ** 2 I = np.eye(6) I[:3, :3] *= np.array([I_xx, I_yy, I_zz]) I[3:, 3:] *= mass return I
def spatial_inertia_of_cylinder(mass, length, radius):
I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2 I_zz = 0.5 * mass * radius ** 2 I = np.eye(6) I[:3, :3] *= np.array([I_xx, I_yy, I_zz]) I[3:, 3:] *= mass return I
coordinates of transformation to finally compute the new pose of the cylinder. """ print(__doc__) import numpy as np from pytransform3d.transformations import ( transform_from_exponential_coordinates) import pytransform3d.visualizer as pv def spatial_inertia_of_cylinder(mass, length, radius):
64
64
116
14
49
erikmannerfelt/pytransform3d
examples/visualizations/vis_moving_cylinder_with_wrench.py
Python
spatial_inertia_of_cylinder
spatial_inertia_of_cylinder
19
25
19
19
04cb3c187e254a616b9a607282a7f0d043f3cd29
bigcode/the-stack
train
0218d94efbfb4fb5be4472bb
train
function
def animation_callback( step, cylinder, cylinder_frame, prev_cylinder2world, Stheta_dot, inertia_inv): if step == 0: # Reset cylinder state prev_cylinder2world[:, :] = np.eye(4) Stheta_dot[:] = 0.0 # Apply constant wrench wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0....
def animation_callback( step, cylinder, cylinder_frame, prev_cylinder2world, Stheta_dot, inertia_inv):
if step == 0: # Reset cylinder state prev_cylinder2world[:, :] = np.eye(4) Stheta_dot[:] = 0.0 # Apply constant wrench wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0.01, 1.0, 1.0]) dt = 0.0005 Stheta_ddot = np.dot(inertia_inv, wrench_in_cylinder) Stheta_dot += dt * Stheta...
I[:3, :3] *= np.array([I_xx, I_yy, I_zz]) I[3:, 3:] *= mass return I def animation_callback( step, cylinder, cylinder_frame, prev_cylinder2world, Stheta_dot, inertia_inv):
64
64
215
26
37
erikmannerfelt/pytransform3d
examples/visualizations/vis_moving_cylinder_with_wrench.py
Python
animation_callback
animation_callback
28
50
28
30
a0b02f1bea0afff33d834fe0bd51d58e059899f9
bigcode/the-stack
train
ba125611d7f2f81b9fa9dcce
train
function
def get_version(): filePath = Path("./musketeer/__init__.py") if not filePath.exists(): warnings.warn( "Could not locate __init__.py to read the version number from", RuntimeWarning, ) return "0.0.1.unknown.version" with Path("./musketeer/__init__.py").open() ...
def get_version():
filePath = Path("./musketeer/__init__.py") if not filePath.exists(): warnings.warn( "Could not locate __init__.py to read the version number from", RuntimeWarning, ) return "0.0.1.unknown.version" with Path("./musketeer/__init__.py").open() as file: fo...
import setuptools import warnings from pathlib import Path with open("README.md") as readmeFile: long_description = readmeFile.read() def get_version():
35
64
139
4
31
TChis/Musketeer
setup.py
Python
get_version
get_version
9
25
9
9
6692aed72ea0911c51b9139a98a3e329857cd46f
bigcode/the-stack
train
1c15d3c513a12c5a6dafc285
train
function
def from_pandas(obj): """ Convert certain Pandas objects into the cudf equivalent. Supports DataFrame, Series, Index, or MultiIndex. Raises ------ TypeError for invalid input type. Examples -------- >>> import cudf >>> import pandas as pd >>> data = [[0, 1], [1, 2], [3, 4]...
def from_pandas(obj):
""" Convert certain Pandas objects into the cudf equivalent. Supports DataFrame, Series, Index, or MultiIndex. Raises ------ TypeError for invalid input type. Examples -------- >>> import cudf >>> import pandas as pd >>> data = [[0, 1], [1, 2], [3, 4]] >>> pdf = pd.Dat...
fortranarray(cov)).set_index( self.columns ) df.columns = self.columns return df def corr(self): """Compute the correlation matrix of a DataFrame. """ corr = cupy.corrcoef(self.values, rowvar=False) df = DataFrame.from_gpu_matrix(cupy.asfortranarr...
102
102
340
6
95
wbo4958/cudf
python/cudf/cudf/core/dataframe.py
Python
from_pandas
from_pandas
4,807
4,847
4,807
4,807
dc198b6d2a4806ac80ad6959d6b5b54bfea8d519
bigcode/the-stack
train
1e2cd1aba8706a9cd61195e7
train
class
class DataFrame(Frame): """ A GPU Dataframe object. Parameters ---------- data : data-type to coerce. Infers date format if to date. Examples -------- Build dataframe with `__setitem__`: >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df[...
class DataFrame(Frame):
""" A GPU Dataframe object. Parameters ---------- data : data-type to coerce. Infers date format if to date. Examples -------- Build dataframe with `__setitem__`: >>> import cudf >>> df = cudf.DataFrame() >>> df['key'] = [0, 1, 2, 3, 4] >>> df['val'] = [float(i + 10) ...
ul", "rmul": "mul", "mod": "rmod", "rmod": "mod", "pow": "rpow", "rpow": "pow", "floordiv": "rfloordiv", "rfloordiv": "floordiv", "truediv": "rtruediv", "rtruediv": "truediv", "__add__": "__radd__", "__radd__": "__add__", "_...
256
256
33,871
5
251
wbo4958/cudf
python/cudf/cudf/core/dataframe.py
Python
DataFrame
DataFrame
90
4,804
90
90
7924c16567a9bb1137964312a674775f4b7f8258
bigcode/the-stack
train
95672adb8d00c48f34d907ab
train
function
def _reverse_op(fn): return { "add": "radd", "radd": "add", "sub": "rsub", "rsub": "sub", "mul": "rmul", "rmul": "mul", "mod": "rmod", "rmod": "mod", "pow": "rpow", "rpow": "pow", "floordiv": "rfloordiv", "rfloordiv": "f...
def _reverse_op(fn):
return { "add": "radd", "radd": "add", "sub": "rsub", "rsub": "sub", "mul": "rmul", "rmul": "mul", "mod": "rmod", "rmod": "mod", "pow": "rpow", "rpow": "pow", "floordiv": "rfloordiv", "rfloordiv": "floordiv", "tr...
_categorical_dtype, is_datetime_dtype, is_list_like, is_scalar, ) from cudf.utils.utils import OrderedColumnDict def _unique_name(existing_names, suffix="_unique_name"): ret = suffix i = 1 while ret in existing_names: ret = "%s_%d" % (suffix, i) i += 1 return ret def _rever...
89
89
298
6
82
wbo4958/cudf
python/cudf/cudf/core/dataframe.py
Python
_reverse_op
_reverse_op
57
87
57
57
c77fdaa758ef26a2f1ee381fc67a89e048ab0686
bigcode/the-stack
train
7a87fb36bcff9886b61b202e
train
function
def _align_indices(lhs, rhs): """ Internal util to align the indices of two DataFrames. Returns a tuple of the aligned dataframes, or the original arguments if the indices are the same, or if rhs isn't a DataFrame. """ lhs_out, rhs_out = lhs, rhs if isinstance(rhs, DataFrame) and not lhs.ind...
def _align_indices(lhs, rhs):
""" Internal util to align the indices of two DataFrames. Returns a tuple of the aligned dataframes, or the original arguments if the indices are the same, or if rhs isn't a DataFrame. """ lhs_out, rhs_out = lhs, rhs if isinstance(rhs, DataFrame) and not lhs.index.equals(rhs.index): ...
): return left.merge(right, *args, **kwargs) # a bit of fanciness to inject doctstring with left parameter merge_doc = DataFrame.merge.__doc__ idx = merge_doc.find("right") merge.__doc__ = "".join( [merge_doc[:idx], "\n\tleft : DataFrame\n\t", merge_doc[idx:]] ) def _align_indices(lhs, rhs):
83
83
277
8
75
wbo4958/cudf
python/cudf/cudf/core/dataframe.py
Python
_align_indices
_align_indices
4,862
4,894
4,862
4,862
3c2d12587bd4e5aa6b4ce188a24590a8d176d8b4
bigcode/the-stack
train
d74354004ec1ad3c02626695
train
function
def _unique_name(existing_names, suffix="_unique_name"): ret = suffix i = 1 while ret in existing_names: ret = "%s_%d" % (suffix, i) i += 1 return ret
def _unique_name(existing_names, suffix="_unique_name"):
ret = suffix i = 1 while ret in existing_names: ret = "%s_%d" % (suffix, i) i += 1 return ret
copy_docstring from cudf.utils.dtypes import ( cudf_dtype_from_pydata_dtype, is_categorical_dtype, is_datetime_dtype, is_list_like, is_scalar, ) from cudf.utils.utils import OrderedColumnDict def _unique_name(existing_names, suffix="_unique_name"):
64
64
54
12
51
wbo4958/cudf
python/cudf/cudf/core/dataframe.py
Python
_unique_name
_unique_name
48
54
48
48
c101875ce57b6a61fff0fd850423a50bdd647f7d
bigcode/the-stack
train
4eb7b5f39b880b267e2afece
train
function
def _setitem_with_dataframe(input_df, replace_df, input_cols=None, mask=None): """ This function sets item dataframes relevant columns with replacement df :param input_df: Dataframe to be modified inplace :param replace_df: Replacement DataFrame to replace values with :param input_co...
def _setitem_with_dataframe(input_df, replace_df, input_cols=None, mask=None):
""" This function sets item dataframes relevant columns with replacement df :param input_df: Dataframe to be modified inplace :param replace_df: Replacement DataFrame to replace values with :param input_cols: columns to replace in the input dataframe :param mask: boolean mask...
[:-2]] = df[col] elif col in common_y: rhs_out[col[:-2]] = df[col] elif col in lhs: lhs_out[col] = df[col] elif col in rhs: rhs_out[col] = df[col] return lhs_out, rhs_out def _setitem_with_dataframe(input_df, replace_df, input_cols...
82
82
275
19
62
wbo4958/cudf
python/cudf/cudf/core/dataframe.py
Python
_setitem_with_dataframe
_setitem_with_dataframe
4,897
4,927
4,897
4,897
b4e7c9e52375706e0e1d7dddd3bd8efeb19c105c
bigcode/the-stack
train
a54bdb64b0418e638c97af0a
train
function
def merge(left, right, *args, **kwargs): return left.merge(right, *args, **kwargs)
def merge(left, right, *args, **kwargs):
return left.merge(right, *args, **kwargs)
.from_pandas(obj) else: raise TypeError( "from_pandas only accepts Pandas Dataframes, Series, " "Index, RangeIndex and MultiIndex objects. " "Got %s" % type(obj) ) def merge(left, right, *args, **kwargs):
64
64
24
12
52
wbo4958/cudf
python/cudf/cudf/core/dataframe.py
Python
merge
merge
4,850
4,851
4,850
4,850
1d7c17708d8ef9b939282fcb184fee8321aa88b9
bigcode/the-stack
train
c5a332108b7a287ffdc250a2
train
class
class ClimbUp(Climb): name = "climb_up" direction = Direction.Up
class ClimbUp(Climb):
name = "climb_up" direction = Direction.Up
, target_selection=None): level_stub, exit_tile = self.level_exit new_level = level_stub.level self.current_level.remove_object(character) character.location.set_local_coords(exit_tile.location.get_local_coords()) new_level.add_object(character) return True class ClimbUp...
64
64
22
8
55
ChrisLR/BasicDungeonRL
bfgame/actions/climb.py
Python
ClimbUp
ClimbUp
40
42
40
40
115095b7dd535e13c0a7840e0d4e03391e1f5722
bigcode/the-stack
train
79821723837c0e5a1d419ad2
train
class
class Climb(Action): name = "climb" direction = None def __init__(self, game): super().__init__(game) self.current_level = None self.level_exit = None def can_execute(self, character, target_selection=None): location = character.location self.current_level = loc...
class Climb(Action):
name = "climb" direction = None def __init__(self, game): super().__init__(game) self.current_level = None self.level_exit = None def can_execute(self, character, target_selection=None): location = character.location self.current_level = location.level i...
from core.actions.base import Action from core.direction import Direction class Climb(Action):
18
64
203
5
12
ChrisLR/BasicDungeonRL
bfgame/actions/climb.py
Python
Climb
Climb
5
37
5
5
5879dbdb0e73ba3ea9a7b3f6e013e14e58478a72
bigcode/the-stack
train
ff1ef7ca7afd25a433a6d8c5
train
class
class ClimbDown(Climb): name = "climb_down" direction = Direction.Down
class ClimbDown(Climb):
name = "climb_down" direction = Direction.Down
.level self.current_level.remove_object(character) character.location.set_local_coords(exit_tile.location.get_local_coords()) new_level.add_object(character) return True class ClimbUp(Climb): name = "climb_up" direction = Direction.Up class ClimbDown(Climb):
64
64
22
8
55
ChrisLR/BasicDungeonRL
bfgame/actions/climb.py
Python
ClimbDown
ClimbDown
45
47
45
45
8f85926594b17e9dfa28568f00c39f9307463bdd
bigcode/the-stack
train
c78dd4e2651d537d30ca65f4
train
class
class PCA(object): """Principle Component Analysis.""" def __init__(self, n_comps=5, standard=True, logger=None): """Contructor. Parameters ---------- n_comps: int Number of principle components """ self._fitted = False self.n_comps = n_comps...
class PCA(object):
"""Principle Component Analysis.""" def __init__(self, n_comps=5, standard=True, logger=None): """Contructor. Parameters ---------- n_comps: int Number of principle components """ self._fitted = False self.n_comps = n_comps self.stand...
# scientific computing library import numpy as np class PCA(object):
14
235
786
4
9
filangel/Eigenfaces
src/pca.py
Python
PCA
PCA
5
129
5
5
e30cfe98701584a0a2b8166fe2abfd9960070a95
bigcode/the-stack
train
c9af28ff5e2b4e45578c633a
train
function
def mkdirs(paths): if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths)
def mkdirs(paths):
if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths)
f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f" % (np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)) ) def mkdirs(paths):
64
64
36
5
59
leVirve/ELD
util/util.py
Python
mkdirs
mkdirs
108
113
108
108
6c174a71562c3165502660e121ec41c158ff9259
bigcode/the-stack
train
5745dfcd212dd646f557fb4f
train
function
def get_summary_writer(log_dir): if not os.path.exists(log_dir): os.mkdir(log_dir) log_dir = os.path.join(log_dir, datetime.now().strftime("%b%d_%H-%M-%S") + "_" + socket.gethostname()) if not os.path.exists(log_dir): os.mkdir(log_dir) writer = SummaryWriter(log_dir) return writer
def get_summary_writer(log_dir):
if not os.path.exists(log_dir): os.mkdir(log_dir) log_dir = os.path.join(log_dir, datetime.now().strftime("%b%d_%H-%M-%S") + "_" + socket.gethostname()) if not os.path.exists(log_dir): os.mkdir(log_dir) writer = SummaryWriter(log_dir) return writer
2) starty = y // 2 - (cropy // 2) return img[:, :, starty : starty + cropy, startx : startx + cropx].contiguous() from datetime import datetime from tensorboardX import SummaryWriter def get_summary_writer(log_dir):
64
64
80
7
56
leVirve/ELD
util/util.py
Python
get_summary_writer
get_summary_writer
147
154
147
147
62f13d4deb45bcf04c9576d1bb97f0e8b19f1210
bigcode/the-stack
train
c281ab515eb45fd6e40947aa
train
function
def write_loss(writer, prefix, avg_meters, iteration): for key in avg_meters.keys(): meter = avg_meters[key] writer.add_scalar(os.path.join(prefix, key), meter, iteration)
def write_loss(writer, prefix, avg_meters, iteration):
for key in avg_meters.keys(): meter = avg_meters[key] writer.add_scalar(os.path.join(prefix, key), meter, iteration)
keys = sorted(self.keys()) res = "" for key in keys: res += key + ": %.4f" % self[key] + " | " return res def keys(self): return self.dic.keys() def write_loss(writer, prefix, avg_meters, iteration):
64
64
45
13
51
leVirve/ELD
util/util.py
Python
write_loss
write_loss
187
190
187
187
85797083a665dbf4a5cd5f693f99890ff7144a2d
bigcode/the-stack
train
d09268baf7f8f81d5048d23d
train
function
def format_time(seconds): days = int(seconds / 3600 / 24) seconds = seconds - days * 3600 * 24 hours = int(seconds / 3600) seconds = seconds - hours * 3600 minutes = int(seconds / 60) seconds = seconds - minutes * 60 secondsf = int(seconds) seconds = seconds - secondsf millis = int(s...
def format_time(seconds):
days = int(seconds / 3600 / 24) seconds = seconds - days * 3600 * 24 hours = int(seconds / 3600) seconds = seconds - hours * 3600 minutes = int(seconds / 60) seconds = seconds - minutes * 60 secondsf = int(seconds) seconds = seconds - secondsf millis = int(seconds * 1000) f = ""...
(term_width - int(TOTAL_BAR_LENGTH / 2) + 2): sys.stdout.write("\b") sys.stdout.write(" %d/%d " % (current + 1, total)) if current < total - 1: sys.stdout.write("\r") else: sys.stdout.write("\n") sys.stdout.flush() def format_time(seconds):
78
78
261
5
73
leVirve/ELD
util/util.py
Python
format_time
format_time
247
277
247
247
f130138ddc1f939f867465e32def744ed648a525
bigcode/the-stack
train
6a25706e9c575968818cbcdb
train
function
def diagnose_network(net, name="network"): mean = 0.0 count = 0 for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean)
def diagnose_network(net, name="network"):
mean = 0.0 count = 0 for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean)
[:, 1, :, :] = 0.224 std[:, 2, :, :] = 0.225 batch = (batch + 1) / 2 batch -= mean batch = batch / std return batch def diagnose_network(net, name="network"):
64
64
77
9
54
leVirve/ELD
util/util.py
Python
diagnose_network
diagnose_network
78
88
78
78
3ef2b9d888f9586e7bafa13e8c19331684e31a9d
bigcode/the-stack
train
850fbd3b5de73b3e5d38e6fc
train
function
def get_model_list(dirname, key, epoch=None): if epoch is None: return os.path.join(dirname, key + "_latest.pt") if os.path.exists(dirname) is False: return None gen_models = [ os.path.join(dirname, f) for f in os.listdir(dirname) if os.path.isfile(os.path.join(dirnam...
def get_model_list(dirname, key, epoch=None):
if epoch is None: return os.path.join(dirname, key + "_latest.pt") if os.path.exists(dirname) is False: return None gen_models = [ os.path.join(dirname, f) for f in os.listdir(dirname) if os.path.isfile(os.path.join(dirname, f)) and key in f and ".pt" in f and "latest...
7], (1, 1, 3)) image_numpy = np.concatenate([image_numpy[:, :, :3], image_numpy[:, :, 3:6], edge_map], axis=1) return image_numpy # Get model list for resume def get_model_list(dirname, key, epoch=None):
64
64
187
11
52
leVirve/ELD
util/util.py
Python
get_model_list
get_model_list
38
59
38
38
1892b8bb95d89f713cf509160d3932e59f593994
bigcode/the-stack
train
510fdaa595f4691729a46fbc
train
function
def loadmat(filename): """ this function should be called instead of direct spio.loadmat as it cures the problem of not properly recovering python dictionaries from mat files. It calls the function check keys to cure all entries which are still mat-objects """ def _check_keys(d): ""...
def loadmat(filename):
""" this function should be called instead of direct spio.loadmat as it cures the problem of not properly recovering python dictionaries from mat files. It calls the function check keys to cure all entries which are still mat-objects """ def _check_keys(d): """ checks if ent...
2: f += str(millis) + "ms" i += 1 if f == "": f = "0ms" return f def parse_args(args): str_args = args.split(",") parsed_args = [] for str_arg in str_args: arg = int(str_arg) if arg >= 0: parsed_args.append(arg) return parsed_args # https:/...
116
116
387
5
110
leVirve/ELD
util/util.py
Python
loadmat
loadmat
291
341
291
291
9277fd5afc60d7be859fe857cb91c805015bb1cd
bigcode/the-stack
train
7af7a444f2b0c1cbfdcf089e
train
function
def set_opt_param(optimizer, key, value): for group in optimizer.param_groups: group[key] = value
def set_opt_param(optimizer, key, value):
for group in optimizer.param_groups: group[key] = value
def mkdirs(paths): if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path): if not os.path.exists(path): os.makedirs(path) def set_opt_param(optimizer, key, value):
64
64
26
11
53
leVirve/ELD
util/util.py
Python
set_opt_param
set_opt_param
121
123
121
121
838da8a0985efb567c1bf102b45ccd1b18780a95
bigcode/the-stack
train
dfbc94ff171a028e127b2c1d
train
function
def progress_bar(current, total, msg=None): global last_time, begin_time if current == 0: begin_time = time.time() # Reset for new bar. cur_len = int(TOTAL_BAR_LENGTH * current / total) rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1 sys.stdout.write(" [") for i in range(cur_len): ...
def progress_bar(current, total, msg=None):
global last_time, begin_time if current == 0: begin_time = time.time() # Reset for new bar. cur_len = int(TOTAL_BAR_LENGTH * current / total) rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1 sys.stdout.write(" [") for i in range(cur_len): sys.stdout.write("=") sys.stdout.wri...
, avg_meters, iteration): for key in avg_meters.keys(): meter = avg_meters[key] writer.add_scalar(os.path.join(prefix, key), meter, iteration) import socket _, term_width = os.popen("stty size", "r").read().split() term_width = int(term_width) TOTAL_BAR_LENGTH = 65.0 last_time = time.time() begi...
99
99
332
10
88
leVirve/ELD
util/util.py
Python
progress_bar
progress_bar
203
244
203
203
c0e435081f229575d870a8c67a4a199533c00bcc
bigcode/the-stack
train
9ec964de456a6d07b2a07f25
train
function
def mkdir(path): if not os.path.exists(path): os.makedirs(path)
def mkdir(path):
if not os.path.exists(path): os.makedirs(path)
(np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)) ) def mkdirs(paths): if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path):
64
64
17
4
60
leVirve/ELD
util/util.py
Python
mkdir
mkdir
116
118
116
116
3269b23b71574fdb997df028d2f4599d5c30cf4e
bigcode/the-stack
train
0789e64ddf933d58b1909206
train
class
class AverageMeters(object): def __init__(self, dic=None, total_num=None): self.dic = dic or {} # self.total_num = total_num self.total_num = total_num or {} def update(self, new_dic): for key in new_dic: if not key in self.dic: self.dic[key] = new_di...
class AverageMeters(object):
def __init__(self, dic=None, total_num=None): self.dic = dic or {} # self.total_num = total_num self.total_num = total_num or {} def update(self, new_dic): for key in new_dic: if not key in self.dic: self.dic[key] = new_dic[key] self.t...
) log_dir = os.path.join(log_dir, datetime.now().strftime("%b%d_%H-%M-%S") + "_" + socket.gethostname()) if not os.path.exists(log_dir): os.mkdir(log_dir) writer = SummaryWriter(log_dir) return writer class AverageMeters(object):
64
64
203
5
58
leVirve/ELD
util/util.py
Python
AverageMeters
AverageMeters
157
184
157
157
c45262d6a37c22b5f6ec22cf1122f5a29fe32cb0
bigcode/the-stack
train
c575f3e18359b37648e7e842
train
function
def tensor2im(image_tensor, imtype=np.uint8): image_numpy = image_tensor[0].cpu().float().numpy() if image_numpy.shape[0] == 1: image_numpy = np.tile(image_numpy, (3, 1, 1)) image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 image_numpy = image_numpy.astype(imtype) if ima...
def tensor2im(image_tensor, imtype=np.uint8):
image_numpy = image_tensor[0].cpu().float().numpy() if image_numpy.shape[0] == 1: image_numpy = np.tile(image_numpy, (3, 1, 1)) image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 image_numpy = image_numpy.astype(imtype) if image_numpy.shape[-1] == 6: image_numpy =...
PIL import Image def get_config(config): with open(config, "r") as stream: return yaml.load(stream) # Converts a Tensor into a Numpy array # |imtype|: the desired type of the converted numpy array def tensor2im(image_tensor, imtype=np.uint8):
64
64
211
13
50
leVirve/ELD
util/util.py
Python
tensor2im
tensor2im
23
34
23
23
3c84d5628a86455b65e2efc7480b284a4d679cdb
bigcode/the-stack
train
ff74876efaa83515ab23e5a0
train
function
def get_config(config): with open(config, "r") as stream: return yaml.load(stream)
def get_config(config):
with open(config, "r") as stream: return yaml.load(stream)
from __future__ import print_function import math import os import sys import time import numpy as np import scipy import scipy.io as spio import torch import yaml from PIL import Image def get_config(config):
51
64
22
5
45
leVirve/ELD
util/util.py
Python
get_config
get_config
16
18
16
16
c9313542ddde4adaf7ec707391eb871f8ac3ee9e
bigcode/the-stack
train
b9b067da1d77ce7670f7b2b1
train
function
def parse_args(args): str_args = args.split(",") parsed_args = [] for str_arg in str_args: arg = int(str_arg) if arg >= 0: parsed_args.append(arg) return parsed_args
def parse_args(args):
str_args = args.split(",") parsed_args = [] for str_arg in str_args: arg = int(str_arg) if arg >= 0: parsed_args.append(arg) return parsed_args
str(secondsf) + "s" i += 1 if millis > 0 and i <= 2: f += str(millis) + "ms" i += 1 if f == "": f = "0ms" return f def parse_args(args):
64
64
51
5
58
leVirve/ELD
util/util.py
Python
parse_args
parse_args
280
287
280
280
dddc65ecc7b95c57ad7bb6315d81dbb1774963b6
bigcode/the-stack
train
e81c89963cfd7fdc11e8e309
train
function
def print_numpy(x, val=True, shp=False): x = x.astype(np.float64) if shp: print("shape,", x.shape) if val: x = x.flatten() print( "mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f" % (np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)) ...
def print_numpy(x, val=True, shp=False):
x = x.astype(np.float64) if shp: print("shape,", x.shape) if val: x = x.flatten() print( "mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f" % (np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)) )
1 if count > 0: mean = mean / count print(name) print(mean) def save_image(image_numpy, image_path): image_pil = Image.fromarray(image_numpy) image_pil.save(image_path) def print_numpy(x, val=True, shp=False):
64
64
112
11
53
leVirve/ELD
util/util.py
Python
print_numpy
print_numpy
96
105
96
96
2186876017a6d711474a93db8765738fb429eaad
bigcode/the-stack
train
a3f5fd8812ff2ffcab1459e0
train
function
def vis(x): if isinstance(x, torch.Tensor): Image.fromarray(tensor2im(x)).show() elif isinstance(x, np.ndarray): Image.fromarray(x.astype(np.uint8)).show() else: raise NotImplementedError("vis for type [%s] is not implemented", type(x))
def vis(x):
if isinstance(x, torch.Tensor): Image.fromarray(tensor2im(x)).show() elif isinstance(x, np.ndarray): Image.fromarray(x.astype(np.uint8)).show() else: raise NotImplementedError("vis for type [%s] is not implemented", type(x))
for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path): if not os.path.exists(path): os.makedirs(path) def set_opt_param(optimizer, key, value): for group in optimizer.param_groups: group[key] = value def vis(x):
64
64
66
4
59
leVirve/ELD
util/util.py
Python
vis
vis
126
132
126
126
1d775f44b3ae6fccc7802259e4206f046c0d7ce0
bigcode/the-stack
train
c58e338d1a1f4e43f324d365
train
function
def vgg_preprocess(batch): # normalize using imagenet mean and std mean = batch.new(batch.size()) std = batch.new(batch.size()) mean[:, 0, :, :] = 0.485 mean[:, 1, :, :] = 0.456 mean[:, 2, :, :] = 0.406 std[:, 0, :, :] = 0.229 std[:, 1, :, :] = 0.224 std[:, 2, :, :] = 0.225 batch...
def vgg_preprocess(batch): # normalize using imagenet mean and std
mean = batch.new(batch.size()) std = batch.new(batch.size()) mean[:, 0, :, :] = 0.485 mean[:, 1, :, :] = 0.456 mean[:, 2, :, :] = 0.406 std[:, 0, :, :] = 0.229 std[:, 1, :, :] = 0.224 std[:, 2, :, :] = 0.225 batch = (batch + 1) / 2 batch -= mean batch = batch / std return...
(model_name).split("_")[-2].isdigit() ] print("[i] available epoch list: %s" % epoch_index, gen_models) i = epoch_index.index(int(epoch)) return gen_models[i] def vgg_preprocess(batch): # normalize using imagenet mean and std
64
64
146
17
47
leVirve/ELD
util/util.py
Python
vgg_preprocess
vgg_preprocess
62
75
62
63
48eada1e2599f19a65cf87fe94c4f1e16a35e08e
bigcode/the-stack
train
e11fc3a9b557dbf109f8944d
train
function
def save_image(image_numpy, image_path): image_pil = Image.fromarray(image_numpy) image_pil.save(image_path)
def save_image(image_numpy, image_path):
image_pil = Image.fromarray(image_numpy) image_pil.save(image_path)
for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean) def save_image(image_numpy, image_path):
64
64
28
9
55
leVirve/ELD
util/util.py
Python
save_image
save_image
91
93
91
91
030657307a3b2652c18fd963eebcf86958b4b9c0
bigcode/the-stack
train
13a8ecf85b72a4c3265b1868
train
function
def crop_center(img, cropx, cropy): _, _, y, x = img.shape startx = x // 2 - (cropx // 2) starty = y // 2 - (cropy // 2) return img[:, :, starty : starty + cropy, startx : startx + cropx].contiguous()
def crop_center(img, cropx, cropy):
_, _, y, x = img.shape startx = x // 2 - (cropx // 2) starty = y // 2 - (cropy // 2) return img[:, :, starty : starty + cropy, startx : startx + cropx].contiguous()
Image.fromarray(tensor2im(x)).show() elif isinstance(x, np.ndarray): Image.fromarray(x.astype(np.uint8)).show() else: raise NotImplementedError("vis for type [%s] is not implemented", type(x)) def crop_center(img, cropx, cropy):
64
64
79
11
53
leVirve/ELD
util/util.py
Python
crop_center
crop_center
135
139
135
135
72b51dc0dbf8ab59e3d743202168bcd130e0a25d
bigcode/the-stack
train
847122e7a9c962b826c06e7f
train
function
def set_vals_in_image3d( image3d, new_image3d, mask, channel_idx=None ) : if ( new_image3d.ndim == 3 ) : ir, ig, ib = [ image3d[...,k] for k in range(3) ] nr, ng, nb = [ new_image3d[...,k] for k in range(3) ] for old_ch, new_ch in zip( [ir, ig, ib], [nr, ng, nb]) : old_ch[mask] =...
def set_vals_in_image3d( image3d, new_image3d, mask, channel_idx=None ) :
if ( new_image3d.ndim == 3 ) : ir, ig, ib = [ image3d[...,k] for k in range(3) ] nr, ng, nb = [ new_image3d[...,k] for k in range(3) ] for old_ch, new_ch in zip( [ir, ig, ib], [nr, ng, nb]) : old_ch[mask] = new_ch[mask] return np.dstack( [ir, ig, ib]) else : n...
, proba_threshold, contrast_threshold, lh_threshold, verbose ) if ( this_bbox_lut is not None ) : bboxes.append( this_bbox_lut ) return bboxes def set_vals_in_image3d( image3d, new_image3d, mask, channel_idx=None ) :
64
64
203
24
39
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
set_vals_in_image3d
set_vals_in_image3d
404
418
404
404
3d185afd9364d699b9ad0880066c9e2dd0869cf1
bigcode/the-stack
train
dcebc68cc29dc7da96cdd4b7
train
function
def simple_decoder( file_path, textDet_model, scriptID_model=None, output_dir=None, dom_font=None, dark_text=None, rotated_text=False, proba_threshold=.5, lh_th...
def simple_decoder( file_path, textDet_model, scriptID_model=None, output_dir=None, dom_font=None, dark_text=None, rotated_text=False, proba_threshold=.5, lh_th...
""" INPUTS: ------------------------------------------------------------------------ | Mandentory Parameters ------------------------------------------------------------------------ file_path = str, path to a local file or URL to a web image textDet_model = keras model, p...
= reject_text_regions( decoded_results, prefix=prefix, save_mode=save_mode, output_dir=output_dir, proba_threshold=proba_threshold, contrast_threshol...
249
249
832
75
173
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
simple_decoder
simple_decoder
726
811
726
738
a05d5c50911307bd07e9c2afa93ab9a5de1975c0
bigcode/the-stack
train
edd0e1f945e785bb8fc73386
train
function
def order_points(pts): # sort the points based on their x-coordinates xSorted = pts[np.argsort(pts[:, 0]), :] # grab the left-most and right-most points from the sorted # x-roodinate points leftMost = xSorted[:2, :] rightMost = xSorted[2:, :] # now, sort the left-most coordinates according t...
def order_points(pts): # sort the points based on their x-coordinates
xSorted = pts[np.argsort(pts[:, 0]), :] # grab the left-most and right-most points from the sorted # x-roodinate points leftMost = xSorted[:2, :] rightMost = xSorted[2:, :] # now, sort the left-most coordinates according to their # y-coordinates so we can grab the top-left and bottom-left ...
1] == 4 ) : img = img[...,1:] return img def read_image( file_path ) : if ('http' in file_path) : return get_image_from_url( file_path ) else : return cv2.imread( file_path, 1 )[...,::-1] def order_points(pts): # sort the points based on their x-coordinates
83
83
279
18
65
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
order_points
order_points
51
72
51
52
cba82934fd7868de799580d50096a4656d5044e7
bigcode/the-stack
train
187531d7209e983155099492
train
function
def parse_detection_results( url, output_lut, text_proba=None, script_proba=None, show_region=True, fh=8) : img = read_image( url ) ih, iw = img.shape[:2] resize_factor = output_lut['resize'] if ( abs(resize_factor-1)> 0.02 ) : nh, nw = int(ih*resize_factor), int(iw*resize_factor) img = ...
def parse_detection_results( url, output_lut, text_proba=None, script_proba=None, show_region=True, fh=8) :
img = read_image( url ) ih, iw = img.shape[:2] resize_factor = output_lut['resize'] if ( abs(resize_factor-1)> 0.02 ) : nh, nw = int(ih*resize_factor), int(iw*resize_factor) img = cv2.resize( img, (nw, nh), interpolation=cv2.INTER_AREA if (resize_factor<1) else cv2.INTER_CUBIC ) # 1....
pyplot.subplot(222) pyplot.imshow( y) pyplot.axis('off') pyplot.title('Text Proba Map ' + ( ' scriptID={}'.format( scriptID ) if scriptID is not None else '' ) ) pyplot.subplot(223) pyplot.imshow( np.round( np.float32(img) * y).astype('uint8') ) pyplot.title('Overlaid') pyplot.axis('off'...
145
145
484
30
115
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
parse_detection_results
parse_detection_results
95
127
95
95
a9496ce44b4517b22a64f2e631c05e3cdeda9c78
bigcode/the-stack
train
ec9efffffe957bfcf2f38b9b
train
function
def text_proba_minmax( text_proba_all ) : proba_max = np.max( text_proba_all, axis = 0 ) proba_min = np.min( text_proba_all, axis = 0 ) border, text = proba_max[...,1],proba_max[...,2] nontext = proba_min[...,0] text_proba = np.dstack([nontext, border*2, text ]) return text_proba/np.sum(text_pro...
def text_proba_minmax( text_proba_all ) :
proba_max = np.max( text_proba_all, axis = 0 ) proba_min = np.min( text_proba_all, axis = 0 ) border, text = proba_max[...,1],proba_max[...,2] nontext = proba_min[...,0] text_proba = np.dstack([nontext, border*2, text ]) return text_proba/np.sum(text_proba,axis=-1,keepdims=True)
) return np.dstack( new_ch_list ) def script_proba_minmax( script_proba_all ) : idx = np.argmin( script_proba_all[:,1], axis = 0 ) return script_proba_all[idx] def text_proba_minmax( text_proba_all ) :
64
64
114
13
51
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
text_proba_minmax
text_proba_minmax
426
432
426
426
a9d2ad9511b263d2d1e3ae343cbe588bb23deaa5
bigcode/the-stack
train
62c42fb6a4e5ff9b0b027a92
train
function
def simple_detection( file_path, textDet_model, scriptID_model=None, dom_font=None, dark_text=None, verbose=2) : """ INPUTS: ---------------------------------------------------------------------...
def simple_detection( file_path, textDet_model, scriptID_model=None, dom_font=None, dark_text=None, verbose=2) :
""" INPUTS: ------------------------------------------------------------------------ | Mandentory Parameters ------------------------------------------------------------------------ file_path = str, path to a local file or URL to a web image textDet_model = keras model, p...
( scriptID_model is not None ) : script_proba = scriptID_model.predict(x)[0] else : script_proba = None verbose_print( verbose, "INFO: done text detection for factor", coef) # 3. update text_proba_list.append( np.expand_dims( text_proba, axis=0 ) ) script...
256
256
866
34
221
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
simple_detection
simple_detection
538
611
538
543
ef04ac7244d5e2a9df8e849c873c7f44afd050c8
bigcode/the-stack
train
dd4a2383873e5f1470088830
train
function
def visualize_text_proba_map( img, y, res, scriptID=None, fh=8 ) : ih, iw = img.shape[:2] fw = int( np.round( float(iw)/ih * fh ) ) pyplot.figure(figsize=(fw*2, fh*2)) pyplot.subplot(221) pyplot.imshow( img ) pyplot.axis('off') pyplot.title('Input') pyplot.subplot(222) pyplot.imshow(...
def visualize_text_proba_map( img, y, res, scriptID=None, fh=8 ) :
ih, iw = img.shape[:2] fw = int( np.round( float(iw)/ih * fh ) ) pyplot.figure(figsize=(fw*2, fh*2)) pyplot.subplot(221) pyplot.imshow( img ) pyplot.axis('off') pyplot.title('Input') pyplot.subplot(222) pyplot.imshow( y) pyplot.axis('off') pyplot.title('Text Proba Map ' + ( '...
], :] # return the coordinates in top-left, top-right, # bottom-right, and bottom-left order return np.array([tl, tr, br, bl], dtype="float32") def visualize_text_proba_map( img, y, res, scriptID=None, fh=8 ) :
64
64
201
22
42
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
visualize_text_proba_map
visualize_text_proba_map
74
93
74
74
82db30ec6f524d661564da2b5e3ae09a20d58383
bigcode/the-stack
train
642d40508b562afe79d9953e
train
function
def compute_fontsize_in_pixels_for_paper( image_height, font_size=10, paper_name='letter' ) : if ( paper_name == 'letter' ) : return compute_fontsize_in_pixels_for_letter( image_height, font_size ) else : target_paper_height = paperLut[paper_name][1] letter_paper_height = float(paperLut[...
def compute_fontsize_in_pixels_for_paper( image_height, font_size=10, paper_name='letter' ) :
if ( paper_name == 'letter' ) : return compute_fontsize_in_pixels_for_letter( image_height, font_size ) else : target_paper_height = paperLut[paper_name][1] letter_paper_height = float(paperLut['letter'][1]) return compute_fontsize_in_pixels_for_letter( image_height, font_size ) ...
= 1650. known_coef_pixel_height_to_fontsize = 1.5 return font_size * known_coef_pixel_height_to_fontsize / known_letter_height * image_height def compute_fontsize_in_pixels_for_paper( image_height, font_size=10, paper_name='letter' ) :
64
64
113
25
38
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
compute_fontsize_in_pixels_for_paper
compute_fontsize_in_pixels_for_paper
171
177
171
171
6aa6a639474fdbec5a25067db405c1e13b063253
bigcode/the-stack
train
d411084888aa17a5a35c55ba
train
function
def compute_fontsize_in_pixels_for_letter( image_height, font_size=10 ) : known_letter_height = 1650. known_coef_pixel_height_to_fontsize = 1.5 return font_size * known_coef_pixel_height_to_fontsize / known_letter_height * image_height
def compute_fontsize_in_pixels_for_letter( image_height, font_size=10 ) :
known_letter_height = 1650. known_coef_pixel_height_to_fontsize = 1.5 return font_size * known_coef_pixel_height_to_fontsize / known_letter_height * image_height
(i_ratio, p_ratio) if ( p_iou > iou ) : iou = p_iou sofar_best = name return sofar_best, paperLut[sofar_best] def compute_fontsize_in_pixels_for_letter( image_height, font_size=10 ) :
64
64
61
18
46
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
compute_fontsize_in_pixels_for_letter
compute_fontsize_in_pixels_for_letter
166
169
166
166
b826fa7c935ecbc34ca77d08434d8a5b48faf4e6
bigcode/the-stack
train
152674b2b1a48bf5e34a7307
train
function
def reject_text_regions( decoded_results, prefix, save_mode='buffer', output_dir=None, proba_threshold=0, contrast_threshold=0, lh_threshold=0, verbose = 1, n_jobs = 8 ) : if ( output_dir is None ) : this_output_dir = None else : this_output_dir = os.path.join( output_dir, prefix ) if ( ...
def reject_text_regions( decoded_results, prefix, save_mode='buffer', output_dir=None, proba_threshold=0, contrast_threshold=0, lh_threshold=0, verbose = 1, n_jobs = 8 ) :
if ( output_dir is None ) : this_output_dir = None else : this_output_dir = os.path.join( output_dir, prefix ) if ( not os.path.isdir( this_output_dir ) ) : os.makedirs( this_output_dir ) use_para = False try : from sklearn.externals.joblib import Parallel, de...
.jpg', wrapped_image[...,::-1], [int(cv2.IMWRITE_JPEG_QUALITY),99] ) this_bbox_lut['jpgbuf'] = buf.tolist() else : pass return this_bbox_lut def reject_text_regions( decoded_results, prefix, save_mode='buffer', output_dir=None, proba_threshold=0, contrast_threshold=0, lh_threshold=0, verbose = 1...
95
95
317
47
47
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
reject_text_regions
reject_text_regions
378
402
378
378
3b7d4d5efaedf838aae73a000ef7f7de7dd03bad
bigcode/the-stack
train
665d4fc68250b581833fe3e5
train
function
def estimate_dominant_fontsize( img, dark_text=None, verbose=0 ) : ih, iw = img.shape[:2] kernel = np.array( [1,2,3,4,5,4,3,2,1], dtype=np.float32) kernel = kernel / np.sum( kernel ) paper_name, _ = parse_paper_size( ih, iw ) est_lh = compute_fontsize_in_pixels_for_paper( max(ih,iw), font_size=10, p...
def estimate_dominant_fontsize( img, dark_text=None, verbose=0 ) :
ih, iw = img.shape[:2] kernel = np.array( [1,2,3,4,5,4,3,2,1], dtype=np.float32) kernel = kernel / np.sum( kernel ) paper_name, _ = parse_paper_size( ih, iw ) est_lh = compute_fontsize_in_pixels_for_paper( max(ih,iw), font_size=10, paper_name=paper_name ) # binarize image if ( img.ndim == 2 ...
size_in_pixels_for_letter( image_height, font_size=10 ) : known_letter_height = 1650. known_coef_pixel_height_to_fontsize = 1.5 return font_size * known_coef_pixel_height_to_fontsize / known_letter_height * image_height def compute_fontsize_in_pixels_for_paper( image_height, font_size=10, paper_name='lette...
190
190
634
19
170
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
estimate_dominant_fontsize
estimate_dominant_fontsize
179
226
179
179
35ae67f3fda561f2281338b191b169974e7f3a61
bigcode/the-stack
train
905d5ee3dd9e8541b2ced18c
train
function
def read_image( file_path ) : if ('http' in file_path) : return get_image_from_url( file_path ) else : return cv2.imread( file_path, 1 )[...,::-1]
def read_image( file_path ) :
if ('http' in file_path) : return get_image_from_url( file_path ) else : return cv2.imread( file_path, 1 )[...,::-1]
(Image.open(StringIO(response.content))) if ( img.ndim == 2 ) : img = np.dstack([img,img,img]) else : if ( img.shape[-1] == 4 ) : img = img[...,1:] return img def read_image( file_path ) :
64
64
47
8
55
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
read_image
read_image
45
49
45
45
c3c983a666a588101c36c966c22ed0cc2f05433d
bigcode/the-stack
train
00a33d5ad02f4f0babb47e06
train
function
def convert_imageArray_to_inputTensor( img, apply_padding=True ) : '''convert an raw uint8 image array to an input network tensor INPUT: img = np.ndarray, image array size= HxW or HxWx3, dtype=uint8 apply_padding = bool, whether or not force padding OUTPUT: x = np.nda...
def convert_imageArray_to_inputTensor( img, apply_padding=True ) :
'''convert an raw uint8 image array to an input network tensor INPUT: img = np.ndarray, image array size= HxW or HxWx3, dtype=uint8 apply_padding = bool, whether or not force padding OUTPUT: x = np.ndarray, network input tensor size=1xH'xW'x3, where H' a...
text_proba, script_proba, resize_factor, output_dir=output_dir, rotated_text=True, proba_threshold=proba_threshold, lh_threshold=lh_threshold, ...
118
118
396
15
103
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
convert_imageArray_to_inputTensor
convert_imageArray_to_inputTensor
892
926
892
892
0934ee718a5a117eb6f809b441eb5be351bd1787
bigcode/the-stack
train
a57b5cf8491e2a2f6ac70d2f
train
function
def verbose_print( verbose=0, *objects ) : if ( verbose == 0 ) : pass elif ( verbose == 1 ) : print( ' '.join( [ str(obj) for obj in objects ] ) ) else : print( time_stamp(), '|', ' '.join( [ str(obj) for obj in objects ] ) ) return
def verbose_print( verbose=0, *objects ) :
if ( verbose == 0 ) : pass elif ( verbose == 1 ) : print( ' '.join( [ str(obj) for obj in objects ] ) ) else : print( time_stamp(), '|', ' '.join( [ str(obj) for obj in objects ] ) ) return
n_obs = np.convolve( obs, kernel, mode='same') dominant_fontsize = np.argmax( n_obs ) return dominant_fontsize def time_stamp() : return '{}'.format( datetime.now() )[2:22] def verbose_print( verbose=0, *objects ) :
64
64
80
12
52
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
verbose_print
verbose_print
232
239
232
232
92dc30519b3f25977091f8f7bc9364312e36f494
bigcode/the-stack
train
e46b0a19a92f825be30ed507
train
function
def lazy_detection( file_path, textDet_model, scriptID_model=None, num_resolutions=5, verbose=2) : """ INPUTS: ------------------------------------------------------------------------ | Mandentory Parameters ...
def lazy_detection( file_path, textDet_model, scriptID_model=None, num_resolutions=5, verbose=2) :
""" INPUTS: ------------------------------------------------------------------------ | Mandentory Parameters ------------------------------------------------------------------------ file_path = str, path to a local file or URL to a web image textDet_model = keras model, p...
]) else : new_ch_list = [] for k in range(3) : old_ch = image3d[...,k] if ( k==channel_idx ) : old_ch[mask] = new_image3d[mask] new_ch_list.append( old_ch ) return np.dstack( new_ch_list ) def script_proba_minmax( script_proba_all ) : ...
256
256
1,211
31
225
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
lazy_detection
lazy_detection
434
536
434
438
2f6de152bad343fe8569216a5259537d8cc1b3bd
bigcode/the-stack
train
fb8d9f83a89a6d8035dfad92
train
function
def reject_one_text_region( idx, bbox_dec_result, prefix, save_mode='buffer', output_dir=None, proba_threshold=0, contrast_threshold=0, lh_threshold=0, verbose=0 ) : bbox, proba, wrapped_image = bbox_dec_result if ( proba < proba_threshold ) : verbose_print( verbose, "INFO: reject #", idx, "due to low p...
def reject_one_text_region( idx, bbox_dec_result, prefix, save_mode='buffer', output_dir=None, proba_threshold=0, contrast_threshold=0, lh_threshold=0, verbose=0 ) :
bbox, proba, wrapped_image = bbox_dec_result if ( proba < proba_threshold ) : verbose_print( verbose, "INFO: reject #", idx, "due to low proba,", proba, "<", proba_threshold ) return None upper_left, upper_right, lower_right, lower_left = bbox cnt = np.row_stack([upper_left, upper_right,...
0, backend='threading' )( delayed( decode_one_bbox )( text_proba, text_label, img, reg_stats, reg_idx ) for reg_idx in all_reg_indices ) return list(filter( lambda r : r is not None, results )) except : pass results = [] for reg_idx in all_reg_indices : res = decode_one_b...
156
156
522
44
111
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
reject_one_text_region
reject_one_text_region
343
376
343
343
0aefb9799a8c5013542ff28f442524455eb20b42
bigcode/the-stack
train
fa77e3b4ae80262e625e6d73
train
function
def decode_horizontal_text_bbox( text_proba, text_label, img, reg_stats ) : results = [] ih, iw = img.shape[:2] for reg_idx in range( 1, len( reg_stats ) ) : # 1. get CC bounding box info reg_left, reg_top, reg_width, reg_height, _ = reg_stats[reg_idx] # 2. relax text border ...
def decode_horizontal_text_bbox( text_proba, text_label, img, reg_stats ) :
results = [] ih, iw = img.shape[:2] for reg_idx in range( 1, len( reg_stats ) ) : # 1. get CC bounding box info reg_left, reg_top, reg_width, reg_height, _ = reg_stats[reg_idx] # 2. relax text border sk_h = max( 2, int(np.round(np.round(reg_height*.8)*.5)) ) sk_w = ma...
np.argmax( n_obs ) return dominant_fontsize def time_stamp() : return '{}'.format( datetime.now() )[2:22] def verbose_print( verbose=0, *objects ) : if ( verbose == 0 ) : pass elif ( verbose == 1 ) : print( ' '.join( [ str(obj) for obj in objects ] ) ) else : print( time_...
130
130
436
19
110
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
decode_horizontal_text_bbox
decode_horizontal_text_bbox
241
268
241
241
b6d0f0f1fef57ca9ba8c261e4df041c99ea03f95
bigcode/the-stack
train
d7387da3870b17c51dbd1351
train
function
def decode_rotated_text_bbox( text_proba, text_label, img, reg_stats, n_jobs=8 ) : use_para = False try : from sklearn.externals.joblib import Parallel, delayed use_para = True except : pass all_reg_indices = range( 1, len( reg_stats ) ) if ( use_para ) : try : ...
def decode_rotated_text_bbox( text_proba, text_label, img, reg_stats, n_jobs=8 ) :
use_para = False try : from sklearn.externals.joblib import Parallel, delayed use_para = True except : pass all_reg_indices = range( 1, len( reg_stats ) ) if ( use_para ) : try : # use parallel process results = Parallel( n_jobs=n_jobs, verbose...
in [ upper_left, upper_right, lower_right, lower_left ] ] # 6. update return [ corner_pts, pr, wrapped ] except : return None def decode_rotated_text_bbox( text_proba, text_label, img, reg_stats, n_jobs=8 ) :
64
64
214
25
38
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
decode_rotated_text_bbox
decode_rotated_text_bbox
320
340
320
320
dfcf0cb8601dd502f88c869844a6c5b5b9b29378
bigcode/the-stack
train
72fa0b43cadc1b5618e38ccb
train
function
def lazy_decoder( file_path, textDet_model, scriptID_model=None, num_resolutions=5, output_dir=None, proba_threshold=.33, lh_threshold=8, contrast_threshold=32., return_proba=T...
def lazy_decoder( file_path, textDet_model, scriptID_model=None, num_resolutions=5, output_dir=None, proba_threshold=.33, lh_threshold=8, contrast_threshold=32., return_proba=T...
""" INPUTS: ------------------------------------------------------------------------ | Mandentory Parameters ------------------------------------------------------------------------ file_path = str, path to a local file or URL to a web image textDet_model = keras model, p...
-7 """ resize_factor, text_proba, script_proba = simple_detection( file_path, textDet_model, scriptID_model, dom_font=do...
219
219
730
67
151
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
lazy_decoder
lazy_decoder
813
887
813
823
63b89bd95a1244c4a2b5502fb63b2812e0e42576
bigcode/the-stack
train
7b9b58222ef45cba15b71e65
train
function
def get_topK_scriptID( script_proba, topK = 2 ) : lut = [ 'NonText', 'Latin', 'Hebrew', 'Cyrillic', 'Arabic', 'Chinese', 'TextButUnknown'] indices = np.argsort( script_proba )[::-1] scriptIDs = ["{}-{:.2f}".format(lut[indices[k]], script_proba[indices[k]] ) for k in range( topK )] return " | ".join( scr...
def get_topK_scriptID( script_proba, topK = 2 ) :
lut = [ 'NonText', 'Latin', 'Hebrew', 'Cyrillic', 'Arabic', 'Chinese', 'TextButUnknown'] indices = np.argsort( script_proba )[::-1] scriptIDs = ["{}-{:.2f}".format(lut[indices[k]], script_proba[indices[k]] ) for k in range( topK )] return " | ".join( scriptIDs )
ba_map( img, text_proba, debug, scriptID, fh=fh ) else : pyplot.figure( figsize=(10,10)) pyplot.imshow( debug ) pyplot.title('detected text regions') def get_topK_scriptID( script_proba, topK = 2 ) :
64
64
109
18
46
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
get_topK_scriptID
get_topK_scriptID
129
133
129
129
ec591e0082c5bb104910c4e4f40bb0a7636064ca
bigcode/the-stack
train
2b9e1852330503aaad8831e9
train
function
def decode_scriptID( dist ) : '''decode scriptID from a given distribution INPUT: dist = 1D or 2D np.ndarray if 1D, size of 7, if 2D, size of nb_samples-by-7 OUTPUT: scriptID = 1D np.ndarray ''' assert dist.ndim <=2 if ( dist.ndim == 1 ) : di...
def decode_scriptID( dist ) :
'''decode scriptID from a given distribution INPUT: dist = 1D or 2D np.ndarray if 1D, size of 7, if 2D, size of nb_samples-by-7 OUTPUT: scriptID = 1D np.ndarray ''' assert dist.ndim <=2 if ( dist.ndim == 1 ) : dist = dist.reshape([1,-1]) ...
4. pad a 3D image array to a 4D tensor x = np.expand_dims( x, axis = 0 ) # 5. substract means learned from image-net x = preprocess_input( x ) return x def decode_scriptID( dist ) :
64
64
193
8
55
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
decode_scriptID
decode_scriptID
928
949
928
928
3cae989140738ffee38aa3cb25f150db769b2ef2
bigcode/the-stack
train
c2588555810db8afcc3ad7bf
train
function
def get_image_from_url(url) : '''read a web image from url INPUT: url = string, web address OUTPUT: img = np.ndarray ''' response = requests.get(url) img = np.array(Image.open(StringIO(response.content))) if ( img.ndim == 2 ) : img = np.dstack([img,img,img]) else ...
def get_image_from_url(url) :
'''read a web image from url INPUT: url = string, web address OUTPUT: img = np.ndarray ''' response = requests.get(url) img = np.array(Image.open(StringIO(response.content))) if ( img.ndim == 2 ) : img = np.dstack([img,img,img]) else : if ( img.shape[-1] =...
: from io import StringIO from matplotlib import pyplot from skimage.morphology import dilation from skimage.filters import threshold_otsu, threshold_niblack, threshold_sauvola MINSIDE=256. MAXSIDE=3200. def get_image_from_url(url) :
64
64
107
8
56
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
get_image_from_url
get_image_from_url
29
43
29
29
f7ae246f20d50923881c38b82c68736e9c6aba5c
bigcode/the-stack
train
7dd1ea0be5028fce147257e1
train
function
def dump_results( file_path, text_proba, script_proba, resize_factor=1, output_dir=None, rotated_text=False, proba_threshold=.5, lh_threshold=15, contrast_threshold=24., ...
def dump_results( file_path, text_proba, script_proba, resize_factor=1, output_dir=None, rotated_text=False, proba_threshold=.5, lh_threshold=15, contrast_threshold=24., ...
""" INPUTS: ------------------------------------------------------------------------ | Mandentory Parameters ------------------------------------------------------------------------ file_path = str, url or file path to the raw image text_proba = np.ndarray, text probabili...
(iw*resize_factor) img = cv2.resize( img, (nw, nh), interpolation=method ) else : resize_factor = 1 nh, nw = ih, iw # 2. convert input image to network tensor verbose_print( verbose, "INFO: begin FCN text detection") x = convert_imageArray_to_inputTensor( img ) # 3. predict t...
256
256
1,291
64
191
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
dump_results
dump_results
614
724
614
624
7038b6c4b663fa1ed94999b952cea1d5f9e34d13
bigcode/the-stack
train
6c7c39c97acefd554498c4c3
train
function
def uncompress_jpeg_buffer( bbox_lut ) : jpeg_buf = bbox_lut['jpgbuf'] reg_img = cv2.imdecode( np.array( jpeg_buf, dtype='uint8' ), 1 ) # bgr reg_img = reg_img[...,::-1] # rgb return reg_img
def uncompress_jpeg_buffer( bbox_lut ) :
jpeg_buf = bbox_lut['jpgbuf'] reg_img = cv2.imdecode( np.array( jpeg_buf, dtype='uint8' ), 1 ) # bgr reg_img = reg_img[...,::-1] # rgb return reg_img
script_proba )[::-1] scriptIDs = ["{}-{:.2f}".format(lut[indices[k]], script_proba[indices[k]] ) for k in range( topK )] return " | ".join( scriptIDs ) def uncompress_jpeg_buffer( bbox_lut ) :
64
64
69
12
52
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
uncompress_jpeg_buffer
uncompress_jpeg_buffer
135
139
135
135
dadea9f527044864603e2c6de19867b2675a93af
bigcode/the-stack
train
1e2dca2f71aea952c9bc4c51
train
function
def decode_one_bbox( text_proba, text_label, img, reg_stats, reg_idx ) : ih, iw = img.shape[:2] try : # 1. get CC bounding box info reg_left, reg_top, reg_width, reg_height, _ = reg_stats[reg_idx] reg_proba = text_proba[reg_top:reg_top+reg_height+1,reg_left:reg_left+reg_width+1] ...
def decode_one_bbox( text_proba, text_label, img, reg_stats, reg_idx ) :
ih, iw = img.shape[:2] try : # 1. get CC bounding box info reg_left, reg_top, reg_width, reg_height, _ = reg_stats[reg_idx] reg_proba = text_proba[reg_top:reg_top+reg_height+1,reg_left:reg_left+reg_width+1] reg_mask = text_label[reg_top:reg_top+reg_height+1,reg_left:reg_left+reg_...
1 reg_width = reg_right - reg_left + 1 # 3. crop region for fast analysis reg_proba = text_proba[reg_top:reg_top+reg_height+1,reg_left:reg_left+reg_width+1] reg_mask = text_label[reg_top:reg_top+reg_height+1,reg_left:reg_left+reg_width+1] == reg_idx reg_img = img[reg_top:reg_top...
256
256
919
21
234
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
decode_one_bbox
decode_one_bbox
270
318
270
270
523e50e0303248e70cfafbee20c1bbb104e73f8e
bigcode/the-stack
train
1275c8cdf78f429ec24c906c
train
function
def script_proba_minmax( script_proba_all ) : idx = np.argmin( script_proba_all[:,1], axis = 0 ) return script_proba_all[idx]
def script_proba_minmax( script_proba_all ) :
idx = np.argmin( script_proba_all[:,1], axis = 0 ) return script_proba_all[idx]
old_ch = image3d[...,k] if ( k==channel_idx ) : old_ch[mask] = new_image3d[mask] new_ch_list.append( old_ch ) return np.dstack( new_ch_list ) def script_proba_minmax( script_proba_all ) :
64
64
40
13
51
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
script_proba_minmax
script_proba_minmax
421
423
421
421
04ff507f27c6d1043af5e0b3dc74af87497f3402
bigcode/the-stack
train
61db6203bd06cabe780c0139
train
function
def time_stamp() : return '{}'.format( datetime.now() )[2:22]
def time_stamp() :
return '{}'.format( datetime.now() )[2:22]
)+1) for k, v in zip( keys, vals ) : obs[k] = float(v)/vall n_obs = np.convolve( obs, kernel, mode='same') dominant_fontsize = np.argmax( n_obs ) return dominant_fontsize def time_stamp() :
64
64
19
5
58
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
time_stamp
time_stamp
229
230
229
229
8318fafdc6e92688ca367923dece35532554ce70
bigcode/the-stack
train
2dc7d1e256bc750bcf7154e2
train
function
def get_bbox_polygon( bbox_lut ) : cnt_x = bbox_lut['cntx'] cnt_y = bbox_lut['cnty'] pts = np.column_stack( [cnt_x, cnt_y] ) return pts
def get_bbox_polygon( bbox_lut ) :
cnt_x = bbox_lut['cntx'] cnt_y = bbox_lut['cnty'] pts = np.column_stack( [cnt_x, cnt_y] ) return pts
= bbox_lut['jpgbuf'] reg_img = cv2.imdecode( np.array( jpeg_buf, dtype='uint8' ), 1 ) # bgr reg_img = reg_img[...,::-1] # rgb return reg_img def get_bbox_polygon( bbox_lut ) :
64
64
51
10
53
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
get_bbox_polygon
get_bbox_polygon
141
145
141
141
7810a55e491d21ab1a47920b1c6e0d76811a220d
bigcode/the-stack
train
6a27e2a59bbdafe54cdaafd8
train
function
def parse_paper_size( image_width, image_height ) : if ( image_height < image_width ) : image_width, image_height = image_height, image_width i_ratio = float(image_width)/image_height iou = 0 sofar_best = None for name, (pw, ph) in iteritems(paperLut) : p_ratio = float(pw)/ph ...
def parse_paper_size( image_width, image_height ) :
if ( image_height < image_width ) : image_width, image_height = image_height, image_width i_ratio = float(image_width)/image_height iou = 0 sofar_best = None for name, (pw, ph) in iteritems(paperLut) : p_ratio = float(pw)/ph p_iou = min(i_ratio, p_ratio)/max(i_ratio, p_ratio)...
_lut['cnty'] pts = np.column_stack( [cnt_x, cnt_y] ) return pts paperLut ={ 'A4': [210, 297], 'letter' : [216,279], } def parse_paper_size( image_width, image_height ) :
64
64
148
13
51
isi-vista/textDetectionWithScriptID
lib/textDetDec.py
Python
parse_paper_size
parse_paper_size
152
164
152
152
67c43807f3ad04808e3ed5831a048273d6db1b96
bigcode/the-stack
train