code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from flask import Blueprint, jsonify, session, request, redirect, url_for, render_template
from flask_dance.consumer import OAuth2ConsumerBlueprint
import logging
import json
import oauthlib
import datetime
import traceback
import urllib.parse
from datetime import timezone
from activity.activity import activity
from c... | project-api/server/routes/selfserve.py | from flask import Blueprint, jsonify, session, request, redirect, url_for, render_template
from flask_dance.consumer import OAuth2ConsumerBlueprint
import logging
import json
import oauthlib
import datetime
import traceback
import urllib.parse
from datetime import timezone
from activity.activity import activity
from c... | 0.290176 | 0.031232 |
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
from todo.models import Lst
from hier.models import Lst
app_name = 'store'
#----------------------------------
# deprecated
class Group(mod... | store/models.py | from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
from todo.models import Lst
from hier.models import Lst
app_name = 'store'
#----------------------------------
# deprecated
class Group(mod... | 0.326271 | 0.055592 |
CHARMAP = {
#0x0000:"亜", # dqviewer では「亜」だが、うまくいかない
0x0000:" ",
0x0001:"園",
0x0002:"馬",
0x0003:"平",
0x0004:"閉",
0x0005:"辺",
0x0006:"飛",
0x0007:"匹",
0x0008:"ぷ",
0x0009:"亡",
0x000A:"不",
0x000B:"風",
0x000C:"聞",
0x000D:"囲",
0x000E:"因",
0x000F:"院",
0x0... | dqutils/dq5/charlarge.py | CHARMAP = {
#0x0000:"亜", # dqviewer では「亜」だが、うまくいかない
0x0000:" ",
0x0001:"園",
0x0002:"馬",
0x0003:"平",
0x0004:"閉",
0x0005:"辺",
0x0006:"飛",
0x0007:"匹",
0x0008:"ぷ",
0x0009:"亡",
0x000A:"不",
0x000B:"風",
0x000C:"聞",
0x000D:"囲",
0x000E:"因",
0x000F:"院",
0x0... | 0.132248 | 0.361897 |
import face_recognition
from cv2 import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import traceback
import os
def SearchPersonFR(image, database, model):
'''
Function to find who the person is
Arguments:
image {cv2 image} -- image of the person
database {dict} -... | ObjectDetection/faceTest.py | import face_recognition
from cv2 import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import traceback
import os
def SearchPersonFR(image, database, model):
'''
Function to find who the person is
Arguments:
image {cv2 image} -- image of the person
database {dict} -... | 0.514156 | 0.312108 |
from helper import utility as util
import os
import configparser
import numpy as np
from scipy import misc
import random
import logging
INPUT_IMAGE_DIR = "input"
INTERPOLATED_IMAGE_DIR = "interpolated"
TRUE_IMAGE_DIR = "true"
def convert_to_multi_channel_image(multi_channel_image, image, scale):
height = multi_c... | helper/loader.py | from helper import utility as util
import os
import configparser
import numpy as np
from scipy import misc
import random
import logging
INPUT_IMAGE_DIR = "input"
INTERPOLATED_IMAGE_DIR = "interpolated"
TRUE_IMAGE_DIR = "true"
def convert_to_multi_channel_image(multi_channel_image, image, scale):
height = multi_c... | 0.546496 | 0.266612 |
import sys
import argparse
OFFSET = 0xc0e0
# Not at all sure about the max length of the binary path to be started but
LENGTH = 32
CONTENT = b'/\x00b\x00i\x00n\x00/\x00b\x00a\x00s\x00h'
def find_offset(binary):
for i in range(0, len(binary)):
if binary[i:i+len(CONTENT)] == CONTENT:
... | wsl-bashexe-patcher.py | import sys
import argparse
OFFSET = 0xc0e0
# Not at all sure about the max length of the binary path to be started but
LENGTH = 32
CONTENT = b'/\x00b\x00i\x00n\x00/\x00b\x00a\x00s\x00h'
def find_offset(binary):
for i in range(0, len(binary)):
if binary[i:i+len(CONTENT)] == CONTENT:
... | 0.21626 | 0.152663 |
import numpy as np
import pandas as pd
import cv2
import os
import imageio
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
import pickle
import itertools
import json
import glob
import collections
import shutil
import pickle
import re
DTYPE = "float32"
PD_SEP = ","
PD_NAN = np.inf
PD_DTYPE = ... | HTPA32x32d/tools.py | import numpy as np
import pandas as pd
import cv2
import os
import imageio
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
import pickle
import itertools
import json
import glob
import collections
import shutil
import pickle
import re
DTYPE = "float32"
PD_SEP = ","
PD_NAN = np.inf
PD_DTYPE = ... | 0.745584 | 0.316303 |
from branje_strani import shrani_stran, nalozi_stran_iz_datoteke
MAPA_KATALOGA = 'katalog'
def dobi_ime_strani_indeks(indeks):
return f'{MAPA_KATALOGA}\stran_{indeks}.html'
# v vzorec strani vstavimo indeks nato pa shranimo stran s tem url-jem
OSNOVA_SPAR_STRANI = 'https://www.spar.si'
VZOREC_STRANI = OSNOVA_SPAR... | branje_kataloga.py | from branje_strani import shrani_stran, nalozi_stran_iz_datoteke
MAPA_KATALOGA = 'katalog'
def dobi_ime_strani_indeks(indeks):
return f'{MAPA_KATALOGA}\stran_{indeks}.html'
# v vzorec strani vstavimo indeks nato pa shranimo stran s tem url-jem
OSNOVA_SPAR_STRANI = 'https://www.spar.si'
VZOREC_STRANI = OSNOVA_SPAR... | 0.257952 | 0.14885 |
import os
import shutil
import sys
from PIL import Image, ImageChops, ImageDraw
from photoshoppy.models.blend_mode.model import BlendMode, ALL_BLEND_MODES
from photoshoppy.psd_file import PSDFile
from photoshoppy.psd_render import render_utils
THIS_DIR = os.path.dirname(__file__)
BLENDING_MODES_DIR = os.path.join(TH... | tests/test_blending_modes.py | import os
import shutil
import sys
from PIL import Image, ImageChops, ImageDraw
from photoshoppy.models.blend_mode.model import BlendMode, ALL_BLEND_MODES
from photoshoppy.psd_file import PSDFile
from photoshoppy.psd_render import render_utils
THIS_DIR = os.path.dirname(__file__)
BLENDING_MODES_DIR = os.path.join(TH... | 0.26693 | 0.143998 |
#Initiate
import pygame
import Tile
#PlayerClass
class player(pygame.sprite.Sprite):
def __init__(self,x=7,y=8):
self.speed = 2
#Image variables
self.i=1
self.j=0
#Awareness
self.location=Tile.tile.grid[x][y]
self.radar=Tile.tile.grid[x][y+1]
... | PokePengo/Player.py |
#Initiate
import pygame
import Tile
#PlayerClass
class player(pygame.sprite.Sprite):
def __init__(self,x=7,y=8):
self.speed = 2
#Image variables
self.i=1
self.j=0
#Awareness
self.location=Tile.tile.grid[x][y]
self.radar=Tile.tile.grid[x][y+1]
... | 0.095102 | 0.096025 |
from fastapi import APIRouter
from starlette.requests import Request
from app.api.utils.responseCode import resp_200, resp_400, resp_500
from app.supervisor_.core.clogger import ActivityLog
router = APIRouter()
activity = ActivityLog.getInstance()
def get_nodes(*, request: Request, ):
nodes = request.app.state.... | backend/app/app/api/api_v1/router/supervisord/nodes.py | from fastapi import APIRouter
from starlette.requests import Request
from app.api.utils.responseCode import resp_200, resp_400, resp_500
from app.supervisor_.core.clogger import ActivityLog
router = APIRouter()
activity = ActivityLog.getInstance()
def get_nodes(*, request: Request, ):
nodes = request.app.state.... | 0.192312 | 0.07836 |
import sqlite3
def __sqlite(query: str):
con = sqlite3.connect("../resources_manager/ttbm.db")
cur = con.cursor()
cur.execute(query)
result = cur.fetchall()
con.commit()
con.close()
return result
def sqlite_3_add_user(name: str, password: str, id: int):
__sqlite(f"INSERT INTO user... | bot/bot/resources_manager/sql.py | import sqlite3
def __sqlite(query: str):
con = sqlite3.connect("../resources_manager/ttbm.db")
cur = con.cursor()
cur.execute(query)
result = cur.fetchall()
con.commit()
con.close()
return result
def sqlite_3_add_user(name: str, password: str, id: int):
__sqlite(f"INSERT INTO user... | 0.186762 | 0.15588 |
import os
import glob
import shutil
import argparse
import subprocess
# convert a .mid file to a .omd file using the omdconvert.exe program by OneTesla
def convert_midi_to_omd(file_path: str):
# get absolute path from relative path
absolute_path = os.path.abspath(file_path)
# execute the omd converter wi... | convertall.py | import os
import glob
import shutil
import argparse
import subprocess
# convert a .mid file to a .omd file using the omdconvert.exe program by OneTesla
def convert_midi_to_omd(file_path: str):
# get absolute path from relative path
absolute_path = os.path.abspath(file_path)
# execute the omd converter wi... | 0.40592 | 0.305115 |
import unittest
from unittest import mock
import jinja2
from pythonforandroid.build import run_pymodules_install
from pythonforandroid.archs import ArchARMv7_a, ArchAarch_64
class TestBuildBasic(unittest.TestCase):
def test_run_pymodules_install_optional_project_dir(self):
"""
Makes sure the `r... | tests/test_build.py | import unittest
from unittest import mock
import jinja2
from pythonforandroid.build import run_pymodules_install
from pythonforandroid.archs import ArchARMv7_a, ArchAarch_64
class TestBuildBasic(unittest.TestCase):
def test_run_pymodules_install_optional_project_dir(self):
"""
Makes sure the `r... | 0.63477 | 0.354293 |
from flask import render_template, url_for, request, flash, redirect
# importation de render_template (relie les templates aux routes), url_for (permet de construire des url vers les
# fonctions et les pages html), request (permet d'importer types d'objets et de les utiliser comme insinstance),
# flash (envoie des me... | app/routes/generic.py | from flask import render_template, url_for, request, flash, redirect
# importation de render_template (relie les templates aux routes), url_for (permet de construire des url vers les
# fonctions et les pages html), request (permet d'importer types d'objets et de les utiliser comme insinstance),
# flash (envoie des me... | 0.291182 | 0.320383 |
import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from ..io.x_input_stream import XInputStream as XInputStream_98d40ab4
from ..io.x_output_stream import XOutputStream as XOutputStream_a4e00b35
class XBinaryStreamResolver(XInter... | ooobuild/lo/document/x_binary_stream_resolver.py | import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from ..io.x_input_stream import XInputStream as XInputStream_98d40ab4
from ..io.x_output_stream import XOutputStream as XOutputStream_a4e00b35
class XBinaryStreamResolver(XInter... | 0.733547 | 0.463869 |
import copy
class ChangeCheckerMixin(object):
containerItems = {dict: dict.iteritems, list: enumerate}
immutable = False
def snapshot(self):
''' create a snapshot of self's state -- like a shallow copy, but
recursing over container types (not over general instances:
instances... | lang/py/cookbook/v2/source/cb2_6_12_sol_1.py | import copy
class ChangeCheckerMixin(object):
containerItems = {dict: dict.iteritems, list: enumerate}
immutable = False
def snapshot(self):
''' create a snapshot of self's state -- like a shallow copy, but
recursing over container types (not over general instances:
instances... | 0.291787 | 0.105579 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Union
from discord import ButtonStyle, Embed
from discord.ui import View, button as button_decorator
from discord.utils import maybe_coroutine
if TYPE_CHECKING:
from typing_extensions import Self
from discord import Interacti... | utils/simple_paginator.py | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Union
from discord import ButtonStyle, Embed
from discord.ui import View, button as button_decorator
from discord.utils import maybe_coroutine
if TYPE_CHECKING:
from typing_extensions import Self
from discord import Interacti... | 0.878731 | 0.092934 |
import json
from typing import Any, Dict, List
import requests
from ...shared.exceptions import PermissionException
from ...shared.interfaces.logging import LoggingModule
from .interface import NotAllowed, PermissionService
class PermissionHTTPAdapter(PermissionService):
"""
Adapter to connect to permission... | openslides_backend/services/permission/adapter.py | import json
from typing import Any, Dict, List
import requests
from ...shared.exceptions import PermissionException
from ...shared.interfaces.logging import LoggingModule
from .interface import NotAllowed, PermissionService
class PermissionHTTPAdapter(PermissionService):
"""
Adapter to connect to permission... | 0.36886 | 0.098425 |
# Author: <NAME> (<EMAIL>)
# modules
import string, re, collections
import os, sys, subprocess
from optparse import OptionParser
# BioPython modules for reading and writing sequences
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
def main():
usage ... | database_clustering/csv_to_gene_db.py |
# Author: <NAME> (<EMAIL>)
# modules
import string, re, collections
import os, sys, subprocess
from optparse import OptionParser
# BioPython modules for reading and writing sequences
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
def main():
usage ... | 0.344774 | 0.191479 |
# 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, publish, distribute, sublicense, and/or
# sell cop... | sigal/plugins/extended_caching.py |
# 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, publish, distribute, sublicense, and/or
# sell cop... | 0.444203 | 0.16378 |
# The MIT License (MIT)
# Copyright (c) 2018 AndyTempel
# 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, m... | dblapi/router.py |
# The MIT License (MIT)
# Copyright (c) 2018 AndyTempel
# 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, m... | 0.781747 | 0.124532 |
"""This model adds noise/rir to signal."""
import delta.compat as tf
from delta.utils.hparam import HParams
from core.ops import py_x_ops
from delta.data.frontend.base_frontend import BaseFrontend
class Add_rir_noise_aecres(BaseFrontend):
"""
Add a random signal-to-noise ratio noise or impulse response to clean ... | delta/data/frontend/add_rir_noise_aecres.py | """This model adds noise/rir to signal."""
import delta.compat as tf
from delta.utils.hparam import HParams
from core.ops import py_x_ops
from delta.data.frontend.base_frontend import BaseFrontend
class Add_rir_noise_aecres(BaseFrontend):
"""
Add a random signal-to-noise ratio noise or impulse response to clean ... | 0.861217 | 0.466177 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_lightning.metrics import MulticlassROC, MulticlassPrecisionRecall
from pytorch_lightning.metrics.functional import auc, precision, recall
class MultiAUPRC(nn.Module):
def __init__(self, num_classes: int):
super(MultiAUPRC, s... | utils/metrics.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_lightning.metrics import MulticlassROC, MulticlassPrecisionRecall
from pytorch_lightning.metrics.functional import auc, precision, recall
class MultiAUPRC(nn.Module):
def __init__(self, num_classes: int):
super(MultiAUPRC, s... | 0.963695 | 0.683726 |
import sys
class Tokenizer:
CTX_NO = 'NO'
CTX_NUMBER = 'NUMBER'
SINGLE_SYMBOLS = ['[', ',', ']']
SPACE_SYMBOLS = [' ', '\t', '\r', '\n']
DEC_NUMBER_SYMBOLS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def __init__(self):
self.tokens = []
def consume(self, line: str):
... | python-1/main.py | import sys
class Tokenizer:
CTX_NO = 'NO'
CTX_NUMBER = 'NUMBER'
SINGLE_SYMBOLS = ['[', ',', ']']
SPACE_SYMBOLS = [' ', '\t', '\r', '\n']
DEC_NUMBER_SYMBOLS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def __init__(self):
self.tokens = []
def consume(self, line: str):
... | 0.232136 | 0.232986 |
import logging
from sys import exc_info
LOGGER = logging.getLogger('anthem.hook')
class Hook(object):
"""A Request Hook callback pointer and its metadata: failsafe, priority, and kwargs."""
callback = None
"""
The bare callable that this Hook object is wrapping, which will
be called when the H... | medoly/anthem/hook.py | import logging
from sys import exc_info
LOGGER = logging.getLogger('anthem.hook')
class Hook(object):
"""A Request Hook callback pointer and its metadata: failsafe, priority, and kwargs."""
callback = None
"""
The bare callable that this Hook object is wrapping, which will
be called when the H... | 0.635449 | 0.193967 |
import torch
import torch.nn as nn
from torch.nn import functional as F
class ColorConstancyLoss(nn.Module):
"""Color Constancy Loss"""
def __init__(self):
super(ColorConstancyLoss, self).__init__()
def forward(self, x):
mean_rgb = torch.mean(x, [2, 3], keepdim=True)
mr, mg, mb =... | zero_dce/losses.py | import torch
import torch.nn as nn
from torch.nn import functional as F
class ColorConstancyLoss(nn.Module):
"""Color Constancy Loss"""
def __init__(self):
super(ColorConstancyLoss, self).__init__()
def forward(self, x):
mean_rgb = torch.mean(x, [2, 3], keepdim=True)
mr, mg, mb =... | 0.964539 | 0.677247 |
from unittest import TestCase
from unittest.mock import patch, ANY
import responses
import azkaban_cli.azkaban
from azkaban_cli.exceptions import FetchFlowExecutionUpdatesError, SessionError
class AzkabanFetchFlowExecutionTest(TestCase):
def setUp(self):
"""
Creates an Azkaban instance and set a... | azkaban_cli/tests/test_azkaban/test_fetch_flow_execution_updates.py | from unittest import TestCase
from unittest.mock import patch, ANY
import responses
import azkaban_cli.azkaban
from azkaban_cli.exceptions import FetchFlowExecutionUpdatesError, SessionError
class AzkabanFetchFlowExecutionTest(TestCase):
def setUp(self):
"""
Creates an Azkaban instance and set a... | 0.668123 | 0.374333 |
import plot_class
import random
class Minesweeper:
''' Constructor of the class: start the game for you '''
def __init__( self, lines = 10, cols = 10 ):
self._lines = lines
self._cols = cols
self._map = [ [plot_class.Plot() for i in range(cols) ] for j in range(lines) ]
''' Return... | main.py | import plot_class
import random
class Minesweeper:
''' Constructor of the class: start the game for you '''
def __init__( self, lines = 10, cols = 10 ):
self._lines = lines
self._cols = cols
self._map = [ [plot_class.Plot() for i in range(cols) ] for j in range(lines) ]
''' Return... | 0.495606 | 0.375621 |
import json
import logging
import unittest
from pathlib import Path
import numpy as np
from sira.configuration import Configuration
from sira.model_ingest import ingest_model
from sira.modelling.hazard import HazardsContainer
from sira.scenario import Scenario
from sira.simulation import calculate_response
rootLogger... | tests/test_output_sanity_check.py | import json
import logging
import unittest
from pathlib import Path
import numpy as np
from sira.configuration import Configuration
from sira.model_ingest import ingest_model
from sira.modelling.hazard import HazardsContainer
from sira.scenario import Scenario
from sira.simulation import calculate_response
rootLogger... | 0.562657 | 0.409634 |
class ASTNode:
def __init__(self):
pass
def accept(self, visitor):
return visitor.visitASTNode(self)
class StmtNode(ASTNode):
def __init__(self, content, line_index, stmtcol_index):
"""
stmtcol = statement column
"""
super().__init__()
self.content ... | naming-protocol/ast/ast.py | class ASTNode:
def __init__(self):
pass
def accept(self, visitor):
return visitor.visitASTNode(self)
class StmtNode(ASTNode):
def __init__(self, content, line_index, stmtcol_index):
"""
stmtcol = statement column
"""
super().__init__()
self.content ... | 0.736211 | 0.310838 |
usage = """
Usage:
moses-detokenizer [options] <lang> [<inputfile> [<outputfile>]]
moses-detokenizer --selftest [--verbose]
Options:
--selftest, -t Run selftests.
--verbose, -v Be more verbose.
2017, <NAME> <<EMAIL>>
"""
from docopt import docopt
from openfile import openfile
from os import path
... | github/preprocess/sockeye/code/MOSES/scripts/tokenizer/mosestokenizer/detokenizer.py | usage = """
Usage:
moses-detokenizer [options] <lang> [<inputfile> [<outputfile>]]
moses-detokenizer --selftest [--verbose]
Options:
--selftest, -t Run selftests.
--verbose, -v Be more verbose.
2017, <NAME> <<EMAIL>>
"""
from docopt import docopt
from openfile import openfile
from os import path
... | 0.469277 | 0.24135 |
from typing import Callable, Dict, List, Tuple, Type, Union, Text
import cv2
import numpy as np
from matplotlib import pyplot as plt
from functools import reduce
Image = Type[np.ndarray]
FnWithArgs = Tuple[Callable[..., Image], Dict[Text, int]]
FnWithoutArgs = Tuple[Callable[[Image], Image]]
FunctionList = List[Union... | src/data_preprocessing.py | from typing import Callable, Dict, List, Tuple, Type, Union, Text
import cv2
import numpy as np
from matplotlib import pyplot as plt
from functools import reduce
Image = Type[np.ndarray]
FnWithArgs = Tuple[Callable[..., Image], Dict[Text, int]]
FnWithoutArgs = Tuple[Callable[[Image], Image]]
FunctionList = List[Union... | 0.860823 | 0.544801 |
import os
import sys
import subprocess
from git import GitCommandError
from optparse import OptionParser
from sh import mktemp, cd, rm # pylint: disable=E0611
from functools import partial
try:
from sh import git_dch as gbp_dch # pylint: disable=E0611
gbp_buildpackage = ['git-buildpackage']
except ImportErro... | devflow/autopkg.py | import os
import sys
import subprocess
from git import GitCommandError
from optparse import OptionParser
from sh import mktemp, cd, rm # pylint: disable=E0611
from functools import partial
try:
from sh import git_dch as gbp_dch # pylint: disable=E0611
gbp_buildpackage = ['git-buildpackage']
except ImportErro... | 0.40251 | 0.119305 |
import os
import tempfile
import unittest
from copy import deepcopy
from pathlib import Path
from varats.tools.bb_config import generate_benchbuild_config
from varats.utils.settings import vara_cfg, bb_cfg
class BenchBuildConfig(unittest.TestCase):
"""Test BenchBuild config."""
@classmethod
def setUpCla... | tests/utils/test_bb_config.py | import os
import tempfile
import unittest
from copy import deepcopy
from pathlib import Path
from varats.tools.bb_config import generate_benchbuild_config
from varats.utils.settings import vara_cfg, bb_cfg
class BenchBuildConfig(unittest.TestCase):
"""Test BenchBuild config."""
@classmethod
def setUpCla... | 0.522202 | 0.174903 |
from django.contrib.auth import login, authenticate
from django.shortcuts import render,redirect
from .models import *
from .forms import *
from django.views import generic
# Create your views here.
def condition(request):
context = { }
return render(request,'condition.html',context=context)
def index(request):... | home/views.py | from django.contrib.auth import login, authenticate
from django.shortcuts import render,redirect
from .models import *
from .forms import *
from django.views import generic
# Create your views here.
def condition(request):
context = { }
return render(request,'condition.html',context=context)
def index(request):... | 0.298083 | 0.062703 |
import chain
from behave import given, when, then
from itertools import count
from unittest.mock import MagicMock
from chain.core.domains.state import State
@given("a random number of static chains")
def step_create_random_static_chains(context: dict) -> None:
"""Create a Random Number of Static Chains.
Thi... | chain/tests/acceptance/steps/step_chain.py | import chain
from behave import given, when, then
from itertools import count
from unittest.mock import MagicMock
from chain.core.domains.state import State
@given("a random number of static chains")
def step_create_random_static_chains(context: dict) -> None:
"""Create a Random Number of Static Chains.
Thi... | 0.813572 | 0.605012 |
import torch
import torch.nn as nn
from transformers.generation_utils import GenerationMixin
from transformers.modeling_outputs import Seq2SeqLMOutput
from transformers.models.bert.modeling_bert import BertOnlyMLMHead
from unitorch.modules.prefix_model import (
PrefixConfig,
PrefixTextModel,
_reorder_buffe... | unitorch/models/unilm/modeling.py |
import torch
import torch.nn as nn
from transformers.generation_utils import GenerationMixin
from transformers.modeling_outputs import Seq2SeqLMOutput
from transformers.models.bert.modeling_bert import BertOnlyMLMHead
from unitorch.modules.prefix_model import (
PrefixConfig,
PrefixTextModel,
_reorder_buffe... | 0.923117 | 0.390069 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argume... | youcos/scrape_youtube.py | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argume... | 0.736401 | 0.213603 |
import numpy as np
import matplotlib.pyplot as plt
from gdal import Open as OpenGdal
#-------------------------------------------------------------------------------
fn0 = '../data/SVDNB_npp_20150101-20151231_75N060W_{}_v10_c201701311200.avg_rade9.tif'
# vcm - viirs cloud mask
# vcm-orm = outlier removed
# vcm-ntl =... | sketches/examplemaps.py | import numpy as np
import matplotlib.pyplot as plt
from gdal import Open as OpenGdal
#-------------------------------------------------------------------------------
fn0 = '../data/SVDNB_npp_20150101-20151231_75N060W_{}_v10_c201701311200.avg_rade9.tif'
# vcm - viirs cloud mask
# vcm-orm = outlier removed
# vcm-ntl =... | 0.245447 | 0.28245 |
from requests import Session
if __name__ == '__main__':
s = Session()
s.trust_env = False
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.post('http://1... | scripts/boostrap_server/run_test.py | from requests import Session
if __name__ == '__main__':
s = Session()
s.trust_env = False
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.get('http://127.0.0.1:8008/')
print(resp.text)
resp = s.post('http://1... | 0.278355 | 0.135747 |
import re
from ply.lex import lex
from errors import error
tokens = [
'ARROW', 'ASSIGN', 'COLON', 'COMMA', 'CONST', 'DEF', 'DIVIDE', 'ELSE', 'EQ',
'FALSE', 'FLOAT', 'FOR', 'FOREIGN', 'GE', 'GT', 'ID', 'IF', 'IN', 'INTEGER',
'LAND', 'LBRACE', 'LBRACKET', 'LE', 'LNOT', 'LOR', 'LPAREN', 'LT', 'MINUS',
'NE', 'PLUS', ... | blaze/blir/lexer.py | import re
from ply.lex import lex
from errors import error
tokens = [
'ARROW', 'ASSIGN', 'COLON', 'COMMA', 'CONST', 'DEF', 'DIVIDE', 'ELSE', 'EQ',
'FALSE', 'FLOAT', 'FOR', 'FOREIGN', 'GE', 'GT', 'ID', 'IF', 'IN', 'INTEGER',
'LAND', 'LBRACE', 'LBRACKET', 'LE', 'LNOT', 'LOR', 'LPAREN', 'LT', 'MINUS',
'NE', 'PLUS', ... | 0.243193 | 0.219986 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
from scipy import signal
from scipy import linalg as la
from src.models.sequence.rnns.cells.basic import RNNCell
from src.models.nn.components import LinearActivation, Activation # , get_initializer
from src.models.nn.ga... | src/models/sequence/rnns/cells/memory.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
from scipy import signal
from scipy import linalg as la
from src.models.sequence.rnns.cells.basic import RNNCell
from src.models.nn.components import LinearActivation, Activation # , get_initializer
from src.models.nn.ga... | 0.751101 | 0.482978 |
import re
from dataclasses import dataclass
from datetime import datetime
from typing import List, Callable
from pathlib import Path
from cryptysto.utils import read_csv, asset
from cryptysto.types import *
def load_bitfinex_ledger_file(path: Path) -> BitfinexLedger:
return list(
map(
lambda... | cryptysto/bitfinex.py | import re
from dataclasses import dataclass
from datetime import datetime
from typing import List, Callable
from pathlib import Path
from cryptysto.utils import read_csv, asset
from cryptysto.types import *
def load_bitfinex_ledger_file(path: Path) -> BitfinexLedger:
return list(
map(
lambda... | 0.553505 | 0.13612 |
from os import getcwd
from sys import platform
from csv import DictReader
from graphics import Entry, Image, GraphWin, Point, Rectangle, Text
# Purpose: To output the current working directory w/ the proper trailing delim
# Input: None
# Output: The CWD with the proper OS delim
def myCWD():
myCWD = getcwd()
... | snack_till_lib.py | from os import getcwd
from sys import platform
from csv import DictReader
from graphics import Entry, Image, GraphWin, Point, Rectangle, Text
# Purpose: To output the current working directory w/ the proper trailing delim
# Input: None
# Output: The CWD with the proper OS delim
def myCWD():
myCWD = getcwd()
... | 0.422266 | 0.196036 |
from collections import OrderedDict
from django.utils import timezone
from django.utils.translation import ugettext as _
from rest_framework import serializers
from rest_framework.reverse import reverse
from timetracker.sheets.models import TimeSheet
class TimeSheetSerializer(serializers.ModelSerializer):
hour... | timetracker/sheets/api/serializers.py | from collections import OrderedDict
from django.utils import timezone
from django.utils.translation import ugettext as _
from rest_framework import serializers
from rest_framework.reverse import reverse
from timetracker.sheets.models import TimeSheet
class TimeSheetSerializer(serializers.ModelSerializer):
hour... | 0.701509 | 0.120103 |
import csv
import json
import logging
import re
from pathlib import Path
from hanzipy.exceptions import NotAHanziCharacter
logging.basicConfig(level=logging.DEBUG)
RADICAL_REGEX = r"[一丨丶⺀丿乙⺃乚⺄亅丷]"
CURRENT_DIR = BASE_DIR = Path(__file__).parent
class HanziDecomposer:
def __init__(self):
self.characters... | hanzipy/decomposer.py | import csv
import json
import logging
import re
from pathlib import Path
from hanzipy.exceptions import NotAHanziCharacter
logging.basicConfig(level=logging.DEBUG)
RADICAL_REGEX = r"[一丨丶⺀丿乙⺃乚⺄亅丷]"
CURRENT_DIR = BASE_DIR = Path(__file__).parent
class HanziDecomposer:
def __init__(self):
self.characters... | 0.48121 | 0.215557 |
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from kivy.uix.checkbox import CheckBox
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.widget im... | signalslayout/signaldisplay.py |
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from kivy.uix.checkbox import CheckBox
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.widget im... | 0.51562 | 0.114121 |
import datetime
import gzip
import itertools
import json
import logging
import os
import shutil
import sys
import zipfile
from blsgov_api import load_db_list, get_loader
from config import WRK_DB_DIR, META_FILE_NAME, TMP_DB_DIR, DATA_PREFIX, ASPECT_PREFIX, \
SERIES_PREFIX, JSON_GZ_SUFFIX, JSON_SUFFIX, ZIP_SUFFIX, ... | update.py | import datetime
import gzip
import itertools
import json
import logging
import os
import shutil
import sys
import zipfile
from blsgov_api import load_db_list, get_loader
from config import WRK_DB_DIR, META_FILE_NAME, TMP_DB_DIR, DATA_PREFIX, ASPECT_PREFIX, \
SERIES_PREFIX, JSON_GZ_SUFFIX, JSON_SUFFIX, ZIP_SUFFIX, ... | 0.201499 | 0.071461 |
"""Classes to enumerate TPM data from WMI."""
import logging
from gwinpy.wmi import wmi_query
class TpmInfo(object):
"""Query TPM data in WMI."""
def __init__(self):
self.wmi = wmi_query.WMIQuery(namespace=r'root\cimv2\security\microsofttpm')
def IsActivated(self):
"""Whether the TPM is currently act... | gwinpy/wmi/tpm_info.py | """Classes to enumerate TPM data from WMI."""
import logging
from gwinpy.wmi import wmi_query
class TpmInfo(object):
"""Query TPM data in WMI."""
def __init__(self):
self.wmi = wmi_query.WMIQuery(namespace=r'root\cimv2\security\microsofttpm')
def IsActivated(self):
"""Whether the TPM is currently act... | 0.891052 | 0.250317 |
from arango import ArangoClient
import getpass
import sys
from mypy_extensions import TypedDict
HostAnalysis = TypedDict(
"HostAnalysis", {"protocol": str, "hostname": str, "port": int}
)
def analyze_host(host: str) -> HostAnalysis:
if host[:8] == "https://":
protocol = "https"
elif host[:7] ==... | devops/scripts/ensure_workspace_metadata.py | from arango import ArangoClient
import getpass
import sys
from mypy_extensions import TypedDict
HostAnalysis = TypedDict(
"HostAnalysis", {"protocol": str, "hostname": str, "port": int}
)
def analyze_host(host: str) -> HostAnalysis:
if host[:8] == "https://":
protocol = "https"
elif host[:7] ==... | 0.291989 | 0.223652 |
import os
import re
from selenium.webdriver.remote.webelement import WebElement
from utils.global_holder import GlobalHolder
class ElementAccessor(object):
@staticmethod
def __set_value(element: WebElement, value: str):
if element is None:
return
GlobalHolder.Browser.execute_scri... | tests/utils/element_accessor.py |
import os
import re
from selenium.webdriver.remote.webelement import WebElement
from utils.global_holder import GlobalHolder
class ElementAccessor(object):
@staticmethod
def __set_value(element: WebElement, value: str):
if element is None:
return
GlobalHolder.Browser.execute_scri... | 0.363986 | 0.157687 |
import contextlib
import io
from itertools import zip_longest
from test import QiskitNatureTestCase
import numpy as np
from qiskit_nature.results import ElectronicStructureResult
class TestElectronicStructureResult(QiskitNatureTestCase):
# pylint: disable=attribute-defined-outside-init
"""Additional tests a... | test/results/test_electronic_structure_result.py | import contextlib
import io
from itertools import zip_longest
from test import QiskitNatureTestCase
import numpy as np
from qiskit_nature.results import ElectronicStructureResult
class TestElectronicStructureResult(QiskitNatureTestCase):
# pylint: disable=attribute-defined-outside-init
"""Additional tests a... | 0.692954 | 0.458046 |
import os
import os.path as osp
import numpy as np
from scipy.integrate import odeint
import moviepy.editor as mpy
from qtpy.QtCore import Qt
from qtpy.QtCore import QPointF
from qtpy.QtGui import QColor
from nezzle.graphics import EllipseNode
from nezzle.graphics import TextLabel
from nezzle.graphics import CurvedE... | examples/codes/visualize_ode_lorenz.py | import os
import os.path as osp
import numpy as np
from scipy.integrate import odeint
import moviepy.editor as mpy
from qtpy.QtCore import Qt
from qtpy.QtCore import QPointF
from qtpy.QtGui import QColor
from nezzle.graphics import EllipseNode
from nezzle.graphics import TextLabel
from nezzle.graphics import CurvedE... | 0.29381 | 0.404802 |
import math
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
def _as_mat(x):
if x.ndim == 2:
return x
return x.reshape(len(x), -1)
class Linear(function.Function):
"""Linear function (a.k.a. fully-connected layer or affine transformation)... | chainer/functions/connection/linear.py | import math
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
def _as_mat(x):
if x.ndim == 2:
return x
return x.reshape(len(x), -1)
class Linear(function.Function):
"""Linear function (a.k.a. fully-connected layer or affine transformation)... | 0.888257 | 0.716975 |
try:
from django.utils.unittest import TestCase
except ImportError:
from unittest import TestCase
from django.core.exceptions import ValidationError
from menuhin.models import MenuItem, is_valid_uri, MenuItemGroup, URI
class IsValidUriTestCase(TestCase):
def test_is_valid_scheme(self):
s... | menuhin/tests/models.py | try:
from django.utils.unittest import TestCase
except ImportError:
from unittest import TestCase
from django.core.exceptions import ValidationError
from menuhin.models import MenuItem, is_valid_uri, MenuItemGroup, URI
class IsValidUriTestCase(TestCase):
def test_is_valid_scheme(self):
s... | 0.510008 | 0.405213 |
from api import Base, DBEngine
from datetime import datetime
from fastapi.encoders import jsonable_encoder
from sqlalchemy import Column, ForeignKey, Integer, Float, String, Text, Date, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.types import ARRAY
from sqlalchemy.ext.declarative import declarati... | api/models.py | from api import Base, DBEngine
from datetime import datetime
from fastapi.encoders import jsonable_encoder
from sqlalchemy import Column, ForeignKey, Integer, Float, String, Text, Date, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.types import ARRAY
from sqlalchemy.ext.declarative import declarati... | 0.461988 | 0.184363 |
import sys
import click
import os
import glob
from flask import Flask, Markup, Response, render_template, render_template_string, send_from_directory, current_app, safe_join
from flask_flatpages import FlatPages, pygmented_markdown, pygments_style_defs
from flask_frozen import Freezer
app = Flask(__name__)
app.config... | application.py | import sys
import click
import os
import glob
from flask import Flask, Markup, Response, render_template, render_template_string, send_from_directory, current_app, safe_join
from flask_flatpages import FlatPages, pygmented_markdown, pygments_style_defs
from flask_frozen import Freezer
app = Flask(__name__)
app.config... | 0.339061 | 0.076304 |
from nethack_raph.Findable import *
from nethack_raph.glossaries import MONSTERS_GLOSSARY, ITEMS_TO_THROW, LAUNCHERS, MISSILES
class Item(Findable):
CURSED = 0
UNCURSED = 1
BLESSED = 2
UNKNOWNBUC = 3
bad_effects = ['mimic', 'poisonous', 'hallucination', 'stun', 'die', 'acidic', 'lycanthropy', 'sl... | nethack_raph/Item.py | from nethack_raph.Findable import *
from nethack_raph.glossaries import MONSTERS_GLOSSARY, ITEMS_TO_THROW, LAUNCHERS, MISSILES
class Item(Findable):
CURSED = 0
UNCURSED = 1
BLESSED = 2
UNKNOWNBUC = 3
bad_effects = ['mimic', 'poisonous', 'hallucination', 'stun', 'die', 'acidic', 'lycanthropy', 'sl... | 0.369429 | 0.333408 |
import numpy as np
import cvxpy as cp
from copy import deepcopy
from mvmm.multi_view.block_diag.utils import \
get_guess, get_lin_coef, get_row_col_sum_mat
def get_cp_problem_un_lap(Gamma,
eig_var,
epsilon,
B,
... | mvmm/multi_view/block_diag/sub_prob_cp_un_lap.py | import numpy as np
import cvxpy as cp
from copy import deepcopy
from mvmm.multi_view.block_diag.utils import \
get_guess, get_lin_coef, get_row_col_sum_mat
def get_cp_problem_un_lap(Gamma,
eig_var,
epsilon,
B,
... | 0.785966 | 0.50354 |
import os
import argparse
import numpy as np
import math as ma
import music21 as m21
THREE_DOTTED_BREVE = 15
THREE_DOTTED_32ND = 0.21875
MIN_VELOCITY = 0
MAX_VELOCITY = 128
MIN_TEMPO = 24
MAX_TEMPO = 160
MAX_PITCH = 128
def load(datapath, sample_freq=4, piano_range=(33, 93), transpose_range=10, stretching_ra... | workspace/baseline/midi_encoder.py | import os
import argparse
import numpy as np
import math as ma
import music21 as m21
THREE_DOTTED_BREVE = 15
THREE_DOTTED_32ND = 0.21875
MIN_VELOCITY = 0
MAX_VELOCITY = 128
MIN_TEMPO = 24
MAX_TEMPO = 160
MAX_PITCH = 128
def load(datapath, sample_freq=4, piano_range=(33, 93), transpose_range=10, stretching_ra... | 0.458591 | 0.17427 |
import base64
import json
import googleapiclient.discovery
import string
import time
def process_log_entry(data, context):
data_buffer = base64.b64decode(data['data'])
log_entry = json.loads(data_buffer)
firewall_name = log_entry['jsonPayload']['resource']['name']
project_id = log_entry['resource']['l... | src/main.py | import base64
import json
import googleapiclient.discovery
import string
import time
def process_log_entry(data, context):
data_buffer = base64.b64decode(data['data'])
log_entry = json.loads(data_buffer)
firewall_name = log_entry['jsonPayload']['resource']['name']
project_id = log_entry['resource']['l... | 0.339828 | 0.113064 |
from argparse import ArgumentParser
import os
import subprocess
import logging
import utility
import ome_schema
def extract_metadata(input_path, output_path):
"""
Extract OME metadata from the input file and write it out as a nicely formatted xml using
bftools. (http://www.openmicroscopy.org/site/supp... | src/stack3d/formats/extract_zeiss_metadata.py | from argparse import ArgumentParser
import os
import subprocess
import logging
import utility
import ome_schema
def extract_metadata(input_path, output_path):
"""
Extract OME metadata from the input file and write it out as a nicely formatted xml using
bftools. (http://www.openmicroscopy.org/site/supp... | 0.611266 | 0.195095 |
from __future__ import unicode_literals
from datetime import datetime
import unittest
import warnings
from mixpanel_jql import JQL, raw, Events, People
from mixpanel_jql.query import _f
from mixpanel_jql.exceptions import InvalidJavaScriptText, JQLSyntaxError
class TestJavaScriptArgs(unittest.TestCase):
def s... | tests/test_syntax.py |
from __future__ import unicode_literals
from datetime import datetime
import unittest
import warnings
from mixpanel_jql import JQL, raw, Events, People
from mixpanel_jql.query import _f
from mixpanel_jql.exceptions import InvalidJavaScriptText, JQLSyntaxError
class TestJavaScriptArgs(unittest.TestCase):
def s... | 0.657978 | 0.29294 |
"Types of matter, things made of matter etc"
from useful import weightedchoice
import json
class Matter:
"Everything on the map is matter"
# What is returned when scanned
description = "It's very generic"
shortdesc = "Matter"
# Resources you get when you mine it, in tons
resources = {}
... | Inactive/Prototype1/matter.py | "Types of matter, things made of matter etc"
from useful import weightedchoice
import json
class Matter:
"Everything on the map is matter"
# What is returned when scanned
description = "It's very generic"
shortdesc = "Matter"
# Resources you get when you mine it, in tons
resources = {}
... | 0.581541 | 0.225076 |
from flask_table import Table, Col
# Declare your table
class ItemTable(Table):
name = Col('Infastructure')
description = Col('Quantity')
cost = Col('Info')
# Get some objects
class Item(object):
def __init__(self, name, description, cost):
self.name = name
self.description = descripti... | table.py | from flask_table import Table, Col
# Declare your table
class ItemTable(Table):
name = Col('Infastructure')
description = Col('Quantity')
cost = Col('Info')
# Get some objects
class Item(object):
def __init__(self, name, description, cost):
self.name = name
self.description = descripti... | 0.606265 | 0.136005 |
# Standard library:
from datetime import datetime
from datetime import timedelta
# Django:
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import Http404
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import redire... | populaires/views.py | # Standard library:
from datetime import datetime
from datetime import timedelta
# Django:
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import Http404
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import redire... | 0.535827 | 0.085633 |
import numpy as np
import keras.applications
from keras.layers import Dropout, Dense, BatchNormalization, Flatten
from keras.models import Model
from keras.optimizers import Adam
from helper import constant
from matplotlib import pyplot as plt
class NetworkModel:
def pretrained_model(self):
"""
:r... | src/network_model.py | import numpy as np
import keras.applications
from keras.layers import Dropout, Dense, BatchNormalization, Flatten
from keras.models import Model
from keras.optimizers import Adam
from helper import constant
from matplotlib import pyplot as plt
class NetworkModel:
def pretrained_model(self):
"""
:r... | 0.943348 | 0.530662 |
from igem_wikisync import wikisync as sync
from igem_wikisync.logger import logger
import os
import sys
from hashlib import md5
config = {
'team': 'UTokyo', # change the team name!
'src_dir': 'public/',
'build_dir': 'build/',
'year': '2021',
'silence_warnings': False,
'poster... | hexogem/wikisync.py | from igem_wikisync import wikisync as sync
from igem_wikisync.logger import logger
import os
import sys
from hashlib import md5
config = {
'team': 'UTokyo', # change the team name!
'src_dir': 'public/',
'build_dir': 'build/',
'year': '2021',
'silence_warnings': False,
'poster... | 0.157234 | 0.052595 |
from random import randint
from unicodedata import normalize
def remover_acentos(string):
"""Recebe uma string e retorna a versão dela sem acentos ortográficos e em lowercase."""
normalizado = normalize('NFD', string)
return normalizado.encode('ascii', 'ignore').decode('utf8').lower()
def validar_entrad... | jogo_da_forca.py | from random import randint
from unicodedata import normalize
def remover_acentos(string):
"""Recebe uma string e retorna a versão dela sem acentos ortográficos e em lowercase."""
normalizado = normalize('NFD', string)
return normalizado.encode('ascii', 'ignore').decode('utf8').lower()
def validar_entrad... | 0.576184 | 0.406273 |
for i in range(5):
print(i)
''' Output:
0
1
2
3
4
'''
# RANGE and CONTINUE
# ==========================
for i in range(5):
if i == 3:
continue
print(i)
''' Output:
0
1
2
4
'''
# RANGE and BREAK
# ==========================
for i in range(5):
if i == 3:
break
print(i)
''' Output:... | ForLoop.py | for i in range(5):
print(i)
''' Output:
0
1
2
3
4
'''
# RANGE and CONTINUE
# ==========================
for i in range(5):
if i == 3:
continue
print(i)
''' Output:
0
1
2
4
'''
# RANGE and BREAK
# ==========================
for i in range(5):
if i == 3:
break
print(i)
''' Output:... | 0.039426 | 0.165593 |
from torch import Tensor
from torch.nn import CrossEntropyLoss
from torch.nn import BCEWithLogitsLoss
from leanai.training.losses.loss import Loss
from leanai.training.loss_registry import register_loss
@register_loss()
class SparseCrossEntropyLossFromLogits(Loss):
def __init__(self, reduction: str = "mean"):
... | leanai/training/losses/classification.py | from torch import Tensor
from torch.nn import CrossEntropyLoss
from torch.nn import BCEWithLogitsLoss
from leanai.training.losses.loss import Loss
from leanai.training.loss_registry import register_loss
@register_loss()
class SparseCrossEntropyLossFromLogits(Loss):
def __init__(self, reduction: str = "mean"):
... | 0.964128 | 0.776178 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .util import d
class GRU(nn.Module):
"""
Transformer for classifying sequences
"""
def __init__(self, emb, depth, hidden_size, seq_length, num_tokens, num_classes,
ff_hidden_mult=2, dropout=0.0, directions=1):
"""
... | former/rnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .util import d
class GRU(nn.Module):
"""
Transformer for classifying sequences
"""
def __init__(self, emb, depth, hidden_size, seq_length, num_tokens, num_classes,
ff_hidden_mult=2, dropout=0.0, directions=1):
"""
... | 0.959173 | 0.457561 |
import discord
from discord.ext import commands
import database as db
import variables as var
from functions import get_prefix
def has_command_permission():
async def predicate(ctx: commands.Context):
plugin_name = ctx.cog.__cog_name__
cmd_name = ctx.command.name
guild_doc = await db.PERMI... | axiol/ext/permissions.py | import discord
from discord.ext import commands
import database as db
import variables as var
from functions import get_prefix
def has_command_permission():
async def predicate(ctx: commands.Context):
plugin_name = ctx.cog.__cog_name__
cmd_name = ctx.command.name
guild_doc = await db.PERMI... | 0.357568 | 0.218471 |
from sqlalchemy import Column, Integer, String, create_engine, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import Column, Integer, String, create_engine, DateTime, ForeignKey
from sqlalchemy.orm import sessionmaker
from datetime ... | persistence/models.py | from sqlalchemy import Column, Integer, String, create_engine, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import Column, Integer, String, create_engine, DateTime, ForeignKey
from sqlalchemy.orm import sessionmaker
from datetime ... | 0.646237 | 0.094385 |
import tensorflow as _tf
from abc import ABC as _ABC, abstractmethod as _abstractmethod
from .input import UpdateInput
from .mlp import MLP
class UpdateLayer(_tf.keras.layers.Layer, _ABC):
"""Base Update Layer abstract class to be inherited by Update Layer implementations.
Abstract class to define handling ... | gnn/update.py | import tensorflow as _tf
from abc import ABC as _ABC, abstractmethod as _abstractmethod
from .input import UpdateInput
from .mlp import MLP
class UpdateLayer(_tf.keras.layers.Layer, _ABC):
"""Base Update Layer abstract class to be inherited by Update Layer implementations.
Abstract class to define handling ... | 0.936786 | 0.371222 |
import numpy as np
import random
import torch
from torch.backends import cudnn
from absl import app, flags
from datasets import ML1M, ML100K, Flixster, Douban, YahooMusic
from model import GCCF
from hyperparameters import hparams
from utils import get_adj
cudnn.deterministic = True
cudnn.benchmark = False
seed = 12... | main.py | import numpy as np
import random
import torch
from torch.backends import cudnn
from absl import app, flags
from datasets import ML1M, ML100K, Flixster, Douban, YahooMusic
from model import GCCF
from hyperparameters import hparams
from utils import get_adj
cudnn.deterministic = True
cudnn.benchmark = False
seed = 12... | 0.727782 | 0.218148 |
BAZEL_SKYLIB_RELEASE = "1.0.3"
BAZEL_SKYLIB_SHA256 = "1c531376ac7e5a180e0237938a2536de0c54d93f5c278634818e0efc952dd56c"
OPENCENSUS_PROTO_RELEASE = "0.3.0"
OPENCENSUS_PROTO_SHA256 = "b7e13f0b4259e80c3070b583c2f39e53153085a6918718b1c710caf7037572b0"
PGV_GIT_SHA = "278964a8052f96a2f514add0298098f63fb7f47f" # June 9, 20... | generated_api_shadow/bazel/repository_locations.bzl | BAZEL_SKYLIB_RELEASE = "1.0.3"
BAZEL_SKYLIB_SHA256 = "1c531376ac7e5a180e0237938a2536de0c54d93f5c278634818e0efc952dd56c"
OPENCENSUS_PROTO_RELEASE = "0.3.0"
OPENCENSUS_PROTO_SHA256 = "b7e13f0b4259e80c3070b583c2f39e53153085a6918718b1c710caf7037572b0"
PGV_GIT_SHA = "278964a8052f96a2f514add0298098f63fb7f47f" # June 9, 20... | 0.24899 | 0.163713 |
from datetime import datetime as dt
import logging
from secrets import token_urlsafe
from flask import (
request,
render_template,
flash,
redirect,
Blueprint,
url_for,
current_app
)
from flask_babel import lazy_gettext as _l
from flask_login import current_user, logout_user, login_user
from... | {{cookiecutter.project_name}}/{{cookiecutter.app_name}}/auth/views.py | from datetime import datetime as dt
import logging
from secrets import token_urlsafe
from flask import (
request,
render_template,
flash,
redirect,
Blueprint,
url_for,
current_app
)
from flask_babel import lazy_gettext as _l
from flask_login import current_user, logout_user, login_user
from... | 0.321993 | 0.057838 |
__all__ = [
"End",
"Byte",
"Short",
"Int",
"Long",
"Float",
"Double",
"ByteArray",
"String",
"List",
"Compound",
"IntArray",
"LongArray",
"EndInstantiation",
"OutOfRange",
"IncompatibleItemType",
"CastError",
]
from struct import... | nbtlib/tag.py | __all__ = [
"End",
"Byte",
"Short",
"Int",
"Long",
"Float",
"Double",
"ByteArray",
"String",
"List",
"Compound",
"IntArray",
"LongArray",
"EndInstantiation",
"OutOfRange",
"IncompatibleItemType",
"CastError",
]
from struct import... | 0.893629 | 0.263682 |
from functools import wraps
import logging
import time
from stevedore import ExtensionManager
import numpy as np
logger = logging.getLogger(__name__)
SQRT3 = np.sqrt(3)
SQRT2 = np.sqrt(2)
SQRTPI = np.sqrt(np.pi)
IMAGE_MAX = 255.99999
class NoiseError(Exception):
def __init__(self, noise, thresh):
... | pyfibre/utilities.py | from functools import wraps
import logging
import time
from stevedore import ExtensionManager
import numpy as np
logger = logging.getLogger(__name__)
SQRT3 = np.sqrt(3)
SQRT2 = np.sqrt(2)
SQRTPI = np.sqrt(np.pi)
IMAGE_MAX = 255.99999
class NoiseError(Exception):
def __init__(self, noise, thresh):
... | 0.837421 | 0.490785 |
import os
import pytest
import pyvista as pv
from ansys.dpf import core
from ansys.dpf.post import examples
# enable off_screen plotting to avoid test interruption
pv.OFF_SCREEN = True
# currently running dpf on docker. Used for testing on CI
running_docker = os.environ.get("DPF_DOCKER", False)
def resolve_test... | tests/conftest.py | import os
import pytest
import pyvista as pv
from ansys.dpf import core
from ansys.dpf.post import examples
# enable off_screen plotting to avoid test interruption
pv.OFF_SCREEN = True
# currently running dpf on docker. Used for testing on CI
running_docker = os.environ.get("DPF_DOCKER", False)
def resolve_test... | 0.561335 | 0.351784 |
import json
from datetime import datetime
from unittest.mock import Mock, patch
import graphene
import pytest
from django.utils.dateparse import parse_datetime
from django.utils.text import slugify
from graphql_relay import to_global_id
from prices import Money
from remote_works.graphql.core.enums import ReportingPer... | tests/api/test_skill.py | import json
from datetime import datetime
from unittest.mock import Mock, patch
import graphene
import pytest
from django.utils.dateparse import parse_datetime
from django.utils.text import slugify
from graphql_relay import to_global_id
from prices import Money
from remote_works.graphql.core.enums import ReportingPer... | 0.49585 | 0.360799 |
import datetime
import os
import unittest
import pymetacode.configuration
class TestConfiguration(unittest.TestCase):
def setUp(self):
self.configuration = pymetacode.configuration.Configuration()
self.filename = 'foo.yaml'
def tearDown(self):
if os.path.exists(self.filename):
... | tests/test_configuration.py | import datetime
import os
import unittest
import pymetacode.configuration
class TestConfiguration(unittest.TestCase):
def setUp(self):
self.configuration = pymetacode.configuration.Configuration()
self.filename = 'foo.yaml'
def tearDown(self):
if os.path.exists(self.filename):
... | 0.458349 | 0.439807 |
import weakref
import services
import sims4.gsi.archive
with sims4.reload.protected(globals()):
tracked_objects_dict = {}
deleted_objs = []
logger = sims4.log.Logger('GameplayArchiver')
MAX_DELETED_SIM_RECORDS = 10
def logged_gsi_object_deleted(obj):
deleted_id = tracked_objects_dict[obj]
del tracked_o... | S4/S4 Library/simulation/gsi_handlers/gameplay_archiver.py | import weakref
import services
import sims4.gsi.archive
with sims4.reload.protected(globals()):
tracked_objects_dict = {}
deleted_objs = []
logger = sims4.log.Logger('GameplayArchiver')
MAX_DELETED_SIM_RECORDS = 10
def logged_gsi_object_deleted(obj):
deleted_id = tracked_objects_dict[obj]
del tracked_o... | 0.223631 | 0.136091 |
#
# # 读入数据
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# In[2]:
path = 'ex2data1.txt'
exam1 = 'exam1'
exam2 = 'exam2'
admitted = 'admitted'
data = pd.read_csv(path, header=None, names=[exam1, exam2, admitted])
# data.head()
# # 可视化
# In[3]:
positive = data[data[admitted... | StudyNotesOfML/2. Logistic regression/Logistic regression.py |
#
# # 读入数据
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# In[2]:
path = 'ex2data1.txt'
exam1 = 'exam1'
exam2 = 'exam2'
admitted = 'admitted'
data = pd.read_csv(path, header=None, names=[exam1, exam2, admitted])
# data.head()
# # 可视化
# In[3]:
positive = data[data[admitted... | 0.227985 | 0.616186 |
import requests
from urllib.parse import quote
class ActionNetworkApi:
"""Python wrapper for Action Network API."""
def __init__(self, api_key, **kwargs):
"""Instantiate the API client and get config."""
self.headers = {"OSDI-API-Token": api_key}
self.refresh_config()
self.ba... | pyactionnetwork/api.py |
import requests
from urllib.parse import quote
class ActionNetworkApi:
"""Python wrapper for Action Network API."""
def __init__(self, api_key, **kwargs):
"""Instantiate the API client and get config."""
self.headers = {"OSDI-API-Token": api_key}
self.refresh_config()
self.ba... | 0.838779 | 0.134435 |
"""Test the OCP on Cloud Report serializers."""
from unittest import TestCase
from unittest.mock import Mock
from rest_framework import serializers
from api.report.all.openshift.serializers import OCPAllQueryParamSerializer
class OCPAllQueryParamSerializerTest(TestCase):
"""Tests for the handling query paramete... | koku/api/report/test/all/openshift/tests_serializers.py | """Test the OCP on Cloud Report serializers."""
from unittest import TestCase
from unittest.mock import Mock
from rest_framework import serializers
from api.report.all.openshift.serializers import OCPAllQueryParamSerializer
class OCPAllQueryParamSerializerTest(TestCase):
"""Tests for the handling query paramete... | 0.895571 | 0.489015 |
import base64
import binascii
import io
import tempfile
import flask
import google.cloud.storage as gcloud_storage
import google.cloud.exceptions as gcloud_exceptions
from werkzeug.contrib.cache import FileSystemCache
from .. import config, model, util
from .blueprint import coordinator_api
# Cache the worker blo... | apiserver/apiserver/coordinator/storage.py | import base64
import binascii
import io
import tempfile
import flask
import google.cloud.storage as gcloud_storage
import google.cloud.exceptions as gcloud_exceptions
from werkzeug.contrib.cache import FileSystemCache
from .. import config, model, util
from .blueprint import coordinator_api
# Cache the worker blo... | 0.499023 | 0.110327 |
import numpy as np
import cv2
from .colors import get_color
class BoundBox:
def __init__(self, xmin, ymin, xmax, ymax, c=None, classes=None):
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
self.c = c
self.classes = classes
self.label ... | utils/bbox.py |
import numpy as np
import cv2
from .colors import get_color
class BoundBox:
def __init__(self, xmin, ymin, xmax, ymax, c=None, classes=None):
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
self.c = c
self.classes = classes
self.label ... | 0.445288 | 0.27133 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from ast import literal_eval
import compas
import compas_rhino
from compas.utilities import flatten
from compas.utilities import geometric_key
from compas_rhino.geometry import RhinoPoint
from compas_rhino.g... | src/compas_tna/rhino/diagramhelper.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from ast import literal_eval
import compas
import compas_rhino
from compas.utilities import flatten
from compas.utilities import geometric_key
from compas_rhino.geometry import RhinoPoint
from compas_rhino.g... | 0.571288 | 0.119511 |
import abc
import os
import re
import numpy as np
from erhsh.utils.print_util import TblPrinter
class CheckpointLoader(object):
def __init__(self, checkpoint_path):
self.checkpoint_path = checkpoint_path
@abc.abstractmethod
def _load_checkpoint(self):
pass
def __list(self, filter_k... | erhsh/common/checkpoint.py | import abc
import os
import re
import numpy as np
from erhsh.utils.print_util import TblPrinter
class CheckpointLoader(object):
def __init__(self, checkpoint_path):
self.checkpoint_path = checkpoint_path
@abc.abstractmethod
def _load_checkpoint(self):
pass
def __list(self, filter_k... | 0.363195 | 0.094678 |
from collections import MutableMapping
import math
import random
class SkipList(MutableMapping):
__slots__ = '_head', '_tail', '_n', '_height'
#------------------------------- nested _Node class -------------------------------
class _Node:
__slots__ = '_key', '_value', '_next'
"""Lightwe... | Assignments/Assignment_Midterm/DS_Mid_201911189/skiplist.py | from collections import MutableMapping
import math
import random
class SkipList(MutableMapping):
__slots__ = '_head', '_tail', '_n', '_height'
#------------------------------- nested _Node class -------------------------------
class _Node:
__slots__ = '_key', '_value', '_next'
"""Lightwe... | 0.7586 | 0.143608 |
import os
import sys
import shutil
import platform
import subprocess
import secrets
import click
import jinja2
from . import __version__
src = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'skeleton')
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__)))... | flask_skeleton/core.py | import os
import sys
import shutil
import platform
import subprocess
import secrets
import click
import jinja2
from . import __version__
src = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'skeleton')
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__)))... | 0.249082 | 0.047426 |
from helpers.api_request import request_url
from helpers.api_token import get_token
from config.api import settings
token = get_token(settings.CREDENTIALS_ADM)
token_unprivileges = get_token(settings.CREDENTIALS_USER)
aws_data = settings.STACK_POST_AWS
aws_stack_name = settings.STACK_NAME_AWS
gcp_data = settings.STACK... | sld-api-backend/test/test_02_crud_stacks.py | from helpers.api_request import request_url
from helpers.api_token import get_token
from config.api import settings
token = get_token(settings.CREDENTIALS_ADM)
token_unprivileges = get_token(settings.CREDENTIALS_USER)
aws_data = settings.STACK_POST_AWS
aws_stack_name = settings.STACK_NAME_AWS
gcp_data = settings.STACK... | 0.461259 | 0.257616 |
from threading import Thread
from time import sleep
import WindowManager as WinMan
import MapManager as MapMan
import globals as global_vars
import curses
class InputListener(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
"""
periodically querys the keyboard keypr... | lib/InputListener.py | from threading import Thread
from time import sleep
import WindowManager as WinMan
import MapManager as MapMan
import globals as global_vars
import curses
class InputListener(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
"""
periodically querys the keyboard keypr... | 0.236604 | 0.104021 |
import gzip
import logging
from typing import Dict
import bioregistry
import click
import pandas as pd
from tqdm import tqdm
from .models import Alt, Reference, Resource, Synonym, Xref, create_all, drop_all, engine, session
from ...cli_utils import verbose_option
from ...resource_utils import ensure_alts, ensure_insp... | src/pyobo/database/sql/legacy_loader.py | import gzip
import logging
from typing import Dict
import bioregistry
import click
import pandas as pd
from tqdm import tqdm
from .models import Alt, Reference, Resource, Synonym, Xref, create_all, drop_all, engine, session
from ...cli_utils import verbose_option
from ...resource_utils import ensure_alts, ensure_insp... | 0.576542 | 0.077797 |
import numpy as np
import sys, os, re, music21
from optparse import OptionParser
from multiprocessing import Process
from collections import deque
from sqlalchemy import desc, asc
from db import Song, Track, Note, get_sessions
from ngram_helper import key_transpose_pitch
from exceptions import InvalidKeySignature
N... | src/artist_generator/ngram/train.py | import numpy as np
import sys, os, re, music21
from optparse import OptionParser
from multiprocessing import Process
from collections import deque
from sqlalchemy import desc, asc
from db import Song, Track, Note, get_sessions
from ngram_helper import key_transpose_pitch
from exceptions import InvalidKeySignature
N... | 0.486575 | 0.244262 |
from math import ceil
from copy import copy
import torch
import numpy as np
import skimage
from skimage import io
from skimage import color
from sklearn.decomposition import PCA
from sklearn.preprocessing import minmax_scale
class RunningAverage:
def __init__(self):
self.iter = 0
self.avg = 0.0
... | posetrack/util.py | from math import ceil
from copy import copy
import torch
import numpy as np
import skimage
from skimage import io
from skimage import color
from sklearn.decomposition import PCA
from sklearn.preprocessing import minmax_scale
class RunningAverage:
def __init__(self):
self.iter = 0
self.avg = 0.0
... | 0.820541 | 0.543711 |
model = {
u'yn ': 0,
u'dd ': 1,
u' yn': 2,
u' y ': 3,
u'ydd': 4,
u'eth': 5,
u'th ': 6,
u' i ': 7,
u'aet': 8,
u'd y': 9,
u'ch ': 10,
u'od ': 11,
u'ol ': 12,
u'edd': 13,
u' ga': 14,
u' gw': 15,
u"'r ": 16,
u'au ': 17,
u'ddi': 18,
u'ad ': 19,
u' cy': 20,
u' gy': 21,
u' ei': 22,
u' o ': 23,
u'iad':... | env/lib/python2.7/site-packages/guess_language/data/models/cy.py | model = {
u'yn ': 0,
u'dd ': 1,
u' yn': 2,
u' y ': 3,
u'ydd': 4,
u'eth': 5,
u'th ': 6,
u' i ': 7,
u'aet': 8,
u'd y': 9,
u'ch ': 10,
u'od ': 11,
u'ol ': 12,
u'edd': 13,
u' ga': 14,
u' gw': 15,
u"'r ": 16,
u'au ': 17,
u'ddi': 18,
u'ad ': 19,
u' cy': 20,
u' gy': 21,
u' ei': 22,
u' o ': 23,
u'iad':... | 0.36625 | 0.067117 |