max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
GearBot/Util/Pages.py | JohnyTheCarrot/GearBot | 0 | 4600 | import discord
from Util import Utils, Emoji, Translator
page_handlers = dict()
known_messages = dict()
def on_ready(bot):
load_from_disc()
def register(type, init, update, sender_only=False):
page_handlers[type] = {
"init": init,
"update": update,
"sender_only": sender_only
}... | import discord
from Util import Utils, Emoji, Translator
page_handlers = dict()
known_messages = dict()
def on_ready(bot):
load_from_disc()
def register(type, init, update, sender_only=False):
page_handlers[type] = {
"init": init,
"update": update,
"sender_only": sender_only
}... | en | 0.748671 | # single 2k line, split smaller | 2.180439 | 2 |
software/Opal/spud/diamond/build/lib.linux-x86_64-2.7/diamond/dialogs.py | msc-acse/acse-9-independent-research-project-Wade003 | 2 | 4601 | #!/usr/bin/env python
# This file is part of Diamond.
#
# Diamond is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | #!/usr/bin/env python
# This file is part of Diamond.
#
# Diamond is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | en | 0.743369 | #!/usr/bin/env python # This file is part of Diamond. # # Diamond is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ... | 2.597278 | 3 |
src/mazes.py | tim-fi/pyxel_games | 2 | 4602 | from __future__ import annotations
from dataclasses import dataclass, field, InitVar
from typing import List, Tuple, Iterator, Iterable, Optional
from random import choice
import pyxel
# -------------------------------------------------------
# Types
# -------------------------------------------------------
Maze = T... | from __future__ import annotations
from dataclasses import dataclass, field, InitVar
from typing import List, Tuple, Iterator, Iterable, Optional
from random import choice
import pyxel
# -------------------------------------------------------
# Types
# -------------------------------------------------------
Maze = T... | en | 0.167656 | # ------------------------------------------------------- # Types # ------------------------------------------------------- # ------------------------------------------------------- # Constants # ------------------------------------------------------- # Flags # Calculated # ---------------------------------------------... | 2.687738 | 3 |
bobjiang/settings.py | bobjiangps/django-blog | 3 | 4603 | <reponame>bobjiangps/django-blog<filename>bobjiang/settings.py
"""
Django settings for bobjiang project.
Generated by 'django-admin startproject' using Django 2.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https... | """
Django settings for bobjiang project.
Generated by 'django-admin startproject' using Django 2.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
i... | en | 0.590093 | Django settings for bobjiang project. Generated by 'django-admin startproject' using Django 2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ # Build paths inside... | 1.99311 | 2 |
Users/models.py | titusnjuguna/FreeDom | 1 | 4604 | from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',
upload_to='profile_pic/')
... | from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',
upload_to='profile_pic/')
... | none | 1 | 2.470039 | 2 | |
dvc/__init__.py | zjj2wry/dvc | 0 | 4605 | <reponame>zjj2wry/dvc<filename>dvc/__init__.py
"""
DVC
----
Make your data science projects reproducible and shareable.
"""
import os
import warnings
VERSION_BASE = '0.23.2'
__version__ = VERSION_BASE
PACKAGEPATH = os.path.abspath(os.path.dirname(__file__))
HOMEPATH = os.path.dirname(PACKAGEPATH)
VERSIONPATH = os.pa... | """
DVC
----
Make your data science projects reproducible and shareable.
"""
import os
import warnings
VERSION_BASE = '0.23.2'
__version__ = VERSION_BASE
PACKAGEPATH = os.path.abspath(os.path.dirname(__file__))
HOMEPATH = os.path.dirname(PACKAGEPATH)
VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py')
def _updat... | en | 0.90598 | DVC ---- Make your data science projects reproducible and shareable. Dynamically update version file. # Write a helper file, that will be installed with the package # and will provide a true version of the installed dvc Remove version.py so that it doesn't get into the release. # dvc is run directly from source without... | 2.01966 | 2 |
pkg_dir/src/utils/notion_utils.py | robperch/robase_datalysis | 2 | 4606 | ## MODULE WITH UTIL FUNCTIONS - NOTION
"----------------------------------------------------------------------------------------------------------------------"
####################################################### Imports ########################################################
"---------------------------------... | ## MODULE WITH UTIL FUNCTIONS - NOTION
"----------------------------------------------------------------------------------------------------------------------"
####################################################### Imports ########################################################
"---------------------------------... | en | 0.71388 | ## MODULE WITH UTIL FUNCTIONS - NOTION ####################################################### Imports ######################################################## ## Standard library imports ## Third party imports ## Local application imports ####################################################### Functions ##############... | 2.015178 | 2 |
libpermian/issueanalyzer/test_baseissue.py | velezd/permian | 0 | 4607 | <filename>libpermian/issueanalyzer/test_baseissue.py
import unittest
import logging
import contextlib
from libpermian.settings import Settings
from .proxy import IssueAnalyzerProxy
from .base import BaseAnalyzer, BaseIssue
from .issueset import IssueSet
LOGGER = logging.getLogger('test')
class NewIssue(BaseIssue):
... | <filename>libpermian/issueanalyzer/test_baseissue.py
import unittest
import logging
import contextlib
from libpermian.settings import Settings
from .proxy import IssueAnalyzerProxy
from .base import BaseAnalyzer, BaseIssue
from .issueset import IssueSet
LOGGER = logging.getLogger('test')
class NewIssue(BaseIssue):
... | en | 0.967834 | # test lookup was called # TrackedResolvedIssue should behave the same way as TrackedUnresolvedIssue # so just inherit the whole test case to run the very same test # sync the issues so that lookup is not called => logged during submit # repeated submit doesn't do anything # This should have no effect # The update_issu... | 2.39226 | 2 |
naplib/alignment/prosodylab_aligner/__main__.py | gavinmischler/naplib-python | 1 | 4608 | <filename>naplib/alignment/prosodylab_aligner/__main__.py
# Copyright (c) 2011-2014 <NAME> and <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# withou... | <filename>naplib/alignment/prosodylab_aligner/__main__.py
# Copyright (c) 2011-2014 <NAME> and <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# withou... | en | 0.76501 | # Copyright (c) 2011-2014 <NAME> and <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publi... | 2.28259 | 2 |
init/build_statements.py | andgein/sis-2017-winter-olymp | 0 | 4609 | <reponame>andgein/sis-2017-winter-olymp<filename>init/build_statements.py
#!/usr/bin/env python3
import codecs
import os
import os.path
import shutil
import subprocess
import logging
import glob
import json
CONTEST_DIR = 'polygon-contest'
INIT_FILE = 'init.txt'
BUILD_DIR = 'build'
LANGUAGE = 'russian'
FILES_DIR = 'fi... | #!/usr/bin/env python3
import codecs
import os
import os.path
import shutil
import subprocess
import logging
import glob
import json
CONTEST_DIR = 'polygon-contest'
INIT_FILE = 'init.txt'
BUILD_DIR = 'build'
LANGUAGE = 'russian'
FILES_DIR = 'files-' + LANGUAGE
def time_limit_from_int(tl):
tl //= 1000
return... | fr | 0.221828 | #!/usr/bin/env python3 | 2.193841 | 2 |
conanfile.py | mmurooka/mc_rtc_data | 1 | 4610 | # -*- coding: utf-8 -*-
#
from conans import python_requires
import conans.tools as tools
import os
base = python_requires("Eigen3ToPython/latest@multi-contact/dev")
class MCRTCDataConan(base.Eigen3ToPythonConan):
name = "mc_rtc_data"
version = "1.0.4"
description = "Environments/Robots description for m... | # -*- coding: utf-8 -*-
#
from conans import python_requires
import conans.tools as tools
import os
base = python_requires("Eigen3ToPython/latest@multi-contact/dev")
class MCRTCDataConan(base.Eigen3ToPythonConan):
name = "mc_rtc_data"
version = "1.0.4"
description = "Environments/Robots description for m... | en | 0.770005 | # -*- coding: utf-8 -*- # | 1.759021 | 2 |
hyperion/migrations/0006_auto_20190218_2251.py | ExiaSR/hyperion | 3 | 4611 | <filename>hyperion/migrations/0006_auto_20190218_2251.py
# Generated by Django 2.1.5 on 2019-02-18 22:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hyperion', '0005_auto_20190212_2116'),
]
operations = [
... | <filename>hyperion/migrations/0006_auto_20190218_2251.py
# Generated by Django 2.1.5 on 2019-02-18 22:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hyperion', '0005_auto_20190212_2116'),
]
operations = [
... | en | 0.730537 | # Generated by Django 2.1.5 on 2019-02-18 22:51 | 1.887926 | 2 |
pottan_ocr/utils.py | nithyadurai87/pottan-ocr-tamil | 5 | 4612 | import torch
import json
import numpy as np
from torch.autograd import Variable
import gzip
import yaml
from re import split
from matplotlib import pyplot
def showImg( im ):
pyplot.imshow( im )
pyplot.show()
def myOpen( fname, mode ):
return open( fname, mode, encoding="utf-8" )
def readFile( fname ):
... | import torch
import json
import numpy as np
from torch.autograd import Variable
import gzip
import yaml
from re import split
from matplotlib import pyplot
def showImg( im ):
pyplot.imshow( im )
pyplot.show()
def myOpen( fname, mode ):
return open( fname, mode, encoding="utf-8" )
def readFile( fname ):
... | en | 0.801349 | Compute average for `torch.Variable` and `torch.Tensor`. Load a pretrained model into given model # Handle the case of some old torch version. It will save the data as module.<xyz> . Handle it | 2.33429 | 2 |
pyvips/error.py | kleisauke/pyvips | 0 | 4613 | <gh_stars>0
# errors from libvips
import sys
import logging
from pyvips import ffi, vips_lib
logger = logging.getLogger(__name__)
_is_PY3 = sys.version_info[0] == 3
if _is_PY3:
text_type = str
else:
text_type = unicode
ffi.cdef('''
const char* vips_error_buffer (void);
void vips_error_clear (void)... | # errors from libvips
import sys
import logging
from pyvips import ffi, vips_lib
logger = logging.getLogger(__name__)
_is_PY3 = sys.version_info[0] == 3
if _is_PY3:
text_type = str
else:
text_type = unicode
ffi.cdef('''
const char* vips_error_buffer (void);
void vips_error_clear (void);
''')
de... | en | 0.731439 | # errors from libvips const char* vips_error_buffer (void); void vips_error_clear (void); Convert to a byte string. Convert a Python unicode string to a utf-8-encoded byte string. You must call this on strings you pass to libvips. Convert to a unicode string. If x is a byte string, assume it is utf-8 ... | 2.551768 | 3 |
population_estimator/curses_io.py | cruzanta/population-estimator | 1 | 4614 | <filename>population_estimator/curses_io.py
#!/usr/bin/env python
"""
Module for painting output on and obtaining input from a text-based terminal
window using the curses library.
"""
import curses
import textwrap
def display_string(screen, a_string, output_line):
# Paints a string on a text-based terminal wind... | <filename>population_estimator/curses_io.py
#!/usr/bin/env python
"""
Module for painting output on and obtaining input from a text-based terminal
window using the curses library.
"""
import curses
import textwrap
def display_string(screen, a_string, output_line):
# Paints a string on a text-based terminal wind... | en | 0.896846 | #!/usr/bin/env python Module for painting output on and obtaining input from a text-based terminal window using the curses library. # Paints a string on a text-based terminal window. # Paints each item of a list on a text-based terminal window. # Paints each key, value pair of a dict on a text-based terminal window. Pa... | 3.85061 | 4 |
tools/micropython-mockup/urandom.py | hwinther/lanot | 0 | 4615 | def randrange(n, y):
pass
| def randrange(n, y):
pass
| none | 1 | 0.90243 | 1 | |
SAP/released_tr_email_sender/ui.py | botisko/personal_programs | 0 | 4616 | <gh_stars>0
import json
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tr_data import TRData, NO_DATA_MEETS_CRITERIA
from email_text import email_body_template
from helpers import send_email
RECIPIENT = <email_address>
EXCEPTION_FILE = "tr_number_exceptions.json"
class TrEmailSend... | import json
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tr_data import TRData, NO_DATA_MEETS_CRITERIA
from email_text import email_body_template
from helpers import send_email
RECIPIENT = <email_address>
EXCEPTION_FILE = "tr_number_exceptions.json"
class TrEmailSender:
def... | en | 0.668277 | # WINDOW CREATION # TTILE LABEL # BUTTONS # list of TRs # TREE VIEW for list display # Update columns # insert data #LAYOUT PLACEMENT # DISPLAY WINDOW # delete all rows in tree view # update with new data # check if not in exception # if all TRs are in exceptions, insert only pre-defined information # get selected line... | 2.834535 | 3 |
AI-Practice-Tensorflow-Notes-master/opt/opt4_8_backward.py | foochane/Tensorflow-Learning | 2 | 4617 | #coding:utf-8
#0导入模块 ,生成模拟数据集
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import opt4_8_generateds
import opt4_8_forward
STEPS = 40000
BATCH_SIZE = 30
LEARNING_RATE_BASE = 0.001
LEARNING_RATE_DECAY = 0.999
REGULARIZER = 0.01
def backward():
x = tf.placeholder(tf.float32, shape=(None, ... | #coding:utf-8
#0导入模块 ,生成模拟数据集
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import opt4_8_generateds
import opt4_8_forward
STEPS = 40000
BATCH_SIZE = 30
LEARNING_RATE_BASE = 0.001
LEARNING_RATE_DECAY = 0.999
REGULARIZER = 0.01
def backward():
x = tf.placeholder(tf.float32, shape=(None, ... | zh | 0.959217 | #coding:utf-8 #0导入模块 ,生成模拟数据集 #定义损失函数 #定义反向传播方法:包含正则化 | 3.103463 | 3 |
test/examples/integrated/codec/vip/vip_agent.py | rodrigomelo9/uvm-python | 140 | 4618 | <gh_stars>100-1000
#//
#// -------------------------------------------------------------
#// Copyright 2011 Synopsys, Inc.
#// Copyright 2019-2020 <NAME> (tpoikela)
#// All Rights Reserved Worldwide
#//
#// Licensed under the Apache License, Version 2.0 (the
#// "License"); you may not use this file ex... | #//
#// -------------------------------------------------------------
#// Copyright 2011 Synopsys, Inc.
#// Copyright 2019-2020 <NAME> (tpoikela)
#// All Rights Reserved Worldwide
#//
#// Licensed under the Apache License, Version 2.0 (the
#// "License"); you may not use this file except in
#// comp... | en | 0.584565 | #// #// ------------------------------------------------------------- #// Copyright 2011 Synopsys, Inc. #// Copyright 2019-2020 <NAME> (tpoikela) #// All Rights Reserved Worldwide #// #// Licensed under the Apache License, Version 2.0 (the #// "License"); you may not use this file except in #// compli... | 1.906141 | 2 |
tests/test_transliterate.py | abosoar/camel_tools | 1 | 4619 | # -*- coding: utf-8 -*-
# MIT License
#
# Copyright 2018-2020 New York University A<NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation ... | # -*- coding: utf-8 -*-
# MIT License
#
# Copyright 2018-2020 New York University A<NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation ... | en | 0.810241 | # -*- coding: utf-8 -*- # MIT License # # Copyright 2018-2020 New York University A<NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t... | 2.077935 | 2 |
source/code/build-instance-scheduler-template.py | liangruibupt/aws-instance-scheduler | 0 | 4620 | ######################################################################################################################
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | ######################################################################################################################
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | en | 0.494546 | ###################################################################################################################### # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ... | 1.96937 | 2 |
src/parse.py | StanfordAHA/Configuration | 0 | 4621 | ###############################################################################
# file -- parse.py --
# Top contributors (to current version):
# <NAME>
# This file is part of the configuration finder for the Stanford AHA project.
# Copyright (c) 2021 by the authors listed in the file AUTHORS
# in the top-level ... | ###############################################################################
# file -- parse.py --
# Top contributors (to current version):
# <NAME>
# This file is part of the configuration finder for the Stanford AHA project.
# Copyright (c) 2021 by the authors listed in the file AUTHORS
# in the top-level ... | en | 0.663393 | ############################################################################### # file -- parse.py -- # Top contributors (to current version): # <NAME> # This file is part of the configuration finder for the Stanford AHA project. # Copyright (c) 2021 by the authors listed in the file AUTHORS # in the top-level ... | 1.850976 | 2 |
neyesem/main.py | omerfarukbaysal/neyesem | 0 | 4622 | <reponame>omerfarukbaysal/neyesem<gh_stars>0
from flask import Blueprint, render_template, redirect, url_for, request, flash, make_response
from werkzeug.security import generate_password_hash
from flask_login import login_required, current_user
from . import db
import datetime
from .models import Visitor, User
main =... | from flask import Blueprint, render_template, redirect, url_for, request, flash, make_response
from werkzeug.security import generate_password_hash
from flask_login import login_required, current_user
from . import db
import datetime
from .models import Visitor, User
main = Blueprint('main', __name__)
@main.route('/... | en | 0.832692 | #control visitor with cookies #visit=True # if this returns a user, then the email already exists in database # if a user is found, we want to redirect back to signup page so user can try again # create a new user with the form data. Hash the password so the plaintext version isn't saved. # add the new user to the data... | 2.692707 | 3 |
00-Aulas/Aula007_2.py | AmandaRH07/Python_Entra21 | 0 | 4623 | # Funções
cabecalho = "SISTEMA DE CADASTRO DE FUNCIONARIO\n\n\n"
rodape = "\n\n\n Obrigada pela preferencia"
def imprimir_tela(conteudo):
print(cabecalho)
#print(opcao_menu)
print(conteudo)
print(rodape)
def ler_opcoes():
opcao = int(input("Insira a opção: "))
return opcao
def carregar_o... | # Funções
cabecalho = "SISTEMA DE CADASTRO DE FUNCIONARIO\n\n\n"
rodape = "\n\n\n Obrigada pela preferencia"
def imprimir_tela(conteudo):
print(cabecalho)
#print(opcao_menu)
print(conteudo)
print(rodape)
def ler_opcoes():
opcao = int(input("Insira a opção: "))
return opcao
def carregar_o... | pt | 0.921404 | # Funções #print(opcao_menu) | 3.562562 | 4 |
ast_version/src/binop.py | lucassa3/CCompiler | 1 | 4624 | <reponame>lucassa3/CCompiler<filename>ast_version/src/binop.py
from node import Node
class BinOp(Node):
def eval(self, st):
a = self.children[0].eval(st)
b = self.children[1].eval(st)
if self.value == "MINUS":
return a - b
elif self.value == "PLUS":
return a + b
elif self.value == "MULT":
... | from node import Node
class BinOp(Node):
def eval(self, st):
a = self.children[0].eval(st)
b = self.children[1].eval(st)
if self.value == "MINUS":
return a - b
elif self.value == "PLUS":
return a + b
elif self.value == "MULT":
return a * b
elif self.value == "DIV":
return a // b... | none | 1 | 3.658713 | 4 | |
aqt/installer.py | pylipp/aqtinstall | 0 | 4625 | #!/usr/bin/env python3
#
# Copyright (C) 2018 <NAME> <<EMAIL>>
# Copyright (C) 2019,2020 <NAME> <<EMAIL>>
# Copyright (C) 2020, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software withou... | #!/usr/bin/env python3
#
# Copyright (C) 2018 <NAME> <<EMAIL>>
# Copyright (C) 2019,2020 <NAME> <<EMAIL>>
# Copyright (C) 2020, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software withou... | en | 0.732871 | #!/usr/bin/env python3 # # Copyright (C) 2018 <NAME> <<EMAIL>> # Copyright (C) 2019,2020 <NAME> <<EMAIL>> # Copyright (C) 2020, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software withou... | 1.760282 | 2 |
lib/django-0.96/django/views/generic/list_detail.py | MiCHiLU/google_appengine_sdk | 790 | 4626 | from django.template import loader, RequestContext
from django.http import Http404, HttpResponse
from django.core.xheaders import populate_xheaders
from django.core.paginator import ObjectPaginator, InvalidPage
from django.core.exceptions import ObjectDoesNotExist
def object_list(request, queryset, paginate_by=None, p... | from django.template import loader, RequestContext
from django.http import Http404, HttpResponse
from django.core.xheaders import populate_xheaders
from django.core.paginator import ObjectPaginator, InvalidPage
from django.core.exceptions import ObjectDoesNotExist
def object_list(request, queryset, paginate_by=None, p... | en | 0.75824 | Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated are the results paginated? results_per_page number of objects per page (if paginated) has_next is there a ... | 2.314111 | 2 |
pax/_src/core/utility_modules.py | NTT123/pax | 11 | 4627 | """Utility Modules."""
from typing import Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union
import jax
import jax.numpy as jnp
from .module import Module, parameters_method
T = TypeVar("T", bound=Module)
O = TypeVar("O")
class ParameterModule(Module):
"""A PAX module that registers attributes as ... | """Utility Modules."""
from typing import Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union
import jax
import jax.numpy as jnp
from .module import Module, parameters_method
T = TypeVar("T", bound=Module)
O = TypeVar("O")
class ParameterModule(Module):
"""A PAX module that registers attributes as ... | en | 0.408491 | Utility Modules. A PAX module that registers attributes as parameters by default. A PAX module that registers attributes as states by default. A lazy module is a module that only creates submodules when needed. Example: >>> from dataclasses import dataclass >>> @dataclass ... class MLP(pax.experiment... | 3.114794 | 3 |
src/richie/apps/courses/lms/edx.py | kernicPanel/richie | 0 | 4628 | <reponame>kernicPanel/richie
"""
Backend to connect Open edX richie with an LMS
"""
import logging
import re
import requests
from requests.auth import AuthBase
from ..serializers import SyncCourseRunSerializer
from .base import BaseLMSBackend
logger = logging.getLogger(__name__)
def split_course_key(key):
"""S... | """
Backend to connect Open edX richie with an LMS
"""
import logging
import re
import requests
from requests.auth import AuthBase
from ..serializers import SyncCourseRunSerializer
from .base import BaseLMSBackend
logger = logging.getLogger(__name__)
def split_course_key(key):
"""Split an OpenEdX course key by... | en | 0.765348 | Backend to connect Open edX richie with an LMS Split an OpenEdX course key by organization, course and course run codes. We first try splitting the key as a version 1 key (course-v1:org+course+run) and fallback the old version (org/course/run). Attach HTTP token authentication to the given Request object. Set-... | 2.76265 | 3 |
BitTorrent-5.2.2/BTL/brpclib.py | jpabb7/p2pScrapper | 4 | 4629 | # by <NAME>
import xmlrpclib
from xmlrpclib2 import *
from BTL import brpc
old_PyCurlTransport = PyCurlTransport
class PyCurlTransport(old_PyCurlTransport):
def set_connection_params(self, h):
h.add_header('User-Agent', "brpclib.py/1.0")
h.add_header('Connection', "Keep-Alive")
h.add_head... | # by <NAME>
import xmlrpclib
from xmlrpclib2 import *
from BTL import brpc
old_PyCurlTransport = PyCurlTransport
class PyCurlTransport(old_PyCurlTransport):
def set_connection_params(self, h):
h.add_header('User-Agent', "brpclib.py/1.0")
h.add_header('Connection', "Keep-Alive")
h.add_head... | en | 0.761288 | # by <NAME> # read response from input file/socket, and parse it # -------------------------------------------------------------------- # request dispatcher # some magic to bind an B-RPC method to an RPC server. # supports "nested" methods (e.g. examples.getStateName) # ARG! prevent repr(_Method()) from submiting an RP... | 2.520271 | 3 |
database_files/views.py | den-gts/django-database-files-3000 | 8 | 4630 | import base64
import mimetypes
import os
from django.conf import settings
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_control
from django.views.static import serve as django_serve
from database_files.models import File
... | import base64
import mimetypes
import os
from django.conf import settings
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_control
from django.views.static import serve as django_serve
from database_files.models import File
... | en | 0.907878 | Retrieves the file from the database. First attempts to serve the file from the filesystem, then tries the database. # First attempt to serve from filesystem. # Then try serving from database. | 2.056912 | 2 |
NoiseFiltersPy/Injector.py | TVect/NoiseFiltersPy | 6 | 4631 | <reponame>TVect/NoiseFiltersPy<gh_stars>1-10
import numpy as np
import pandas as pd
from abc import ABC
class Injector(ABC):
"""Base class for the injectors of artificial noise.
Attributes
----------
rem_indx : :obj:`List`
Removed indexes (rows) from the dataset after the filtering.
para... | import numpy as np
import pandas as pd
from abc import ABC
class Injector(ABC):
"""Base class for the injectors of artificial noise.
Attributes
----------
rem_indx : :obj:`List`
Removed indexes (rows) from the dataset after the filtering.
parameters : :obj:`Dict`
Parameters used ... | en | 0.448989 | Base class for the injectors of artificial noise. Attributes ---------- rem_indx : :obj:`List` Removed indexes (rows) from the dataset after the filtering. parameters : :obj:`Dict` Parameters used to define the behaviour of the filter. clean_data : :obj:`Sequence` Filtered ... | 3.318407 | 3 |
application/mod_user/forms.py | hackBCA/hackbcafour | 2 | 4632 | <filename>application/mod_user/forms.py
from wtforms import Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField
import re
phone_regex = "(\+\d+-?)?((\(?\d{3}\)?)|(\d{3}))-?\d{3}-?\d{4}$"
gender_choices = [
("", "Gender"),
("male", "Male"),
("f... | <filename>application/mod_user/forms.py
from wtforms import Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField
import re
phone_regex = "(\+\d+-?)?((\(?\d{3}\)?)|(\d{3}))-?\d{3}-?\d{4}$"
gender_choices = [
("", "Gender"),
("male", "Male"),
("f... | en | 0.684903 | #1", [ #1 (Optional)") #2", [ #2 (Optional)") #3", [ #3 (Optional)") #Man I love validators.URL #Temporarily prefix all links with http:// if they are missing it #Revert link values back to actual values #Temporarily prefix all links with http:// if they are missing it #Revert link values back to actual values # attend... | 2.663293 | 3 |
src/app.py | gh640/coding-challenge | 0 | 4633 | # coding: utf-8
'''フロントコントローラを提供する
'''
from math import ceil
import os
from flask import json
from flask import Flask
from flask import request
from flask import send_from_directory
from flask import render_template
# from json_loader import load_locations
# from json_loader import prepare_locations
from models imp... | # coding: utf-8
'''フロントコントローラを提供する
'''
from math import ceil
import os
from flask import json
from flask import Flask
from flask import request
from flask import send_from_directory
from flask import render_template
# from json_loader import load_locations
# from json_loader import prepare_locations
from models imp... | ja | 0.903162 | # coding: utf-8 フロントコントローラを提供する # from json_loader import load_locations # from json_loader import prepare_locations # ページ毎のロケ地表示する | 2.512798 | 3 |
corkus/objects/dungeon.py | MrBartusek/corkus.py | 5 | 4634 | <filename>corkus/objects/dungeon.py
from __future__ import annotations
from .base import CorkusBase
from enum import Enum
class DungeonType(Enum):
REMOVED = "REMOVED"
"""Dungeons that were removed from the game in version ``1.14.1`` like ``Skeleton`` or ``Spider``"""
REMOVED_MINI = "REMOVED_MINI"
"""M... | <filename>corkus/objects/dungeon.py
from __future__ import annotations
from .base import CorkusBase
from enum import Enum
class DungeonType(Enum):
REMOVED = "REMOVED"
"""Dungeons that were removed from the game in version ``1.14.1`` like ``Skeleton`` or ``Spider``"""
REMOVED_MINI = "REMOVED_MINI"
"""M... | en | 0.891263 | Dungeons that were removed from the game in version ``1.14.1`` like ``Skeleton`` or ``Spider`` Minidungeons that were reworked in version ``1.17`` like ``Ice`` or ``Ocean`` Generic dungeons like ``Galleon's Graveyard`` or ``Fallen Factory`` Harder variant of standard dungeons like ``Corrupted Decrepit Sewers`` or ``Cor... | 2.940114 | 3 |
src/brisk.py | chaoer/brisk-descriptor | 18 | 4635 | <filename>src/brisk.py
import pybrisk
class Brisk:
def __init__(self, thresh=60, octaves=4):
self.thresh = thresh
self.octaves = octaves
self.descriptor_extractor = pybrisk.create()
def __del__(self):
pybrisk.destroy(self.descriptor_extractor)
def detect(self, img):
... | <filename>src/brisk.py
import pybrisk
class Brisk:
def __init__(self, thresh=60, octaves=4):
self.thresh = thresh
self.octaves = octaves
self.descriptor_extractor = pybrisk.create()
def __del__(self):
pybrisk.destroy(self.descriptor_extractor)
def detect(self, img):
... | none | 1 | 2.683673 | 3 | |
hale_hub/outlet_interface.py | tantinlala/hale-hub | 0 | 4636 | import serial
import serial.tools.list_ports
from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT
from hale_hub.ifttt_logger import send_ifttt_log
class _Outlet:
def __init__(self, name):
self.state = 0
self.name = name
class _OutletInterface:
def __init__... | import serial
import serial.tools.list_ports
from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT
from hale_hub.ifttt_logger import send_ifttt_log
class _Outlet:
def __init__(self, name):
self.state = 0
self.name = name
class _OutletInterface:
def __init__... | none | 1 | 2.409714 | 2 | |
helix/core.py | carbonscott/helix | 0 | 4637 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)]
def measure_twocores(core_xyz_ref, core_xyz_tar):
''' Measure the following aspects of two helical cores.
- Interhelical distance vector between the centers.
- Inte... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)]
def measure_twocores(core_xyz_ref, core_xyz_tar):
''' Measure the following aspects of two helical cores.
- Interhelical distance vector between the centers.
- Inte... | en | 0.715185 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Measure the following aspects of two helical cores. - Interhelical distance vector between the centers. - Interhelical angle (0-90 degree) # Obtain the centers... # Construct the interhelical distance vector... # Calculate the length of interhelical distanc... | 2.672398 | 3 |
matury/2011/6.py | bartekpacia/informatyka-frycz | 2 | 4638 | <reponame>bartekpacia/informatyka-frycz<gh_stars>1-10
from typing import List
with open("dane/liczby.txt") as f:
nums: List[int] = []
nums_9_chars: List[int] = []
for line in f:
sline = line.strip()
num = int(sline, 2)
if len(sline) == 9:
nums_9_chars.append(num)
... | from typing import List
with open("dane/liczby.txt") as f:
nums: List[int] = []
nums_9_chars: List[int] = []
for line in f:
sline = line.strip()
num = int(sline, 2)
if len(sline) == 9:
nums_9_chars.append(num)
nums.append(num)
count_even = 0
max_num = 0
for n... | none | 1 | 3.405133 | 3 | |
Python/fibs.py | familug/FAMILUG | 5 | 4639 | def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
def fib_fast(n):
from math import sqrt
s5 = sqrt(5)
x = (1 + s5) ** n
y = (1 - s5) ** n
return int((x - y)/(s5 * 2**n))
def print_fib(n):
for i in range(n):
print fib(i),
print
for i i... | def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
def fib_fast(n):
from math import sqrt
s5 = sqrt(5)
x = (1 + s5) ** n
y = (1 - s5) ** n
return int((x - y)/(s5 * 2**n))
def print_fib(n):
for i in range(n):
print fib(i),
print
for i i... | none | 1 | 3.744817 | 4 | |
src/model/ParseInput.py | slavi010/polyhash-2020 | 0 | 4640 | <filename>src/model/ParseInput.py
import os
from typing import List
from src.model.Etape import Etape
from src.model.Grille import Grille
from src.model.ItemCase import ItemCase
from src.model.PointMontage import PointMontage
from src.model.Robot import Robot
from src.model.Tache import Tache
class ParseInput:
"... | <filename>src/model/ParseInput.py
import os
from typing import List
from src.model.Etape import Etape
from src.model.Grille import Grille
from src.model.ItemCase import ItemCase
from src.model.PointMontage import PointMontage
from src.model.Robot import Robot
from src.model.Tache import Tache
class ParseInput:
"... | fr | 0.986608 | Parser qui permet de lire le fichier texte d'input fourni par Google. Va transformer ce fichier en données et classes exploitables pour nous parse le fichier google et retourne la Grille correspondante :rtype: Grille # tests si file_path est un fichier # récupère toutes les lignes du fichiers # Transformat... | 3.001724 | 3 |
test.py | UnKafkaesque/Sentiment-Analysis | 0 | 4641 | <filename>test.py<gh_stars>0
import os
import sys
import time
import traceback
import project1_Copy as p1
import numpy as np
verbose = False
def green(s):
return '\033[1;32m%s\033[m' % s
def yellow(s):
return '\033[1;33m%s\033[m' % s
def red(s):
return '\033[1;31m%s\033[m' % s
def log(*m):
print(" ... | <filename>test.py<gh_stars>0
import os
import sys
import time
import traceback
import project1_Copy as p1
import numpy as np
verbose = False
def green(s):
return '\033[1;32m%s\033[m' % s
def yellow(s):
return '\033[1;33m%s\033[m' % s
def red(s):
return '\033[1;31m%s\033[m' % s
def log(*m):
print(" ... | none | 1 | 2.435914 | 2 | |
homework_1/tests/test_3.py | mag-id/epam_python_autumn_2020 | 0 | 4642 | """
Unit tests for module `homework_1.tasks.task_3`.
"""
from tempfile import NamedTemporaryFile
from typing import Tuple
import pytest
from homework_1.tasks.task_3 import find_maximum_and_minimum
@pytest.mark.parametrize(
["file_content", "expected_result"],
[
pytest.param(
"0\n",
... | """
Unit tests for module `homework_1.tasks.task_3`.
"""
from tempfile import NamedTemporaryFile
from typing import Tuple
import pytest
from homework_1.tasks.task_3 import find_maximum_and_minimum
@pytest.mark.parametrize(
["file_content", "expected_result"],
[
pytest.param(
"0\n",
... | en | 0.533017 | Unit tests for module `homework_1.tasks.task_3`. Mocks file using `NamedTemporaryFile` instance with writed `file_content` inside, where `file_name` == `file.name`. Passes test if `find_maximum_and_minimum`(`file.name`) is equal to `expected_result`. | 2.685598 | 3 |
app/admin/views/__init__.py | CAUCHY2932/Northern_Hemisphere | 0 | 4643 | # coding:utf-8
import app.admin.views.start
import app.admin.views.book
import app.admin.views.user
import app.admin.views.site
| # coding:utf-8
import app.admin.views.start
import app.admin.views.book
import app.admin.views.user
import app.admin.views.site
| en | 0.786515 | # coding:utf-8 | 1.020359 | 1 |
test_mnist.py | aidiary/chainer-siamese | 0 | 4644 | <reponame>aidiary/chainer-siamese
import os
import chainer
import chainer.links as L
from net import SiameseNetwork
import numpy as np
import matplotlib.pyplot as plt
# 訓練済みモデルをロード
model = SiameseNetwork()
chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model)
# テストデータをロード
_, test = chainer.datase... | import os
import chainer
import chainer.links as L
from net import SiameseNetwork
import numpy as np
import matplotlib.pyplot as plt
# 訓練済みモデルをロード
model = SiameseNetwork()
chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model)
# テストデータをロード
_, test = chainer.datasets.get_mnist(ndim=3)
test_data, te... | ja | 1.000021 | # 訓練済みモデルをロード # テストデータをロード # テストデータを学習した低次元空間(2次元)に写像 # ラベルごとに描画 # 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 | 2.245289 | 2 |
TwoFeetTempoMove.py | b0nz0/TwisterTempo | 0 | 4645 | <reponame>b0nz0/TwisterTempo<gh_stars>0
from random import randrange, random
from time import time
import logging
from TwisterTempoGUI import TwisterTempoGUI
class TwoFeetTempoMove(object):
COLORS_ALPHA = {0: 'RED', 1: 'BLUE', 2: 'YELLOW', 3: 'GREEN'}
COLORS_RGB = {0: (255, 0, 0), 1: (0, 0, 255), 2: (255, 25... | from random import randrange, random
from time import time
import logging
from TwisterTempoGUI import TwisterTempoGUI
class TwoFeetTempoMove(object):
COLORS_ALPHA = {0: 'RED', 1: 'BLUE', 2: 'YELLOW', 3: 'GREEN'}
COLORS_RGB = {0: (255, 0, 0), 1: (0, 0, 255), 2: (255, 255, 0), 3: (0, 255, 0)}
FOOT_CHANGE_... | en | 0.743078 | # special moves # randomized next foot on air move # randomized both feet on same circle # end special moves # randomize at 30% the switch on foot | 2.789369 | 3 |
plugins/panorama/panorama/__init__.py | mohnjahoney/website_source | 13 | 4646 | <filename>plugins/panorama/panorama/__init__.py
# -*- coding: utf-8 -*-
"""
Panorama is a Pelican plugin to generate statistics from blog posts
(number of posts per month, categories and so on) display them as beautiful charts.
Project location: https://github.com/romainx/panorama
"""
__version__ = "0.2.0"
__author_... | <filename>plugins/panorama/panorama/__init__.py
# -*- coding: utf-8 -*-
"""
Panorama is a Pelican plugin to generate statistics from blog posts
(number of posts per month, categories and so on) display them as beautiful charts.
Project location: https://github.com/romainx/panorama
"""
__version__ = "0.2.0"
__author_... | en | 0.856642 | # -*- coding: utf-8 -*- Panorama is a Pelican plugin to generate statistics from blog posts (number of posts per month, categories and so on) display them as beautiful charts. Project location: https://github.com/romainx/panorama | 1.445328 | 1 |
transitfeed/transfer.py | cclauss/transitfeed | 9 | 4647 | #!/usr/bin/python2.5
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | #!/usr/bin/python2.5
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | en | 0.898783 | #!/usr/bin/python2.5 # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law... | 2.255219 | 2 |
social/urls.py | Kizito-Alberrt/insta-social | 0 | 4648 | from django.urls import path
from . import views
from . views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update
urlpatterns = [
path('',views.base, name='base'),
path('login',views.login, name='login'),
path('register',v... | from django.urls import path
from . import views
from . views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update
urlpatterns = [
path('',views.base, name='base'),
path('login',views.login, name='login'),
path('register',v... | en | 0.217888 | # path('<str:username>',views.userprofile, name='userprofile'), | 1.863658 | 2 |
vtkplotter_examples/other/dolfin/collisions.py | ismarou/vtkplotter-examples | 4 | 4649 | <reponame>ismarou/vtkplotter-examples<filename>vtkplotter_examples/other/dolfin/collisions.py<gh_stars>1-10
'''
compute_collision() will compute the collision of all the entities with
a Point while compute_first_collision() will always return its first entry.
Especially if a point is on an element edge this can be tric... | '''
compute_collision() will compute the collision of all the entities with
a Point while compute_first_collision() will always return its first entry.
Especially if a point is on an element edge this can be tricky.
You may also want to compare with the Cell.contains(Point) tool.
'''
# Script by Rudy at https://fenicsp... | en | 0.748193 | compute_collision() will compute the collision of all the entities with a Point while compute_first_collision() will always return its first entry. Especially if a point is on an element edge this can be tricky. You may also want to compare with the Cell.contains(Point) tool. # Script by Rudy at https://fenicsproject.d... | 2.743601 | 3 |
alice_check_train/__main__.py | AsciiShell/Alice-Check-Train | 0 | 4650 | <reponame>AsciiShell/Alice-Check-Train
import datetime
import os
from alice_check_train.main import rasp_to_text
from alice_check_train.rasp_api import get_rasp, filter_rasp
def main():
key = os.getenv('RASP_KEY')
station_from = os.getenv('STATION_FROM')
station_to = os.getenv('STATION_TO')
date = da... | import datetime
import os
from alice_check_train.main import rasp_to_text
from alice_check_train.rasp_api import get_rasp, filter_rasp
def main():
key = os.getenv('RASP_KEY')
station_from = os.getenv('STATION_FROM')
station_to = os.getenv('STATION_TO')
date = datetime.date.today().strftime('%Y-%m-%d'... | none | 1 | 2.57637 | 3 | |
aws-KNN-RESTful.py | cakebytheoceanLuo/k-NN | 1 | 4651 | # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb
# https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html
import sys
import requests
import h5py
import numpy as np
import json
import aiohttp
import asyncio
import time
import httpx
from requests.auth imp... | # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb
# https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html
import sys
import requests
import h5py
import numpy as np
import json
import aiohttp
import asyncio
import time
import httpx
from requests.auth imp... | en | 0.467997 | # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb # https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html # if len(sys.argv) != 2: # print("Type in the efSearch!") # sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path = ... | 2.320606 | 2 |
test/test_docker_images.py | bauerj/cibuildwheel | 0 | 4652 | <reponame>bauerj/cibuildwheel
import platform
import textwrap
import pytest
from . import test_projects, utils
dockcross_only_project = test_projects.new_c_project(
setup_py_add=textwrap.dedent(r'''
import os, sys
# check that we're running in the correct docker image as specified in the
... | import platform
import textwrap
import pytest
from . import test_projects, utils
dockcross_only_project = test_projects.new_c_project(
setup_py_add=textwrap.dedent(r'''
import os, sys
# check that we're running in the correct docker image as specified in the
# environment options CIBW_MA... | en | 0.726846 | import os, sys # check that we're running in the correct docker image as specified in the # environment options CIBW_MANYLINUX1_*_IMAGE if "linux" in sys.platform and not os.path.exists("/dockcross"): raise Exception( "/dockcross directory not found. Is this test run... | 2.243068 | 2 |
real_trade/MoveAverageTradePosition.py | taka-mochi/cryptocurrency-autotrading | 3 | 4653 | # coding: utf-8
import math
import dateutil
import dateutil.parser
import json
from ChartBars import Chart
from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS
from Util import BitcoinUtil
def adjust_price_to_tick(price, tick):
return price - math.fmod(price, tick)
def adjust_amount_to_tick(amount, t... | # coding: utf-8
import math
import dateutil
import dateutil.parser
import json
from ChartBars import Chart
from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS
from Util import BitcoinUtil
def adjust_price_to_tick(price, tick):
return price - math.fmod(price, tick)
def adjust_amount_to_tick(amount, t... | en | 0.425424 | # coding: utf-8 # a class for one position # total maximum position size in base currency # total position price in base currency (actually paired currency) # used only for genbutsu # max free margin. we cannot use orders that exceed this margin # api: e.g. instance of CoinCheck # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage ... | 2.647525 | 3 |
test.py | sbcshop/PiRelay-8 | 2 | 4654 | <reponame>sbcshop/PiRelay-8<filename>test.py<gh_stars>1-10
from PiRelay8 import Relay
import time
r1 = Relay("RELAY1")
r2 = Relay("RELAY2")
r3 = Relay("RELAY3")
r4 = Relay("RELAY4")
r5 = Relay("RELAY5")
r6 = Relay("RELAY6")
r7 = Relay("RELAY7")
r8 = Relay("RELAY8")
r1.off()
r2.off()
r3.off()
r4.off()... | from PiRelay8 import Relay
import time
r1 = Relay("RELAY1")
r2 = Relay("RELAY2")
r3 = Relay("RELAY3")
r4 = Relay("RELAY4")
r5 = Relay("RELAY5")
r6 = Relay("RELAY6")
r7 = Relay("RELAY7")
r8 = Relay("RELAY8")
r1.off()
r2.off()
r3.off()
r4.off()
r5.off()
r6.off()
r7.off()
r8.off()
r1.on()
time.s... | none | 1 | 1.951582 | 2 | |
bot/cogs/clan.py | johnvictorfs/atlantisbot-rewrite | 0 | 4655 | <gh_stars>0
import rs3clans
import discord
from discord.ext import commands
from bot.bot_client import Bot
from bot.utils.tools import separator
from bot.utils.context import Context
class Clan(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
@commands.cooldown(1, 5, comman... | import rs3clans
import discord
from discord.ext import commands
from bot.bot_client import Bot
from bot.utils.tools import separator
from bot.utils.context import Context
class Clan(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
@commands.cooldown(1, 5, commands.BucketTyp... | none | 1 | 2.24668 | 2 | |
otcextensions/tests/functional/osclient/vpc/v2/common.py | zsoltn/python-otcextensions | 10 | 4656 | <filename>otcextensions/tests/functional/osclient/vpc/v2/common.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | <filename>otcextensions/tests/functional/osclient/vpc/v2/common.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | en | 0.859348 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distrib... | 1.922516 | 2 |
tests/test_nested_structures_inside_structure_values.py | Robinson04/StructNoSQL | 3 | 4657 | <reponame>Robinson04/StructNoSQL
import unittest
from typing import Set, Optional, Dict, List
from uuid import uuid4
from StructNoSQL import BaseField, MapModel, TableDataModel
from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID
class TableModel(TableDataModel):
ac... | import unittest
from typing import Set, Optional, Dict, List
from uuid import uuid4
from StructNoSQL import BaseField, MapModel, TableDataModel
from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID
class TableModel(TableDataModel):
accountId = BaseField(field_type=st... | en | 0.083629 | # nestedDictListStructure = BaseField(field_type=Dict[str, List[str]], required=False) # nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]], required=False) # todo: implement # todo: implement | 2.576702 | 3 |
test/cpython/test_base64.py | aisk/pyston | 1 | 4658 | import unittest
from test import test_support
import base64
class LegacyBase64TestCase(unittest.TestCase):
def test_encodestring(self):
eq = self.assertEqual
eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n")
eq(base64.encodestring("a"), "YQ==\n")
eq(base64.encod... | import unittest
from test import test_support
import base64
class LegacyBase64TestCase(unittest.TestCase):
def test_encodestring(self):
eq = self.assertEqual
eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n")
eq(base64.encodestring("a"), "YQ==\n")
eq(base64.encod... | en | 0.667702 | #0^&*();:<>,. []{}"), # Non-bytes #0^&*();:<>,. []{}") # Non-bytes #0^&*();:<>,. []{}') # Test default alphabet #0^&*();:<>,. []{}"), # Test with arbitrary alternative characters # Non-bytes # Test standard alphabet #0^&*();:<>,. []{}"), # Non-bytes # Test with 'URL safe' alternative characters # Non-bytes #0^&*();:<>,... | 3.076712 | 3 |
src/Path.py | gabbonj/Workbench | 2 | 4659 | import numpy as np
from ctypes import c_void_p
from .Shader import Shader
from .transforms import *
from OpenGL.GL import *
class Path:
# position=[x1, y1, z1, ..., xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]]
def __init__(self, position, rotation=None):
self.loadPath(position)
... | import numpy as np
from ctypes import c_void_p
from .Shader import Shader
from .transforms import *
from OpenGL.GL import *
class Path:
# position=[x1, y1, z1, ..., xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]]
def __init__(self, position, rotation=None):
self.loadPath(position)
... | en | 0.503176 | # position=[x1, y1, z1, ..., xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] # compiling shader # setting path buffer # compiling shader # setting versors #setting xline bufer # setting yline buffer #setting xline bufer # rendering the path # rendering the xlines # rendering the ylines # rendering the ... | 2.388441 | 2 |
icfree/echo_instructor/args.py | brsynth/icfree-ml | 1 | 4660 | from argparse import (
ArgumentParser
)
from os import getcwd as os_getcwd
DEFAULT_OUTPUT_FOLDER = os_getcwd()
DEFAULT_SAMPLE_VOLUME = 10000
def build_args_parser(
program,
description):
parser = ArgumentParser(
program,
description,
)
parser = add_arguments(pars... | from argparse import (
ArgumentParser
)
from os import getcwd as os_getcwd
DEFAULT_OUTPUT_FOLDER = os_getcwd()
DEFAULT_SAMPLE_VOLUME = 10000
def build_args_parser(
program,
description):
parser = ArgumentParser(
program,
description,
)
parser = add_arguments(pars... | none | 1 | 2.872285 | 3 | |
ex1_01.py | sitdh/59.com-prog | 1 | 4661 | import math
x = float(input())
prop_2 = -(x**2) / math.factorial(2)
prop_3 = (x**4) / math.factorial(4)
prop_4 = -(x**6) / math.factorial(6)
cos_x = float(1 + prop_2 + prop_3 + prop_4)
print(prop_2)
print(prop_3)
print(prop_4)
print(cos_x)
| import math
x = float(input())
prop_2 = -(x**2) / math.factorial(2)
prop_3 = (x**4) / math.factorial(4)
prop_4 = -(x**6) / math.factorial(6)
cos_x = float(1 + prop_2 + prop_3 + prop_4)
print(prop_2)
print(prop_3)
print(prop_4)
print(cos_x)
| none | 1 | 3.595176 | 4 | |
test/datagateway_api/icat/filters/test_where_filter.py | MRichards99/datagateway-api | 2 | 4662 | <filename>test/datagateway_api/icat/filters/test_where_filter.py
import pytest
from datagateway_api.src.common.exceptions import BadRequestError, FilterError
from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler
from datagateway_api.src.datagateway_api.icat.filters import PythonICATWh... | <filename>test/datagateway_api/icat/filters/test_where_filter.py
import pytest
from datagateway_api.src.common.exceptions import BadRequestError, FilterError
from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler
from datagateway_api.src.datagateway_api.icat.filters import PythonICATWh... | en | 0.770221 | Check that values that point to other values in the schema are applied | 2.264467 | 2 |
scrapy/spider/spider/items.py | huobingli/splider | 0 | 4663 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst
# class SpiderItem(scrapy.Item):
# # define the fields for your... | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst
# class SpiderItem(scrapy.Item):
# # define the fields for your... | en | 0.420625 | # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html # class SpiderItem(scrapy.Item): # # define the fields for your item here like: # # name = scrapy.Field() # pass # # # # class TorrentItem(scrapy.Item): # ... | 2.811994 | 3 |
codetools/contexts/multi_context.py | enthought/codetools | 29 | 4664 | #
# (C) Copyright 2013 Enthought, Inc., Austin, TX
# All right reserved.
#
# This file is open source software distributed according to the terms in
# LICENSE.txt
#
""" Context holding multiple subcontexts.
"""
from __future__ import absolute_import
from itertools import chain
from collections import MutableMapping ... | #
# (C) Copyright 2013 Enthought, Inc., Austin, TX
# All right reserved.
#
# This file is open source software distributed according to the terms in
# LICENSE.txt
#
""" Context holding multiple subcontexts.
"""
from __future__ import absolute_import
from itertools import chain
from collections import MutableMapping ... | en | 0.705778 | # # (C) Copyright 2013 Enthought, Inc., Austin, TX # All right reserved. # # This file is open source software distributed according to the terms in # LICENSE.txt # Context holding multiple subcontexts. Wrap several subcontexts. #: The name of the context. #: The underlying dictionary. #: Suppress subcontext modified e... | 2.109503 | 2 |
line_counter/TestCodes/python_test.py | FMoller/coding-auxiliary-tools | 0 | 4665 | """A simple file to test the line_counter performance in python
This is a multiline doctest
"""
__author__ = "<NAME>"
__copyright__ = ""
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = ""
__status__ = ""
#import things
import math
#define things
def some_fun... | """A simple file to test the line_counter performance in python
This is a multiline doctest
"""
__author__ = "<NAME>"
__copyright__ = ""
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = ""
__status__ = ""
#import things
import math
#define things
def some_fun... | en | 0.827695 | A simple file to test the line_counter performance in python This is a multiline doctest #import things #define things This is a function that do things #this happens | 2.969417 | 3 |
causal_attribution/data.py | VaniW/deconfounded-lexicon-induction | 25 | 4666 | """Data pipelines."""
from collections import defaultdict, OrderedDict
from tqdm import tqdm
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
import torch
def get_info(examples, vocab=None, max_seq_len=256):
"""Gathers info on and creats a featurized example generator for... | """Data pipelines."""
from collections import defaultdict, OrderedDict
from tqdm import tqdm
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
import torch
def get_info(examples, vocab=None, max_seq_len=256):
"""Gathers info on and creats a featurized example generator for... | en | 0.674308 | Data pipelines. Gathers info on and creats a featurized example generator for a list of raw examples. Args: examples: list(list, float, or string). Examples to create generator for. vocab: list(str). A vocabulary for discrete datatypes (e.g. text or categorical). max_seq_len: int. maximum s... | 2.778525 | 3 |
fopp/Chapter 12. Functions/get_num_digits.py | H2u-Hwng/EVC | 0 | 4667 | <reponame>H2u-Hwng/EVC
# Take number, and convert integer to string
# Calculate and return number of digits
def get_num_digits(num):
# Convert int to str
num_str = str(num)
# Calculate number of digits
digits = len(num_str)
return digits
# Define main function
def main():
#... | # Take number, and convert integer to string
# Calculate and return number of digits
def get_num_digits(num):
# Convert int to str
num_str = str(num)
# Calculate number of digits
digits = len(num_str)
return digits
# Define main function
def main():
# Prompt user for an int... | en | 0.405366 | # Take number, and convert integer to string # Calculate and return number of digits # Convert int to str # Calculate number of digits # Define main function # Prompt user for an integer # Obtain number of digits # Display result # Call main function | 4.11185 | 4 |
app/dialog/avatar_picture_dialog.py | tirinox/alphavatarbot | 1 | 4668 | <filename>app/dialog/avatar_picture_dialog.py<gh_stars>1-10
import asyncio
from contextlib import AsyncExitStack
from aiogram.dispatcher.filters.state import StatesGroup, State
from aiogram.dispatcher.storage import FSMContextProxy
from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes
from ai... | <filename>app/dialog/avatar_picture_dialog.py<gh_stars>1-10
import asyncio
from contextlib import AsyncExitStack
from aiogram.dispatcher.filters.state import StatesGroup, State
from aiogram.dispatcher.storage import FSMContextProxy
from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes
from ai... | en | 0.489416 | # todo: accept documents! # fixme: no state handle # POST A LOADING STICKER # CLEAN UP IN THE END # pic = await combine_frame_and_photo(self.deps.cfg, user_pic) | 2.144272 | 2 |
image_store_processing.py | olubiyiontheweb/digid_websearch_flask | 1 | 4669 | <reponame>olubiyiontheweb/digid_websearch_flask
from skimage.metrics import structural_similarity as ssim
from glob import glob
from PIL import Image
import numpy as np
import ntpath
import dhash
import cv2
from database_structure import database_migrations
IMAGE_FOLDER = "./image_store"
ALLOWED_EXTENSIONS = ['png', ... | from skimage.metrics import structural_similarity as ssim
from glob import glob
from PIL import Image
import numpy as np
import ntpath
import dhash
import cv2
from database_structure import database_migrations
IMAGE_FOLDER = "./image_store"
ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg']
image_store_hash = dict()
db_ops ... | en | 0.784812 | # image table values to insert in database # TODO Abstract requests and insert from database # images = glob(IMAGE_FOLDER + "/*" + img_type) # get image name # image table values to insert in database # get image name # request image name from image store database # the 'Mean Squared Error' between the two images is th... | 2.476902 | 2 |
cogs/jpserv.py | elthorito/Rai | 0 | 4670 | import discord
from discord.ext import commands
import os
import json
from datetime import date, datetime, timedelta
from .utils import helper_functions as hf
from copy import deepcopy
dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\', '/')
class Jpserv(commands.Cog):
"""Module... | import discord
from discord.ext import commands
import os
import json
from datetime import date, datetime, timedelta
from .utils import helper_functions as hf
from copy import deepcopy
dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\', '/')
class Jpserv(commands.Cog):
"""Module... | en | 0.831845 | Modules unique for the Japanese server # these commands are only useable on Japanese server or my testing server Swaps JHO/JHO2's names and positions in the lists, for if we temporarily want welcome messages to go to JHO2 Irreversible hardcore mode. Must talk to an admin to have this undone. # if ctx.guild.id ... | 2.37962 | 2 |
nehebn2.py | psifertex/nehebn2 | 0 | 4671 | <gh_stars>0
#!/usr/bin/env python3
from components import ProgramState
import binaryninja as binja
import argparse
import os.path
import curses
# TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop)
# TODO...support multi-key presses? Not s... | #!/usr/bin/env python3
from components import ProgramState
import binaryninja as binja
import argparse
import os.path
import curses
# TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop)
# TODO...support multi-key presses? Not sure if this ... | en | 0.843973 | #!/usr/bin/env python3 # TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop) # TODO...support multi-key presses? Not sure if this already works or not # TODO...make sure to support small terminals (I think it does right now, but I should add... | 2.658285 | 3 |
keras/layers/pooling/base_pooling3d.py | itsraina/keras | 0 | 4672 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | en | 0.719389 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica... | 2.464339 | 2 |
main.py | lucastan96/video2bitmap | 1 | 4673 | <reponame>lucastan96/video2bitmap<gh_stars>1-10
import moviepy.editor as mpy
import moviepy.video.fx.all as vfx
import subprocess as sp
# Crop and resize video
clip = mpy.VideoFileClip("smoke.mp4")
(w, h) = clip.size
cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128))
croppe... | import moviepy.editor as mpy
import moviepy.video.fx.all as vfx
import subprocess as sp
# Crop and resize video
clip = mpy.VideoFileClip("smoke.mp4")
(w, h) = clip.size
cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128))
cropped_clip.write_videofile('smoke-cropped.mp4')
# C... | en | 0.764545 | # Crop and resize video # Convert video to frames # Make sure to install ffmpeg on machine # Convert image to black and white bitmap | 2.859926 | 3 |
ghostwriter/rolodex/apps.py | bbhunter/Ghostwriter | 601 | 4674 | """This contains the configuration of the Rolodex application."""
# Django Imports
from django.apps import AppConfig
class RolodexConfig(AppConfig):
name = "ghostwriter.rolodex"
def ready(self):
try:
import ghostwriter.rolodex.signals # noqa F401 isort:skip
except ImportError:
... | """This contains the configuration of the Rolodex application."""
# Django Imports
from django.apps import AppConfig
class RolodexConfig(AppConfig):
name = "ghostwriter.rolodex"
def ready(self):
try:
import ghostwriter.rolodex.signals # noqa F401 isort:skip
except ImportError:
... | en | 0.609917 | This contains the configuration of the Rolodex application. # Django Imports # noqa F401 isort:skip | 1.592843 | 2 |
boards/migrations/0024_boardpreferences_moderators.py | oscarsiles/jotlet | 0 | 4675 | <filename>boards/migrations/0024_boardpreferences_moderators.py
# Generated by Django 4.0.3 on 2022-03-01 14:42
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | <filename>boards/migrations/0024_boardpreferences_moderators.py
# Generated by Django 4.0.3 on 2022-03-01 14:42
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | en | 0.827171 | # Generated by Django 4.0.3 on 2022-03-01 14:42 | 1.53845 | 2 |
models/minimize_model.py | MichalBusta/OpenCitiesAIC | 7 | 4676 | <filename>models/minimize_model.py
'''
Created on Mar 22, 2020
@author: Michal.Busta at gmail.com
'''
#get rid of the optimizer state ...
import torch
MODEL_PATH = '/models/model-b2-2.pth'
state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage)
state_out = {
"state_dict": state["state_dict"],
}
... | <filename>models/minimize_model.py
'''
Created on Mar 22, 2020
@author: Michal.Busta at gmail.com
'''
#get rid of the optimizer state ...
import torch
MODEL_PATH = '/models/model-b2-2.pth'
state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage)
state_out = {
"state_dict": state["state_dict"],
}
... | en | 0.742575 | Created on Mar 22, 2020 @author: Michal.Busta at gmail.com #get rid of the optimizer state ... | 2.339089 | 2 |
setup.py | thomas-kloeber/braumeister | 6 | 4677 | import os
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"(.*)"',
open('braumeister/braumeister.py').read(),
re.M
).group(1)
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="braumeister",
packages=["braumeiste... | import os
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"(.*)"',
open('braumeister/braumeister.py').read(),
re.M
).group(1)
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="braumeister",
packages=["braumeiste... | none | 1 | 1.717636 | 2 | |
modules/inference.py | rubelchowdhury20/wuton-with-densepose | 12 | 4678 | # standard library imports
import os
# third party imports
import numpy as np
from PIL import Image
import torch.nn as nn
from torchvision import transforms
# local imports
import config
from . import utils
from . import geometric_transformer
class GeoTransformationInfer(nn.Module):
def __init__(self, output_di... | # standard library imports
import os
# third party imports
import numpy as np
from PIL import Image
import torch.nn as nn
from torchvision import transforms
# local imports
import config
from . import utils
from . import geometric_transformer
class GeoTransformationInfer(nn.Module):
def __init__(self, output_di... | en | 0.830274 | # standard library imports # third party imports # local imports # inverse normalization of the images along with channel first to channel last steps and finally converting np array to pillow format for saving | 2.306445 | 2 |
imggen/fonts.py | p-lambda/unlabeled_outputs | 4 | 4679 | from pathlib import Path
import h5py
import numpy as np
from torchvision.datasets.vision import VisionDataset
from PIL import Image
import requests
import zipfile
from tqdm import tqdm
def download_file_from_google_drive(id, destination):
URL = "https://docs.google.com/uc?export=download"
session = requests... | from pathlib import Path
import h5py
import numpy as np
from torchvision.datasets.vision import VisionDataset
from PIL import Image
import requests
import zipfile
from tqdm import tqdm
def download_file_from_google_drive(id, destination):
URL = "https://docs.google.com/uc?export=download"
session = requests... | en | 0.769563 | # filter out keep-alive new chunks Args: root (str): path num_train_domains (int): number of train domains up to 41443 test_mean_chars (bool): Use the mean characters as test set split (str): 'train', 'val', 'test' transform: input transformation t... | 2.464536 | 2 |
leetcode/47.py | windniw/just-for-fun | 1 | 4680 | """
link: https://leetcode.com/problems/permutations-ii
problem: 求全排列,nums中存在重复数
solution: 同46,加上排序即可
"""
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1:
return [nums]
new_nums = nums.copy()
new_nums.sort()
... | """
link: https://leetcode.com/problems/permutations-ii
problem: 求全排列,nums中存在重复数
solution: 同46,加上排序即可
"""
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1:
return [nums]
new_nums = nums.copy()
new_nums.sort()
... | en | 0.355969 | link: https://leetcode.com/problems/permutations-ii
problem: 求全排列,nums中存在重复数
solution: 同46,加上排序即可 | 3.177438 | 3 |
adminmgr/media/code/A3/task3/T1_ocefXVJ.py | IamMayankThakur/test-bigdata | 9 | 4681 | import findspark
findspark.init()
from pyspark import SparkConf,SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import Row,SQLContext
import sys
import requests
def tmp(x):
y = (x.split(';')[7]).split(',')
return (y)
def forf(x):
for i in x:
yield (i,1)
def topprint(time,rdd):
re... | import findspark
findspark.init()
from pyspark import SparkConf,SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import Row,SQLContext
import sys
import requests
def tmp(x):
y = (x.split(';')[7]).split(',')
return (y)
def forf(x):
for i in x:
yield (i,1)
def topprint(time,rdd):
re... | en | 0.247817 | #Selecting a window : #outpu3: inputStream=ssc.socketTextStream("localhost",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascendin... | 2.618522 | 3 |
courses/migrations/0003_alter_content_options_alter_module_options_and_more.py | antonnifo/E-Soma | 1 | 4682 | # Generated by Django 4.0.1 on 2022-01-20 13:10
import courses.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0002_video_text_image_file_content'),
]
operations = [
migrations.AlterModelOptions(
name='content',
... | # Generated by Django 4.0.1 on 2022-01-20 13:10
import courses.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0002_video_text_image_file_content'),
]
operations = [
migrations.AlterModelOptions(
name='content',
... | en | 0.869871 | # Generated by Django 4.0.1 on 2022-01-20 13:10 | 1.659792 | 2 |
pkg/maths/maths.py | prateekdegaons1991/experiment-loadtest | 8 | 4683 | #Atoi stands for ASCII to Integer Conversion
def atoi(string):
res = 0
# Iterate through all characters of
# input and update result
for i in range(len(string)):
res = res * 10 + (ord(string[i]) - ord('0'))
return res
#Adjustment contains rule of three for calculating an integer given an... | #Atoi stands for ASCII to Integer Conversion
def atoi(string):
res = 0
# Iterate through all characters of
# input and update result
for i in range(len(string)):
res = res * 10 + (ord(string[i]) - ord('0'))
return res
#Adjustment contains rule of three for calculating an integer given an... | en | 0.842281 | #Atoi stands for ASCII to Integer Conversion # Iterate through all characters of # input and update result #Adjustment contains rule of three for calculating an integer given another integer representing a percentage | 3.902131 | 4 |
google_compute_engine/config_manager.py | redoxdrh/GCP-Flask | 2 | 4684 | #!/usr/bin/python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | #!/usr/bin/python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | en | 0.745963 | #!/usr/bin/python # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli... | 2.551059 | 3 |
mscreen/autodocktools_prepare_py3k/mglutil/web/services/AppService_services.py | e-mayo/mscreen | 9 | 4685 | <reponame>e-mayo/mscreen
##################################################
# ./AppService_services.py
# generated by ZSI.wsdl2python
#
#
##################################################
from .AppService_services_types import *
from .AppService_services_types import \
nbcr_sdsc_edu_opal_types as ns1
import... | ##################################################
# ./AppService_services.py
# generated by ZSI.wsdl2python
#
#
##################################################
from .AppService_services_types import *
from .AppService_services_types import \
nbcr_sdsc_edu_opal_types as ns1
import urllib.parse, types
from... | en | 0.160395 | ################################################## # ./AppService_services.py # generated by ZSI.wsdl2python # # ################################################## @param: request is str @return: response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str ... | 2.125176 | 2 |
examples/pytorch/swin/checkpoint_quantization.py | hieuhoang/FasterTransformer | 0 | 4686 | # Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | en | 0.474087 | # Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ... | 1.548571 | 2 |
mars/deploy/kubernetes/core.py | tomzhang/mars-1 | 0 | 4687 | # -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | # -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | en | 0.802078 | # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require... | 1.903679 | 2 |
tests/tests_model/tests_bert_model.py | elangovana/gene_normalisation | 1 | 4688 | from unittest import TestCase
import torch
import transformers
from model.bert_model import BertModel
class TestBertModel(TestCase):
def test_forward(self):
# Bert Config
vocab_size = 10
sequence_len = 20
batch = 32
num_classes = 3
expected_shape = (batch, seque... | from unittest import TestCase
import torch
import transformers
from model.bert_model import BertModel
class TestBertModel(TestCase):
def test_forward(self):
# Bert Config
vocab_size = 10
sequence_len = 20
batch = 32
num_classes = 3
expected_shape = (batch, seque... | en | 0.661756 | # Bert Config # Act # Assert | 2.960166 | 3 |
tests/renderer_test.py | tmcclintock/PyDonJuan | 2 | 4689 | import json
import os
import tempfile
from unittest import TestCase
import pytest
from donjuan import Dungeon, DungeonRandomizer, Renderer
class RendererTest(TestCase):
def setUp(self):
super().setUp()
self.TEMP_DIR = tempfile.mkdtemp()
def test_smoke(self):
r = Renderer()
a... | import json
import os
import tempfile
from unittest import TestCase
import pytest
from donjuan import Dungeon, DungeonRandomizer, Renderer
class RendererTest(TestCase):
def setUp(self):
super().setUp()
self.TEMP_DIR = tempfile.mkdtemp()
def test_smoke(self):
r = Renderer()
a... | en | 0.880184 | # Render and check for the file # Render and check for the file | 2.504904 | 3 |
src/foremast/validate.py | dnava013/foremast | 157 | 4690 | <gh_stars>100-1000
"""Spinnaker validate functions."""
import logging
from .consts import API_URL
from .utils.credentials import get_env_credential
LOG = logging.getLogger(__name__)
def validate_gate():
"""Check Gate connection."""
try:
credentials = get_env_credential()
LOG.debug('Found cre... | """Spinnaker validate functions."""
import logging
from .consts import API_URL
from .utils.credentials import get_env_credential
LOG = logging.getLogger(__name__)
def validate_gate():
"""Check Gate connection."""
try:
credentials = get_env_credential()
LOG.debug('Found credentials: %s', cred... | en | 0.624976 | Spinnaker validate functions. Check Gate connection. Run all validate steps. | 2.846659 | 3 |
constellation_forms/migrations/0001_initial.py | ConstellationApps/Forms | 2 | 4691 | <filename>constellation_forms/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-15 00:56
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletio... | <filename>constellation_forms/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-15 00:56
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletio... | en | 0.738151 | # -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-15 00:56 | 1.622778 | 2 |
src/webpy1/src/borough/dbsqli.py | ptphp/PyLib | 1 | 4692 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3 as sqlite
import os.path as osp
import sys
class Sqli(object):
conn = ''
cursor = ''
def __init__(self, dbname):
try:
self.conn = sqlite.connect(osp.abspath(dbname))
except Exception, what:
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3 as sqlite
import os.path as osp
import sys
class Sqli(object):
conn = ''
cursor = ''
def __init__(self, dbname):
try:
self.conn = sqlite.connect(osp.abspath(dbname))
except Exception, what:
print wh... | en | 0.407084 | #!/usr/bin/env python # -*- coding: utf-8 -*- CREATE TABLE IF NOT EXISTS [website]( [id] INTEGER PRIMARY KEY, [siteName] TEXT, [loginUrl] TEXT, [loginQuery] TEXT, [postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName])); CREATE INDEX IF NOT EXISTS [website_idx_siteName] ON [websit... | 3.566012 | 4 |
losses/all_lost.py | Liudzz/loss-chapter | 2 | 4693 | """
easy way to use losses
"""
from center_loss import Centerloss
import torch.nn as nn
from FocalLoss import FocalLoss
def center_loss(pred,label,num_calss,feature):
loss = Centerloss(num_calss,feature)
return loss(pred,label)
def Focal_loss(pred,label,num_calss,alaph=None, gamma):
loss = Centerloss(num... | """
easy way to use losses
"""
from center_loss import Centerloss
import torch.nn as nn
from FocalLoss import FocalLoss
def center_loss(pred,label,num_calss,feature):
loss = Centerloss(num_calss,feature)
return loss(pred,label)
def Focal_loss(pred,label,num_calss,alaph=None, gamma):
loss = Centerloss(num... | en | 0.789278 | easy way to use losses | 2.742859 | 3 |
nova/tests/functional/test_metadata.py | Nexenta/nova | 1 | 4694 | # Copyright 2016 Rackspace Australia
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | # Copyright 2016 Rackspace Australia
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | en | 0.859223 | # Copyright 2016 Rackspace Australia # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi... | 1.82482 | 2 |
openue/sequence_labeling/subject_labeling_data_manager.py | zxlzr/OpenUE | 8 | 4695 | import os
import sys
import json
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../bert")))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
import tokenization
from config import config
class Model_data_preparation(object):
def __init__(self, DATA_... | import os
import sys
import json
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../bert")))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
import tokenization
from config import config
class Model_data_preparation(object):
def __init__(self, DATA_... | zh | 0.464947 | # 初始化 bert_token 工具 Known q_list in k_list, find index(first time) of q_list in k_list # print(idx, t) # print(idx) 实体: "1981年" 原句: "●1981年2月27日,中国人口学会成立" so_tokened ['1981', '年'] text_tokened ['●', '##19', '##81', '年', '2', '月', '27', '日', ',', '中', '国', '人', '口', '学', '会', '成', '立'] ... | 2.473582 | 2 |
clarifai/rest/grpc/custom_converters/custom_message_to_dict.py | Taik/clarifai-python | 322 | 4696 | <reponame>Taik/clarifai-python
import typing # noqa
from google.protobuf import descriptor
from google.protobuf.json_format import _IsMapEntry, _Printer
from google.protobuf.message import Message # noqa
from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2
def protobuf_to_dict(object_protobuf, u... | import typing # noqa
from google.protobuf import descriptor
from google.protobuf.json_format import _IsMapEntry, _Printer
from google.protobuf.message import Message # noqa
from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2
def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ign... | en | 0.844027 | # noqa # noqa # type: (Message, typing.Optional[bool], typing.Optional[bool]) -> dict # printer = _CustomPrinter( # pylint: disable=protected-access Because of the fields with the custom extension `cl_show_if_empty`, we need to adjust the original's method's return JSON object and keep these fields. # Singular mess... | 1.856141 | 2 |
__init__.py | mschrimpf/CapsNetKeras | 0 | 4697 | <gh_stars>0
from .capsulenet import *
| from .capsulenet import * | none | 1 | 1.094931 | 1 | |
gate/mate_ksx3267v2.py | mrchoi87/IRSOSv4 | 0 | 4698 | <filename>gate/mate_ksx3267v2.py
#!/usr/bin/env python
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 JiNong, Inc.
# All right reserved.
#
import struct
import time
import socket
import select
import traceback
import hashlib
import json
from enum import IntEnum
from threading import Thread, Lock
from mate import Mat... | <filename>gate/mate_ksx3267v2.py
#!/usr/bin/env python
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 JiNong, Inc.
# All right reserved.
#
import struct
import time
import socket
import select
import traceback
import hashlib
import json
from enum import IntEnum
from threading import Thread, Lock
from mate import Mat... | en | 0.573628 | #!/usr/bin/env python # # -*- coding: utf-8 -*- # # Copyright (c) 2018 JiNong, Inc. # All right reserved. # #self._nodes = self._devinfo.getgw()["children"] #mrchoi87 # Detection Started #mrchoi87 #for unit in range(self._detection["saddr"], 12): # Detection Started # Detection Started # device type # unknown protocol ... | 1.974604 | 2 |
CircleciScripts/run_integrationtests.py | aimalygin/aws-sdk-ios | 17 | 4699 | <filename>CircleciScripts/run_integrationtests.py
import demjson
import sys
from subprocess import Popen, PIPE
import subprocess
import xml.etree.ElementTree as ET
import os
from datetime import datetime
from functions import runcommand
#from sets import Set
def getfailedcases(withBundle = True):
xmlfile='build/... | <filename>CircleciScripts/run_integrationtests.py
import demjson
import sys
from subprocess import Popen, PIPE
import subprocess
import xml.etree.ElementTree as ET
import os
from datetime import datetime
from functions import runcommand
#from sets import Set
def getfailedcases(withBundle = True):
xmlfile='build/... | en | 0.368557 | #from sets import Set #TODO we can filter with condtion #run test ########################## main function ############################### # a command will like # testcommandhead = f"xcodebuild test-without-building -project {projectName} -scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},na... | 2.143866 | 2 |