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 |
|---|---|---|---|---|
import torch
from pytorchltr.datasets.list_sampler import ListSampler
from pytorchltr.datasets.list_sampler import UniformSampler
from pytorchltr.datasets.list_sampler import BalancedRelevanceSampler
from pytest import approx
def rng(seed=1608637542):
gen = torch.Generator()
gen.manual_seed(seed)
return ... | tests/datasets/test_list_sampler.py | import torch
from pytorchltr.datasets.list_sampler import ListSampler
from pytorchltr.datasets.list_sampler import UniformSampler
from pytorchltr.datasets.list_sampler import BalancedRelevanceSampler
from pytest import approx
def rng(seed=1608637542):
gen = torch.Generator()
gen.manual_seed(seed)
return ... | 0.710427 | 0.836154 |
import argparse
import getpass
import colorama as clr
import neo4j_queries
from neo4j_connection import FlightsConnection
exit = False
info_queries = """Available queries:
1.- Information about every airline and their country.
2.- Top 10 airlines that provide the biggest amount of flights.
3.- Flights from Madrid ... | simple_demo/scripts/main.py |
import argparse
import getpass
import colorama as clr
import neo4j_queries
from neo4j_connection import FlightsConnection
exit = False
info_queries = """Available queries:
1.- Information about every airline and their country.
2.- Top 10 airlines that provide the biggest amount of flights.
3.- Flights from Madrid ... | 0.439026 | 0.418994 |
import unittest
from passlocker import passlocker
import Pyperclip
class Testpasslockers(unittest.TestCase):
def setup(self):
"""
setup before running test
"""
self.new_passlocker = ("millywayne", "<PASSWORD>" "github" "<EMAIL>")
def test_init(self):
"""
clear list
... | passlocker__test.py | import unittest
from passlocker import passlocker
import Pyperclip
class Testpasslockers(unittest.TestCase):
def setup(self):
"""
setup before running test
"""
self.new_passlocker = ("millywayne", "<PASSWORD>" "github" "<EMAIL>")
def test_init(self):
"""
clear list
... | 0.44553 | 0.19475 |
import torch
from omegaconf import DictConfig
from torch import nn
from code2seq.model.modules import PathEncoder
class TypedPathEncoder(PathEncoder):
def __init__(
self,
config: DictConfig,
n_tokens: int,
token_pad_id: int,
n_nodes: int,
node_pad_id: int,
... | code2seq/model/modules/typed_path_encoder.py | import torch
from omegaconf import DictConfig
from torch import nn
from code2seq.model.modules import PathEncoder
class TypedPathEncoder(PathEncoder):
def __init__(
self,
config: DictConfig,
n_tokens: int,
token_pad_id: int,
n_nodes: int,
node_pad_id: int,
... | 0.932253 | 0.322199 |
import os
import numpy as np
import torch
import torch.nn as nn
from torch.nn import Module
import neural_renderer as nr
from pose.manopth.manopth.manolayer import ManoLayer
from .theta_regressor import ThetaRegressor
class EncEncoder(nn.Module):
def __init__(self, inp_ch, out_ch, name='enc'):
super(EncEn... | mano/net_mano.py | import os
import numpy as np
import torch
import torch.nn as nn
from torch.nn import Module
import neural_renderer as nr
from pose.manopth.manopth.manolayer import ManoLayer
from .theta_regressor import ThetaRegressor
class EncEncoder(nn.Module):
def __init__(self, inp_ch, out_ch, name='enc'):
super(EncEn... | 0.905331 | 0.400749 |
from wtforms import DateTimeField, Form, IntegerField, StringField
from wtforms.validators import DataRequired, Length, ValidationError
def valid_hours(form, field):
"""Ensures the minutes are in a 30-minute interval."""
if field.data.minute % 30 != 0:
raise ValidationError(
'Reservations ... | koob/forms.py | from wtforms import DateTimeField, Form, IntegerField, StringField
from wtforms.validators import DataRequired, Length, ValidationError
def valid_hours(form, field):
"""Ensures the minutes are in a 30-minute interval."""
if field.data.minute % 30 != 0:
raise ValidationError(
'Reservations ... | 0.719876 | 0.302211 |
import sys
import types
class Inspector:
"""
Inspect frames and produces snapshots with the state.
"""
def __init__(self):
"""
Initialize the inspector and the ordered id generators.
"""
self.ordered_id_count = 0
self.ordered_ids = {}
self.previous_orde... | tracers/python/tracer/inspector.py | import sys
import types
class Inspector:
"""
Inspect frames and produces snapshots with the state.
"""
def __init__(self):
"""
Initialize the inspector and the ordered id generators.
"""
self.ordered_id_count = 0
self.ordered_ids = {}
self.previous_orde... | 0.646349 | 0.542197 |
from ....lo.ui.dialogs.address_book_source_pilot import AddressBookSourcePilot as AddressBookSourcePilot
from ....lo.ui.dialogs.common_file_picker_element_ids import CommonFilePickerElementIds as CommonFilePickerElementIds
from ....lo.ui.dialogs.control_actions import ControlActions as ControlActions
from ....lo.ui.dia... | ooobuild/csslo/ui/dialogs/__init__.py | from ....lo.ui.dialogs.address_book_source_pilot import AddressBookSourcePilot as AddressBookSourcePilot
from ....lo.ui.dialogs.common_file_picker_element_ids import CommonFilePickerElementIds as CommonFilePickerElementIds
from ....lo.ui.dialogs.control_actions import ControlActions as ControlActions
from ....lo.ui.dia... | 0.294519 | 0.031889 |
import numpy
from ..baseclass import Dist
from .. import evaluation, approximation
class Arctan(Dist):
"""
Arc-Tangent.
Args:
dist (Dist): Distribution to perform transformation on.
Example:
>>> distribution = chaospy.Arctan(chaospy.Uniform(-0.5, 0.5))
>>> print(distribution... | chaospy/distributions/operators/arctan.py | import numpy
from ..baseclass import Dist
from .. import evaluation, approximation
class Arctan(Dist):
"""
Arc-Tangent.
Args:
dist (Dist): Distribution to perform transformation on.
Example:
>>> distribution = chaospy.Arctan(chaospy.Uniform(-0.5, 0.5))
>>> print(distribution... | 0.805058 | 0.459319 |
from typing import List
from adventofcode.util.helpers import solution_timer
from adventofcode.util.input_helpers import get_input_for_day
def is_abba_sequence(sequence):
for i in range(len(sequence) - 3):
if sequence[i] == sequence[i + 3] and sequence[i + 1] == sequence[i + 2] and sequence[i] != sequenc... | src/adventofcode/year_2016/day_07_2016.py | from typing import List
from adventofcode.util.helpers import solution_timer
from adventofcode.util.input_helpers import get_input_for_day
def is_abba_sequence(sequence):
for i in range(len(sequence) - 3):
if sequence[i] == sequence[i + 3] and sequence[i + 1] == sequence[i + 2] and sequence[i] != sequenc... | 0.471467 | 0.396535 |
from abc import ABC, abstractmethod
from flask import render_template
import re
import bleach
class Element(ABC):
template_options = {}
def __init__(self, key, text):
self.key = key
self.text = text
super().__init__()
@property
@abstractmethod
def html_template(self):
... | hraew/parser.py | from abc import ABC, abstractmethod
from flask import render_template
import re
import bleach
class Element(ABC):
template_options = {}
def __init__(self, key, text):
self.key = key
self.text = text
super().__init__()
@property
@abstractmethod
def html_template(self):
... | 0.693161 | 0.214527 |
from django import http
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.conf import settings
from django.http import Http404
from what_apps.meta.alerts import local_red_alert
class ServerErrorMiddleware(object):
def get_most_recent_line_in_traceback_from_what_co... | what_apps/meta/errors.py | from django import http
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.conf import settings
from django.http import Http404
from what_apps.meta.alerts import local_red_alert
class ServerErrorMiddleware(object):
def get_most_recent_line_in_traceback_from_what_co... | 0.263789 | 0.046812 |
import time
import tensorflow as tf
import kaggle_mnist_input as loader
import os
import csv
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('training_epoch', 30, "training epoch")
tf.app.flags.DEFINE_integer('batch_size', 128, "batch size")
tf.app.flags.DEFINE_integer('validation_interval', 100, "validation i... | simple_kaggle_mnist_alexnet.py | import time
import tensorflow as tf
import kaggle_mnist_input as loader
import os
import csv
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('training_epoch', 30, "training epoch")
tf.app.flags.DEFINE_integer('batch_size', 128, "batch size")
tf.app.flags.DEFINE_integer('validation_interval', 100, "validation i... | 0.557845 | 0.315011 |
from torch import nn
""" A classifier model for Fashion MNIST Image
We creat this module by sub classing nn.Module, a Module can contain other modules
The common use modules:
- nn.Flatten: The nn.Flatten layer is commonly used to convert multi-dimension input tensor to a one-dimension tensor.
As a res... | basics/source/FashionMNISTImageClassifier.py | from torch import nn
""" A classifier model for Fashion MNIST Image
We creat this module by sub classing nn.Module, a Module can contain other modules
The common use modules:
- nn.Flatten: The nn.Flatten layer is commonly used to convert multi-dimension input tensor to a one-dimension tensor.
As a res... | 0.967869 | 0.963678 |
import logging
from warnings import warn
from typing import List, Dict, Optional
from ._config import Config
from ._entity import BaseEntity, Entity, _ORMType
from ._routing import BaseRouting, RoutingMixin
from ._authentication import BaseAuthentication, Authentication
from .oauth2.google import Google
from .oauth2._... | flask_jwt_router/_jwt_routes.py | import logging
from warnings import warn
from typing import List, Dict, Optional
from ._config import Config
from ._entity import BaseEntity, Entity, _ORMType
from ._routing import BaseRouting, RoutingMixin
from ._authentication import BaseAuthentication, Authentication
from .oauth2.google import Google
from .oauth2._... | 0.638159 | 0.088229 |
import numpy as np
def animate_with_periodic_gp(d, num_frames, base_measure_sample=None, endpoint=False):
"""Animate samples from a standard Normal distribution by drawing samples from a
periodic Gaussian process.
Parameters
----------
d :
Dimension of the underlying multivariate Normal ... | src/probnumeval/visual/_animate_samples.py |
import numpy as np
def animate_with_periodic_gp(d, num_frames, base_measure_sample=None, endpoint=False):
"""Animate samples from a standard Normal distribution by drawing samples from a
periodic Gaussian process.
Parameters
----------
d :
Dimension of the underlying multivariate Normal ... | 0.95773 | 0.78785 |
from calamities import (
TextView,
SpacerView,
MultiSingleChoiceInputView,
)
from ..pattern import FilePatternStep, FilePatternSummaryStep
from ...model import (
PhaseFmapFileSchema,
PhaseDiffFmapFileSchema,
EPIFmapFileSchema,
BaseFmapFileSchema,
BoldFileSchema,
)
from ..feature import... | halfpipe/ui/file/fmap.py |
from calamities import (
TextView,
SpacerView,
MultiSingleChoiceInputView,
)
from ..pattern import FilePatternStep, FilePatternSummaryStep
from ...model import (
PhaseFmapFileSchema,
PhaseDiffFmapFileSchema,
EPIFmapFileSchema,
BaseFmapFileSchema,
BoldFileSchema,
)
from ..feature import... | 0.55254 | 0.206714 |
import numpy as np
from scipy.signal import resample
from scipy.fftpack import fft,ifft,fftshift,fftfreq
class Convolution():
def __init__(self):
print ('Convolution module loaded')
def generate_wavelet_fourier(len_wavelet,
f_start,
... | electroPyy/core/Convolution.py | import numpy as np
from scipy.signal import resample
from scipy.fftpack import fft,ifft,fftshift,fftfreq
class Convolution():
def __init__(self):
print ('Convolution module loaded')
def generate_wavelet_fourier(len_wavelet,
f_start,
... | 0.597843 | 0.457924 |
from django.db import models
from users.models import CustomUser
# Create your models here.
class Friend(models.Model):
# Remove nullability later.
user_profile = models.ForeignKey(CustomUser, related_name="owner", on_delete=models.CASCADE, null=True)
friends = models.ManyToManyField(CustomUser)
pendin... | friends/models.py | from django.db import models
from users.models import CustomUser
# Create your models here.
class Friend(models.Model):
# Remove nullability later.
user_profile = models.ForeignKey(CustomUser, related_name="owner", on_delete=models.CASCADE, null=True)
friends = models.ManyToManyField(CustomUser)
pendin... | 0.546254 | 0.137677 |
import click
from pathlib import Path
import shutil
import json
import re
from .utils import render_template
@click.command()
@click.option('--debug/--no-debug', default=False)
@click.pass_context
def init(ctx, debug):
"""Initiate sit project on current folder."""
DEBUG = ctx.obj['DEBUG'] or debug
MODULE... | sitmango/scripts/init.py | import click
from pathlib import Path
import shutil
import json
import re
from .utils import render_template
@click.command()
@click.option('--debug/--no-debug', default=False)
@click.pass_context
def init(ctx, debug):
"""Initiate sit project on current folder."""
DEBUG = ctx.obj['DEBUG'] or debug
MODULE... | 0.26827 | 0.05634 |
from unittest.mock import create_autospec
import pytest
import smarttub
pytestmark = pytest.mark.asyncio
@pytest.fixture(name='mock_account')
def mock_account(mock_api):
account = create_autospec(smarttub.Account, instance=True)
return account
@pytest.fixture(name='spa')
def spa(mock_api, mock_account):
... | tests/test_spa.py | from unittest.mock import create_autospec
import pytest
import smarttub
pytestmark = pytest.mark.asyncio
@pytest.fixture(name='mock_account')
def mock_account(mock_api):
account = create_autospec(smarttub.Account, instance=True)
return account
@pytest.fixture(name='spa')
def spa(mock_api, mock_account):
... | 0.653016 | 0.614134 |
data = (
'ga', # 0x00
'gag', # 0x01
'gagg', # 0x02
'gags', # 0x03
'gan', # 0x04
'ganj', # 0x05
'ganh', # 0x06
'gad', # 0x07
'gal', # 0x08
'galg', # 0x09
'galm', # 0x0a
'galb', # 0x0b
'gals', # 0x0c
'galt', # 0x0d
'galp', # 0x0e
'galh', # 0x0f
'gam', # 0x10
'gab', # ... | env/lib/python3.8/site-packages/unidecode/x0ac.py | data = (
'ga', # 0x00
'gag', # 0x01
'gagg', # 0x02
'gags', # 0x03
'gan', # 0x04
'ganj', # 0x05
'ganh', # 0x06
'gad', # 0x07
'gal', # 0x08
'galg', # 0x09
'galm', # 0x0a
'galb', # 0x0b
'gals', # 0x0c
'galt', # 0x0d
'galp', # 0x0e
'galh', # 0x0f
'gam', # 0x10
'gab', # ... | 0.05344 | 0.23645 |
from posts.models import Post
from rest_framework import status
from rest_framework.test import APITestCase
from users.models import User
class TestViews(APITestCase):
def setUp(self):
self.user = User.objects.create_user(
username='test', email='<EMAIL>', password='<PASSWORD>')
self.... | comments/tests/test_views.py | from posts.models import Post
from rest_framework import status
from rest_framework.test import APITestCase
from users.models import User
class TestViews(APITestCase):
def setUp(self):
self.user = User.objects.create_user(
username='test', email='<EMAIL>', password='<PASSWORD>')
self.... | 0.656768 | 0.258888 |
import json
import random
import os
input_file = '/Users/shiquan/PycharmProjects/Multimodal-Knowledge-Base/data/1_multiwoz/restaurant_db.json'
output_file = '/Users/shiquan/PycharmProjects/Multimodal-Knowledge-Base/data/1_multiwoz/restaurant_db_transformed.json'
fout = open(output_file, 'w')
rest_dict = {"data": []}
... | s2s-ft/multimodalKB/scripts/3_transform_multiwoz_kb_formats/0_transform.py | import json
import random
import os
input_file = '/Users/shiquan/PycharmProjects/Multimodal-Knowledge-Base/data/1_multiwoz/restaurant_db.json'
output_file = '/Users/shiquan/PycharmProjects/Multimodal-Knowledge-Base/data/1_multiwoz/restaurant_db_transformed.json'
fout = open(output_file, 'w')
rest_dict = {"data": []}
... | 0.137938 | 0.123842 |
# System imports
from enum import Enum
# Local source tree imports
from pyof.foundation.base import GenericMessage, GenericStruct, IntEnum
from pyof.foundation.basic_types import (
BinaryData, FixedTypeList, Pad, UBInt8, UBInt16, UBInt32, UBInt64)
from pyof.v0x05.common.flow_match import Match
from pyof.v0x05.com... | pyof/v0x05/controller2switch/multipart_request.py |
# System imports
from enum import Enum
# Local source tree imports
from pyof.foundation.base import GenericMessage, GenericStruct, IntEnum
from pyof.foundation.basic_types import (
BinaryData, FixedTypeList, Pad, UBInt8, UBInt16, UBInt32, UBInt64)
from pyof.v0x05.common.flow_match import Match
from pyof.v0x05.com... | 0.837985 | 0.239127 |
import mimetypes
import random
import string
import requests
import re
from .uploader import FileStreamUploader
from .settings import providers
class TransferSh(FileStreamUploader):
boundary: str
def __init__(self, *args, **kwargs):
self.url = providers['transfer.sh']['url']
super(TransferS... | pytransfer/services.py | import mimetypes
import random
import string
import requests
import re
from .uploader import FileStreamUploader
from .settings import providers
class TransferSh(FileStreamUploader):
boundary: str
def __init__(self, *args, **kwargs):
self.url = providers['transfer.sh']['url']
super(TransferS... | 0.366023 | 0.06357 |
import os, time, sys, datetime
from random import randint
from huepy import *
__version__ = "1.3.6"
def cc_gen(bin):
cc = ""
if len(bin) != 16:
while len(bin) != 16:
bin += 'x'
else:
pass
if len(bin) == 16:
for x in range(15):
if bin[x] in ("0", "... | tools/azathot/cc_gen.py | import os, time, sys, datetime
from random import randint
from huepy import *
__version__ = "1.3.6"
def cc_gen(bin):
cc = ""
if len(bin) != 16:
while len(bin) != 16:
bin += 'x'
else:
pass
if len(bin) == 16:
for x in range(15):
if bin[x] in ("0", "... | 0.061883 | 0.271427 |
import os
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import logging
_question_prompt = '\nQ: '
_answer_prompt = '\nA: '
_path = os.path.dirname(__file__)
_forbidden_words = set([item.strip().lower()
for item in open(os.path.join(_path, '../data/bad-words.txt... | src/qa.py | import os
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import logging
_question_prompt = '\nQ: '
_answer_prompt = '\nA: '
_path = os.path.dirname(__file__)
_forbidden_words = set([item.strip().lower()
for item in open(os.path.join(_path, '../data/bad-words.txt... | 0.294722 | 0.176352 |
from measurements import Measurement
from units.time import Second
from units.prefixes.large import Kilo
from units.prefixes.small import Milli
seconds = Measurement(1.2, Second())
print(f"seconds: {seconds}")
milliseconds = seconds.convertTo(Milli())
print(f"{seconds} = {milliseconds}")
seconds = milliseconds.inBas... | testing.py | from measurements import Measurement
from units.time import Second
from units.prefixes.large import Kilo
from units.prefixes.small import Milli
seconds = Measurement(1.2, Second())
print(f"seconds: {seconds}")
milliseconds = seconds.convertTo(Milli())
print(f"{seconds} = {milliseconds}")
seconds = milliseconds.inBas... | 0.798187 | 0.638469 |
import tkinter as tk
from tkinter import font
from tkinter import messagebox
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
from ttkbootstrap import Style
class GUI(tk.Tk):
def __init__(self, app) -> None:
super().__init__("Antimonium")
self.app = app
style = Sty... | modules/gui.py | import tkinter as tk
from tkinter import font
from tkinter import messagebox
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
from ttkbootstrap import Style
class GUI(tk.Tk):
def __init__(self, app) -> None:
super().__init__("Antimonium")
self.app = app
style = Sty... | 0.4231 | 0.057361 |
from collections import namedtuple
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas
import pickle
DEFAULT_INPUT_FILENAME = 'images/summary.csv'
class QuestionAndAbilityResult(object):
'''Draw reesults of the item response theory script'''
def __init__(self, argv):
... | scripts/stock_price/item_response_theory_result.py | from collections import namedtuple
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas
import pickle
DEFAULT_INPUT_FILENAME = 'images/summary.csv'
class QuestionAndAbilityResult(object):
'''Draw reesults of the item response theory script'''
def __init__(self, argv):
... | 0.333395 | 0.164349 |
import os
from flask import Flask, render_template, request, Response
import flask_assets as assets
from dictionary import Dictionary
from word import Word
from exceptions import LexicallyWebException
app = Flask(__name__)
app.config.from_object('config')
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWE... | lexically/app.py |
import os
from flask import Flask, render_template, request, Response
import flask_assets as assets
from dictionary import Dictionary
from word import Word
from exceptions import LexicallyWebException
app = Flask(__name__)
app.config.from_object('config')
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWE... | 0.301465 | 0.082734 |
import numpy as np
"""
This file contains constants specifically in baxter domain.
This file is refferenced in:
baxter_predicates
baxter_sampling
test_baxter_predicates
"""
"""
Following Constants are used in baxter_predicates
"""
# Baxter dimension constant
BASE_DIM = 3
JOINT_DIM = 6
ROBOT_ATTR_DIM = 8
JO... | opentamp/src/core/util_classes/hsr_constants.py | import numpy as np
"""
This file contains constants specifically in baxter domain.
This file is refferenced in:
baxter_predicates
baxter_sampling
test_baxter_predicates
"""
"""
Following Constants are used in baxter_predicates
"""
# Baxter dimension constant
BASE_DIM = 3
JOINT_DIM = 6
ROBOT_ATTR_DIM = 8
JO... | 0.47025 | 0.458894 |
# ================== i18n.py =====================
# It localizes website elements.
# Hook type: pre_build (modifies config file)
# Configuration:
# Create a i18n.yaml file in your project root. Look at i18n.yaml and i18n.example.yaml
# to get a feel for the structure.
# Add the correct id to every element (via rea... | template/template-tools/i18n/i18n.py |
# ================== i18n.py =====================
# It localizes website elements.
# Hook type: pre_build (modifies config file)
# Configuration:
# Create a i18n.yaml file in your project root. Look at i18n.yaml and i18n.example.yaml
# to get a feel for the structure.
# Add the correct id to every element (via rea... | 0.405449 | 0.1526 |
import requests
import os
import urllib
import re
os.chdir("downpic")
path="urls.txt"
"""
<span class="article-nav-prev">上一篇<br><a href="https://www.3sgif.com/47814.html" rel="prev">GIF出处:美女gif出处不看后悔 口技很好!</a></span>
<span class="article-nav-next">下一篇<br><a href="https://www.3sgif.com/47839.html" rel="next... | use_requestes.py | import requests
import os
import urllib
import re
os.chdir("downpic")
path="urls.txt"
"""
<span class="article-nav-prev">上一篇<br><a href="https://www.3sgif.com/47814.html" rel="prev">GIF出处:美女gif出处不看后悔 口技很好!</a></span>
<span class="article-nav-next">下一篇<br><a href="https://www.3sgif.com/47839.html" rel="next... | 0.045384 | 0.208965 |
import os
import pprint
import subprocess
import sys
from optparse import make_option
from urllib import quote_plus
from urlparse import urljoin
import dateutil.parser
import requests
from django.conf import settings
from django.core.management import BaseCommand, CommandError
from six import python_2_unicode_compatib... | hard-gists/2fe1c16a7cc27ef01c1f/snippet.py | import os
import pprint
import subprocess
import sys
from optparse import make_option
from urllib import quote_plus
from urlparse import urljoin
import dateutil.parser
import requests
from django.conf import settings
from django.core.management import BaseCommand, CommandError
from six import python_2_unicode_compatib... | 0.439026 | 0.082328 |
#All the changes from the original code were made by Tom Sander, but added by JC Layoun in the repos.
## convert the text/attention list to latex code, which will further generates the text heatmap based on attention weights.
import numpy as np
latex_special_token = ["!@#$%^&*()"]
def generate(text_list, ... | plot_annotation_matrix.py |
#All the changes from the original code were made by Tom Sander, but added by JC Layoun in the repos.
## convert the text/attention list to latex code, which will further generates the text heatmap based on attention weights.
import numpy as np
latex_special_token = ["!@#$%^&*()"]
def generate(text_list, ... | 0.194904 | 0.249945 |
from http import HTTPStatus
from flask_login import current_user
from flask_restplus import Resource, reqparse, abort
from app.api.models import ProfilePaginationModel
from app.api.namespaces import profiles
from database.models import User, FavoriteUser, Pagination
@profiles.route('')
class ProfileList(Resource):
... | src/backend/app/api/public/profiles/profiles.py | from http import HTTPStatus
from flask_login import current_user
from flask_restplus import Resource, reqparse, abort
from app.api.models import ProfilePaginationModel
from app.api.namespaces import profiles
from database.models import User, FavoriteUser, Pagination
@profiles.route('')
class ProfileList(Resource):
... | 0.638835 | 0.06256 |
from multiprocessing import Process
import sys
import getpass
import re
import mechanicalsoup
import os
import pandas as pd
import auto_iMutant2
import auto_ponp2
import auto_muPro
import auto_mutPred2
import auto_phdSNP
import auto_mutAssessor
import auto_provean
import auto_panther
import auto_polyphen2
import auto_... | automate.py |
from multiprocessing import Process
import sys
import getpass
import re
import mechanicalsoup
import os
import pandas as pd
import auto_iMutant2
import auto_ponp2
import auto_muPro
import auto_mutPred2
import auto_phdSNP
import auto_mutAssessor
import auto_provean
import auto_panther
import auto_polyphen2
import auto_... | 0.121295 | 0.147801 |
from unittest.mock import MagicMock
from vdk.api.plugin.plugin_registry import IPluginRegistry
from vdk.internal.builtin_plugins import builtin_hook_impl
from vdk.internal.core.config import ConfigurationBuilder
from vdk.internal.core.context import CoreContext
from vdk.internal.core.statestore import CommonStoreKeys
... | projects/vdk-core/tests/vdk/internal/builtin_plugins/test_builtin_hook_impl.py | from unittest.mock import MagicMock
from vdk.api.plugin.plugin_registry import IPluginRegistry
from vdk.internal.builtin_plugins import builtin_hook_impl
from vdk.internal.core.config import ConfigurationBuilder
from vdk.internal.core.context import CoreContext
from vdk.internal.core.statestore import CommonStoreKeys
... | 0.646906 | 0.225342 |
import pytest
from waterbutler.providers.owncloud.metadata import OwnCloudFileRevisionMetadata
from tests.providers.owncloud.fixtures import (
file_metadata_object,
file_metadata_object_less_info,
folder_metadata_object,
folder_metadata_object_less_info,
revision_metadata_object
)
class TestFil... | tests/providers/owncloud/test_metadata.py | import pytest
from waterbutler.providers.owncloud.metadata import OwnCloudFileRevisionMetadata
from tests.providers.owncloud.fixtures import (
file_metadata_object,
file_metadata_object_less_info,
folder_metadata_object,
folder_metadata_object_less_info,
revision_metadata_object
)
class TestFil... | 0.314471 | 0.205904 |
from imports import *
from rescale_numeric_feature import *
"""
This class calculates feature importance
Input:
"""
class calculate_shap():
def __init__(self):
super(calculate_shap, self).__init__()
self.param = None
def xgboost_shap(self, model, X):
# explain the model's predict... | lib/calculate_shap.py | from imports import *
from rescale_numeric_feature import *
"""
This class calculates feature importance
Input:
"""
class calculate_shap():
def __init__(self):
super(calculate_shap, self).__init__()
self.param = None
def xgboost_shap(self, model, X):
# explain the model's predict... | 0.735642 | 0.60092 |
import json, os
from romUtils import GAME_FILE_PATH
from data.moveData import move_list
from data.typeData import type_map
from generateUtils import *
with open(GAME_FILE_PATH, 'rb') as game_file:
game_file.seek(0x3679A0)
move_json_array = []
for move in move_list:
move_json = {}
move_json['name'] = mo... | generateMoveJson.py | import json, os
from romUtils import GAME_FILE_PATH
from data.moveData import move_list
from data.typeData import type_map
from generateUtils import *
with open(GAME_FILE_PATH, 'rb') as game_file:
game_file.seek(0x3679A0)
move_json_array = []
for move in move_list:
move_json = {}
move_json['name'] = mo... | 0.245175 | 0.119588 |
# Autor: <NAME>
# Datum: Tue Sep 14 18:01:02 2021
# Python 3.8.8
# Ubuntu 20.04.1
import logging
from typing import Any
import pandas as pd
from sklearn.dummy import DummyClassifier
from sklearn.metrics import f1_score
from sklearn.svm import SVC
logger = logging.getLogger(__name__)
def compute_micro_f1(y_true: A... | classify.py |
# Autor: <NAME>
# Datum: Tue Sep 14 18:01:02 2021
# Python 3.8.8
# Ubuntu 20.04.1
import logging
from typing import Any
import pandas as pd
from sklearn.dummy import DummyClassifier
from sklearn.metrics import f1_score
from sklearn.svm import SVC
logger = logging.getLogger(__name__)
def compute_micro_f1(y_true: A... | 0.879845 | 0.605362 |
import dace
from copy import deepcopy as dcpy
from dace import data, symbolic, dtypes, subsets
from dace.graph import edges, nodes, nxutil
from dace.transformation import pattern_matching
from math import ceil
import sympy
import networkx as nx
class MapToForLoop(pattern_matching.Transformation):
""" Implements t... | dace/transformation/dataflow/map_for_loop.py | import dace
from copy import deepcopy as dcpy
from dace import data, symbolic, dtypes, subsets
from dace.graph import edges, nodes, nxutil
from dace.transformation import pattern_matching
from math import ceil
import sympy
import networkx as nx
class MapToForLoop(pattern_matching.Transformation):
""" Implements t... | 0.586404 | 0.408985 |
import numpy
import os
from PIL import Image, ImageOps
import random
import tensorflow as tf
class DataSet(object):
def __init__(self, images, labels, dtype=tf.float32):
"""
Construct a DataSet.
`dtype` can be either `uint8` to leave the input as `[0, 255]`,
or `float32` to rescal... | datasets.py | import numpy
import os
from PIL import Image, ImageOps
import random
import tensorflow as tf
class DataSet(object):
def __init__(self, images, labels, dtype=tf.float32):
"""
Construct a DataSet.
`dtype` can be either `uint8` to leave the input as `[0, 255]`,
or `float32` to rescal... | 0.846038 | 0.660515 |
import logging
import os.path
import pickle
import numpy as np
import scipy.constants
import scipy.signal
from pyrex.internal_functions import (normalize, complex_bilinear_interp,
complex_interp)
from pyrex.signals import Signal, FunctionSignal
from pyrex.antenna import Antenna
fro... | pyrex/custom/ara/antenna.py | import logging
import os.path
import pickle
import numpy as np
import scipy.constants
import scipy.signal
from pyrex.internal_functions import (normalize, complex_bilinear_interp,
complex_interp)
from pyrex.signals import Signal, FunctionSignal
from pyrex.antenna import Antenna
fro... | 0.857709 | 0.527803 |
import pathlib
import random
import argparse
import json
import shutil
from typing import List, Callable
import yaml
import numpy as np
import cv2
from gym_duckietown.envs import SimpleSimEnv
import src.graphics
class Transform:
def __init__(self):
self.transforms = []
def add_transform(self, tran... | scripts/generate_dataset.py | import pathlib
import random
import argparse
import json
import shutil
from typing import List, Callable
import yaml
import numpy as np
import cv2
from gym_duckietown.envs import SimpleSimEnv
import src.graphics
class Transform:
def __init__(self):
self.transforms = []
def add_transform(self, tran... | 0.551574 | 0.313643 |
from abc import ABC, abstractmethod
import textwrap
from typing import Union, List, Dict
from pydantic import BaseModel
from nmea.nmea_utils import convert_bits_to_int, convert_int_to_bits, get_char_of_ascii_code, convert_decimal_to_ascii_code, \
convert_ascii_char_to_ascii6_code, add_padding, add_padding_0_bits,... | nmea/nmea_msg.py | from abc import ABC, abstractmethod
import textwrap
from typing import Union, List, Dict
from pydantic import BaseModel
from nmea.nmea_utils import convert_bits_to_int, convert_int_to_bits, get_char_of_ascii_code, convert_decimal_to_ascii_code, \
convert_ascii_char_to_ascii6_code, add_padding, add_padding_0_bits,... | 0.882479 | 0.397295 |
import boto3
import ban_handler
import cgf_lambda_settings
import cgf_service_client
import errors
import identity_validator
import service
UNKNOWN_PLAYER_ERROR_MESSAGE = "User '{}' is not registered with the PlayerAccount Gem or has not sent data to the Leaderboards Gem"
@service.api
def post(request, user=None):... | dev/Gems/CloudGemLeaderboard/AWS/lambda-code/ServiceLambda/api/player_ban.py |
import boto3
import ban_handler
import cgf_lambda_settings
import cgf_service_client
import errors
import identity_validator
import service
UNKNOWN_PLAYER_ERROR_MESSAGE = "User '{}' is not registered with the PlayerAccount Gem or has not sent data to the Leaderboards Gem"
@service.api
def post(request, user=None):... | 0.425725 | 0.130037 |
import pwd
import re
import sys
from subprocess import check_output, CalledProcessError
users = [user for user in pwd.getpwall() if 1000 <= user.pw_uid < 2000]
try:
lxc_cmd = ["lxc", "ls", "volatile.last_state.power=RUNNING", "-c", "n", "--format", "csv"]
lxc_running = check_output(lxc_cmd, universal_newlin... | cpu_usage_per_user.py |
import pwd
import re
import sys
from subprocess import check_output, CalledProcessError
users = [user for user in pwd.getpwall() if 1000 <= user.pw_uid < 2000]
try:
lxc_cmd = ["lxc", "ls", "volatile.last_state.power=RUNNING", "-c", "n", "--format", "csv"]
lxc_running = check_output(lxc_cmd, universal_newlin... | 0.12932 | 0.110112 |
from linebot.models import TextMessage, VideoMessage, ImageMessage, TextSendMessage, ButtonsTemplate, PostbackTemplateAction, TemplateSendMessage, CarouselTemplate, CarouselColumn
from marketchat.util.beacon import make_beacon
from marketchat.util.line_bot import bot_api
from marketchat.util.router import Router, overl... | marketchat/handle/payment.py | from linebot.models import TextMessage, VideoMessage, ImageMessage, TextSendMessage, ButtonsTemplate, PostbackTemplateAction, TemplateSendMessage, CarouselTemplate, CarouselColumn
from marketchat.util.beacon import make_beacon
from marketchat.util.line_bot import bot_api
from marketchat.util.router import Router, overl... | 0.340485 | 0.117496 |
import os
import numpy as np
from collections import OrderedDict
import SimpleITK as sitk
import shutil
from batchgenerators.utilities.file_and_folder_operations import *
from nnunet.paths import nnUNet_raw_data
def get_identifier(img_path):
group_id = os.path.split(os.path.split(img_path)[0])[1]
id = os.path... | docker/third-party/nnUNet/nnunet/dataset_conversion/Task111_FetalBrain2d.py | import os
import numpy as np
from collections import OrderedDict
import SimpleITK as sitk
import shutil
from batchgenerators.utilities.file_and_folder_operations import *
from nnunet.paths import nnUNet_raw_data
def get_identifier(img_path):
group_id = os.path.split(os.path.split(img_path)[0])[1]
id = os.path... | 0.338514 | 0.187821 |
# Author: <NAME>, 2017
'''
Formatter for the brat stand-off format.
'''
import re
import logging
import itertools as it
from collections import defaultdict
from .export import StreamFormatter
class BratFormatter:
'''
Distributor for delegating to the actual formatters.
'''
def __init__(self, con... | main/oger/doc/brat.py |
# Author: <NAME>, 2017
'''
Formatter for the brat stand-off format.
'''
import re
import logging
import itertools as it
from collections import defaultdict
from .export import StreamFormatter
class BratFormatter:
'''
Distributor for delegating to the actual formatters.
'''
def __init__(self, con... | 0.668339 | 0.214136 |
import json
from typing import List, Optional
import aiokatcp
from katpoint import Antenna
from kattelmod.clock import get_clock, real_timeout
from kattelmod.component import (KATCPComponent, TelstateUpdatingComponent,
TargetObserverMixin)
from kattelmod.session import CaptureState
f... | kattelmod/systems/mkat/sdp.py |
import json
from typing import List, Optional
import aiokatcp
from katpoint import Antenna
from kattelmod.clock import get_clock, real_timeout
from kattelmod.component import (KATCPComponent, TelstateUpdatingComponent,
TargetObserverMixin)
from kattelmod.session import CaptureState
f... | 0.846117 | 0.18924 |
from subprocess import run
import time as t
import matplotlib.pyplot as plt
import sys
import random as rnd
def all_identical(data):
if data == []:
return True
for d in data:
if d != data[0]:
return False
return True
def measure_instance(cmds, *args):
measures = []
out... | benches/bench.py |
from subprocess import run
import time as t
import matplotlib.pyplot as plt
import sys
import random as rnd
def all_identical(data):
if data == []:
return True
for d in data:
if d != data[0]:
return False
return True
def measure_instance(cmds, *args):
measures = []
out... | 0.211417 | 0.404625 |
from web3 import Web3
import time
from sqlalchemy import text
from datetime import datetime
from classes import start_engine
from functions import get_conf
# Get Parameters
conf = get_conf()
infura_key = conf["infura_key"]
db_driver = conf["db.driver"] # snowflake or postgresql
db_host = conf["db.host"]
db_user = co... | eth-blocks.py | from web3 import Web3
import time
from sqlalchemy import text
from datetime import datetime
from classes import start_engine
from functions import get_conf
# Get Parameters
conf = get_conf()
infura_key = conf["infura_key"]
db_driver = conf["db.driver"] # snowflake or postgresql
db_host = conf["db.host"]
db_user = co... | 0.471467 | 0.139426 |
# /*********************************************************************
# *
# * Gmsh tutorial 14
# *
# * Homology and cohomology computation
# *
# *********************************************************************/
# Homology computation in Gmsh finds representative chains of (relative)
# (co)homology spa... | gmsh-4.2.2/demos/api/t14.py |
# /*********************************************************************
# *
# * Gmsh tutorial 14
# *
# * Homology and cohomology computation
# *
# *********************************************************************/
# Homology computation in Gmsh finds representative chains of (relative)
# (co)homology spa... | 0.488283 | 0.554651 |
import matplotlib.pyplot as plt
import numpy as np
from trompy import weib_davis
def licklengthFig(ax, data, contents = '', color='grey'):
if len(data['longlicks']) > 0:
longlicklabel = str(len(data['longlicks'])) + ' long licks,\n' +'max = ' + '%.2f' % max(data['longlicks']) + ' s.'
... | trompy/lick_figs.py | import matplotlib.pyplot as plt
import numpy as np
from trompy import weib_davis
def licklengthFig(ax, data, contents = '', color='grey'):
if len(data['longlicks']) > 0:
longlicklabel = str(len(data['longlicks'])) + ' long licks,\n' +'max = ' + '%.2f' % max(data['longlicks']) + ' s.'
... | 0.541651 | 0.375936 |
import pandas as pd
import numpy as np
import pickle
import sys
sys.path.append('/home/emma/summary_evaluation/score_evaluators')
from prediction_data import PredictionData
class VideosumDataset(PredictionData):
def __init__(self, name, num_classes, local=True):
self.repr_name = name
self.name = n... | play_summary/videosum_dataset.py | import pandas as pd
import numpy as np
import pickle
import sys
sys.path.append('/home/emma/summary_evaluation/score_evaluators')
from prediction_data import PredictionData
class VideosumDataset(PredictionData):
def __init__(self, name, num_classes, local=True):
self.repr_name = name
self.name = n... | 0.264263 | 0.251137 |
from flask import current_app, request, jsonify, url_for
from flask_login import current_user
from .. import socketio
from ..models import File, User
from .. import db
from flask_socketio import send, emit
@socketio.on('connect', namespace='/events')
def events_connect():
"""
This function is called when a n... | app/controller/events.py | from flask import current_app, request, jsonify, url_for
from flask_login import current_user
from .. import socketio
from ..models import File, User
from .. import db
from flask_socketio import send, emit
@socketio.on('connect', namespace='/events')
def events_connect():
"""
This function is called when a n... | 0.351422 | 0.043285 |
import logging
import operator
import os
from bitarray import bitarray, bits2bytes
from progress.bar import ShadyBar
from .tree import Tree, NYT, exchange
from .utils import (encode_dpcm, decode_dpcm, bin_str2bool_list,
bool_list2bin_str, bool_list2int, entropy)
__version__ = '0.1.0'
# pylint: ... | adaptive_huffman_coding/__init__.py | import logging
import operator
import os
from bitarray import bitarray, bits2bytes
from progress.bar import ShadyBar
from .tree import Tree, NYT, exchange
from .utils import (encode_dpcm, decode_dpcm, bin_str2bool_list,
bool_list2bin_str, bool_list2int, entropy)
__version__ = '0.1.0'
# pylint: ... | 0.851367 | 0.354936 |
__author__ = '<NAME>'
import unittest
from mock import Mock
from pyon.util.unit_test import PyonTestCase
from pyon.util.int_test import IonIntegrationTestCase
from nose.plugins.attrib import attr
from pyon.core.exception import BadRequest, NotFound
from pyon.public import RT, IonObject
from interface.services.coi.... | ion/services/coi/test/test_object_management_service.py |
__author__ = '<NAME>'
import unittest
from mock import Mock
from pyon.util.unit_test import PyonTestCase
from pyon.util.int_test import IonIntegrationTestCase
from nose.plugins.attrib import attr
from pyon.core.exception import BadRequest, NotFound
from pyon.public import RT, IonObject
from interface.services.coi.... | 0.619356 | 0.259532 |
import numpy as np
import scipy.sparse as sp
def Diff_mat_r(Nr, r):
'''
Args:
Nr : number of points
r : list of r's
Returns:
Dr_1d : d/dr
rDr_1d : 1/r * d/dr
D2r_1d : d^2/dr^2
'''
# First derivative
Dr_1d = sp.diags([-1, 1], [-1, 1], shape = (Nr,... | diff_matrices_polar.py | import numpy as np
import scipy.sparse as sp
def Diff_mat_r(Nr, r):
'''
Args:
Nr : number of points
r : list of r's
Returns:
Dr_1d : d/dr
rDr_1d : 1/r * d/dr
D2r_1d : d^2/dr^2
'''
# First derivative
Dr_1d = sp.diags([-1, 1], [-1, 1], shape = (Nr,... | 0.59843 | 0.759069 |
from django.db import models
from ..core.models import TimeStampedModel
from ..historias.models import Historias
class Epicrisis(TimeStampedModel):
"""
- Tabla de la Epicrisis relacionada a la historia clinica
- La epicrisis es un documento que se completa cuando
se de de alta el paciente
"""
... | hpc-historias-clinicas/epicrisis/models.py | from django.db import models
from ..core.models import TimeStampedModel
from ..historias.models import Historias
class Epicrisis(TimeStampedModel):
"""
- Tabla de la Epicrisis relacionada a la historia clinica
- La epicrisis es un documento que se completa cuando
se de de alta el paciente
"""
... | 0.398055 | 0.287968 |
version = "v1.0.0"
import os,os.path, sys
from argparse import ArgumentParser
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../core'))
import brc
if __name__ == '__main__':
#Parameters to be input.
parser=ArgumentParser(description="trimming module, version {}".format(version))
... | trim/run_trim.py | version = "v1.0.0"
import os,os.path, sys
from argparse import ArgumentParser
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../core'))
import brc
if __name__ == '__main__':
#Parameters to be input.
parser=ArgumentParser(description="trimming module, version {}".format(version))
... | 0.229535 | 0.108898 |
import numpy as np
from pyccel.epyccel import epyccel
RTOL = 2e-14
ATOL = 1e-15
def test_module_1(language):
import modules.Module_1 as mod
modnew = epyccel(mod, language=language)
from numpy import zeros
# ...
x_expected = zeros(5)
x = zeros(5)
mod.f(x_expected)
mod.g(x_e... | tests/epyccel/test_epyccel_modules.py | import numpy as np
from pyccel.epyccel import epyccel
RTOL = 2e-14
ATOL = 1e-15
def test_module_1(language):
import modules.Module_1 as mod
modnew = epyccel(mod, language=language)
from numpy import zeros
# ...
x_expected = zeros(5)
x = zeros(5)
mod.f(x_expected)
mod.g(x_e... | 0.545528 | 0.516961 |
import numpy as np
from scipy import optimize
"""
<NAME>
an implementation of SIE model as introduced in Kormann, Schneider & Bartelmann (1994)
f : is the SIE lens axis ratio parameter in [0,1]
r,phi : polar coordinates of the images, r is scaled by the Einstein's radius
"""
def fRatio(f):
"""
f : SIE par... | lens/sie/model.py | import numpy as np
from scipy import optimize
"""
<NAME>
an implementation of SIE model as introduced in Kormann, Schneider & Bartelmann (1994)
f : is the SIE lens axis ratio parameter in [0,1]
r,phi : polar coordinates of the images, r is scaled by the Einstein's radius
"""
def fRatio(f):
"""
f : SIE par... | 0.699254 | 0.847842 |
import math
import cv2
import numpy as np
import torch
import torchvision as tv
def run_first_stage(args):
"""Run P-Net, generate bounding boxes, and do NMS.
Arguments:
image: an instance of PIL.Image.
net: an instance of pytorch's nn.Module, P-Net.
scale: a float number,
... | evolveface/align/first_stage.py | import math
import cv2
import numpy as np
import torch
import torchvision as tv
def run_first_stage(args):
"""Run P-Net, generate bounding boxes, and do NMS.
Arguments:
image: an instance of PIL.Image.
net: an instance of pytorch's nn.Module, P-Net.
scale: a float number,
... | 0.883651 | 0.722233 |
import logging
from ...lib import debug
from ...lib.gdsymbol import Symbol
from ...lib.symboltable import Scope
from ...lib.types.table.hierarchicalDict import HierarchicalDict
_LOGGER = logging.getLogger(__name__)
_DEBUG = debug.Debug(_LOGGER)
_version = '0.3.0'
class Requirement(HierarchicalDict):
def __init_... | gdoc/plugin/sysml/requirement.py |
import logging
from ...lib import debug
from ...lib.gdsymbol import Symbol
from ...lib.symboltable import Scope
from ...lib.types.table.hierarchicalDict import HierarchicalDict
_LOGGER = logging.getLogger(__name__)
_DEBUG = debug.Debug(_LOGGER)
_version = '0.3.0'
class Requirement(HierarchicalDict):
def __init_... | 0.261802 | 0.134349 |
import torch.nn as nn
from src.Sublayers import FeedForward, MultiHeadAttention, Norm, attention
import torch
class EncoderLayer(nn.Module):
def __init__(self, d_model, heads, dropout=0.1):
super().__init__()
self.norm_1 = Norm(d_model)
self.norm_2 = Norm(d_model)
self.attn = Multi... | src/Layers.py | import torch.nn as nn
from src.Sublayers import FeedForward, MultiHeadAttention, Norm, attention
import torch
class EncoderLayer(nn.Module):
def __init__(self, d_model, heads, dropout=0.1):
super().__init__()
self.norm_1 = Norm(d_model)
self.norm_2 = Norm(d_model)
self.attn = Multi... | 0.948953 | 0.364735 |
import os
import socket
import sys
import configparser
import logging
import json
import time
from task_loader import TaskLoader
from planner import Planner
# TODO: при отключении клиент адаптера на CUnit, которому была адресована
# последняя команда, начинается спам этой командой, так как в беск. цикле
# вызывается... | Planner/main.py | import os
import socket
import sys
import configparser
import logging
import json
import time
from task_loader import TaskLoader
from planner import Planner
# TODO: при отключении клиент адаптера на CUnit, которому была адресована
# последняя команда, начинается спам этой командой, так как в беск. цикле
# вызывается... | 0.077311 | 0.084985 |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.db import m... | connect4/models.py | from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.db import m... | 0.759761 | 0.180035 |
import math
import sys
sys.path.append("./")
import numpy as np
from utils.belief_prop import bp_error_correction
from utils.viterbi import viterbi_error_correction
from utils.kjv_text import KJVTextDataset
from utils.metrics import char_err_rate, word_err_rate
kjv = KJVTextDataset()
# Simply use ground truth one-h... | scripts/onehot_gaussian.py | import math
import sys
sys.path.append("./")
import numpy as np
from utils.belief_prop import bp_error_correction
from utils.viterbi import viterbi_error_correction
from utils.kjv_text import KJVTextDataset
from utils.metrics import char_err_rate, word_err_rate
kjv = KJVTextDataset()
# Simply use ground truth one-h... | 0.4917 | 0.290022 |
import os
import datetime
import json
import codecs
import markdown
import sys
def save_utf8(filename, text):
with codecs.open(filename, 'w', encoding='utf-8')as f:
f.write(text)
def load_utf8(filename):
with codecs.open(filename, 'r', encoding='utf-8') as f:
return f.read()
def savefinalh... | update_html.py | import os
import datetime
import json
import codecs
import markdown
import sys
def save_utf8(filename, text):
with codecs.open(filename, 'w', encoding='utf-8')as f:
f.write(text)
def load_utf8(filename):
with codecs.open(filename, 'r', encoding='utf-8') as f:
return f.read()
def savefinalh... | 0.361277 | 0.304623 |
import os
import time
import rospy
if (os.environ['ARCHITECTURE'] == 'raspi'):
import RPi.GPIO as GPIO
elif (os.environ['ARCHITECTURE'] == 'nano'):
import Jetson.GPIO as GPIO
from umnitsa_msgs.msg import Joystick, Ultrasonic
class RGB():
def __init__(self):
GPIO.setmode(GPIO.BOARD)
self.SDI = rospy.get_p... | src/umnitsa_hardware/src/rgb.py | import os
import time
import rospy
if (os.environ['ARCHITECTURE'] == 'raspi'):
import RPi.GPIO as GPIO
elif (os.environ['ARCHITECTURE'] == 'nano'):
import Jetson.GPIO as GPIO
from umnitsa_msgs.msg import Joystick, Ultrasonic
class RGB():
def __init__(self):
GPIO.setmode(GPIO.BOARD)
self.SDI = rospy.get_p... | 0.127232 | 0.09472 |
## examples:
## tune.py D331RXf P7I7bML DX352lK # compare scores for three images
## tune.py --ratio_midpoint .8 D331RXf P7I7bML DX352lK # override ratio_midpoint
import argparse
import redrum
import json
# read in parameter overrides
parser = argparse.ArgumentParser()
parser.add_argument('--ratio_midpoint', typ... | redrum/tune.py |
## examples:
## tune.py D331RXf P7I7bML DX352lK # compare scores for three images
## tune.py --ratio_midpoint .8 D331RXf P7I7bML DX352lK # override ratio_midpoint
import argparse
import redrum
import json
# read in parameter overrides
parser = argparse.ArgumentParser()
parser.add_argument('--ratio_midpoint', typ... | 0.449151 | 0.187802 |
import sys
import time
import math
import numpy as np
import matplotlib.pyplot as plt
class NNet:
def __init__(self, in_size, val_size, layers, random_seed=1, verbose=True,
sigm=lambda x:1/(1+np.exp(-x)),
sigm_d=lambda x:np.exp(-x)/np.power((np.exp(-x) + 1), 2)):
self.verbose = ve... | nnet.py | import sys
import time
import math
import numpy as np
import matplotlib.pyplot as plt
class NNet:
def __init__(self, in_size, val_size, layers, random_seed=1, verbose=True,
sigm=lambda x:1/(1+np.exp(-x)),
sigm_d=lambda x:np.exp(-x)/np.power((np.exp(-x) + 1), 2)):
self.verbose = ve... | 0.333069 | 0.393968 |
import sys
import os, os.path
import shutil
if sys.version_info < (3,):
range = xrange
def CheckParameter():
outputPath = None
searchStartDir = None
isIncludeFolder = None
excludePaths = None
count = len(sys.argv)-1
if count >= 8:
for i in range(1, count):
if sys.argv[i] == "-OutputPath":
ou... | Script/HeaderOrganizer.py | import sys
import os, os.path
import shutil
if sys.version_info < (3,):
range = xrange
def CheckParameter():
outputPath = None
searchStartDir = None
isIncludeFolder = None
excludePaths = None
count = len(sys.argv)-1
if count >= 8:
for i in range(1, count):
if sys.argv[i] == "-OutputPath":
ou... | 0.047283 | 0.077169 |
import pandas as pd
import numpy as np
from collections import Counter
import sanalytics.estimators.pu_estimators as pu
import sanalytics.evaluation.utils as seu
import sanalytics.algorithms.utils as sau
import joblib
import random
import itertools
from gensim.models.doc2vec import Doc2Vec
from collections import Count... | Code/analysis/job_array_rq3/testmodels/test_models.py | import pandas as pd
import numpy as np
from collections import Counter
import sanalytics.estimators.pu_estimators as pu
import sanalytics.evaluation.utils as seu
import sanalytics.algorithms.utils as sau
import joblib
import random
import itertools
from gensim.models.doc2vec import Doc2Vec
from collections import Count... | 0.424651 | 0.219421 |
from typing import Generic
from typing import List
from typing import NewType
from typing import Tuple
from typing import Type
from typing import TypeVar
from typedjson.annotation import args_of
from typedjson.annotation import origin_of
from typedjson.annotation import parameters_of
from typedjson.annotation import ... | tests/test_annotation.py |
from typing import Generic
from typing import List
from typing import NewType
from typing import Tuple
from typing import Type
from typing import TypeVar
from typedjson.annotation import args_of
from typedjson.annotation import origin_of
from typedjson.annotation import parameters_of
from typedjson.annotation import ... | 0.853715 | 0.601681 |
from ceo.tools import ascupy
from ceo.pyramid import Pyramid
import numpy as np
import cupy as cp
from scipy.ndimage import center_of_mass
class PyramidWFS(Pyramid):
def __init__(self, N_SIDE_LENSLET, N_PX_LENSLET, modulation=0.0, N_GS=1, throughput=1.0, separation=None):
Pyramid.__init__(self)
sel... | python/ceo/sensors/PyramidWFS.py | from ceo.tools import ascupy
from ceo.pyramid import Pyramid
import numpy as np
import cupy as cp
from scipy.ndimage import center_of_mass
class PyramidWFS(Pyramid):
def __init__(self, N_SIDE_LENSLET, N_PX_LENSLET, modulation=0.0, N_GS=1, throughput=1.0, separation=None):
Pyramid.__init__(self)
sel... | 0.74382 | 0.368491 |
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
import dlib
import imutils
import numpy as np
import cv2
import face_recognition
def FaceAlign(image, shape_predictor="assets/shape_predictor_68_face_landmarks.dat"):
'''
return a list of aligned faces
'''
faceDetector... | image-search/helpers.py | from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
import dlib
import imutils
import numpy as np
import cv2
import face_recognition
def FaceAlign(image, shape_predictor="assets/shape_predictor_68_face_landmarks.dat"):
'''
return a list of aligned faces
'''
faceDetector... | 0.675872 | 0.638018 |
# assumes you downbloaded the CORD-19 data: https://pages.semanticscholar.org/coronavirus-research
# On a modern laptop this scrip takes about less tha a minute to run on each CORD-19 subset.
import os
import sys
import pandas as pd
import numpy as np
import json
from tqdm import tqdm
# Individual paths to various C... | datasources/manual/cord_nineteen_transformer.py |
# assumes you downbloaded the CORD-19 data: https://pages.semanticscholar.org/coronavirus-research
# On a modern laptop this scrip takes about less tha a minute to run on each CORD-19 subset.
import os
import sys
import pandas as pd
import numpy as np
import json
from tqdm import tqdm
# Individual paths to various C... | 0.30549 | 0.345298 |
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | sql_write_pb2.py | """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.235988 | 0.075075 |
#@author hebert.santos
#@since 23/10/2019
#@version P12
#/*/
#//-------------------------------------------------------------------
from tir import Webapp
import unittest
import time
class MATA310(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAEST','','T1... | Protheus_WebApp/Modules/SIGAEST/MATA310TESTCASE.py |
#@author hebert.santos
#@since 23/10/2019
#@version P12
#/*/
#//-------------------------------------------------------------------
from tir import Webapp
import unittest
import time
class MATA310(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAEST','','T1... | 0.150653 | 0.10581 |
import os
from pathlib import Path
from pyfakefs.fake_filesystem_unittest import TestCase
from portals import yaml_db
class TestYamlDb(TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_dump(self):
"""After writing a config a file should exist"""
path_to_config = Path("fred.y... | portals/test/test_yaml_db.py | import os
from pathlib import Path
from pyfakefs.fake_filesystem_unittest import TestCase
from portals import yaml_db
class TestYamlDb(TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_dump(self):
"""After writing a config a file should exist"""
path_to_config = Path("fred.y... | 0.490968 | 0.382055 |
from django import template
from django.contrib.auth.models import User
register = template.Library()
from django.shortcuts import render, get_object_or_404
from ..models import Analysis, ProjectComment, Module, Project, File, ParamsComment, Param
from ..forms import ProjectEditCommForm, ParamForm2, ModuleParamForm, P... | app/templatetags/upload_tags.py | from django import template
from django.contrib.auth.models import User
register = template.Library()
from django.shortcuts import render, get_object_or_404
from ..models import Analysis, ProjectComment, Module, Project, File, ParamsComment, Param
from ..forms import ProjectEditCommForm, ParamForm2, ModuleParamForm, P... | 0.306838 | 0.073032 |
from enum import Enum, unique
import math
class Stats(object):
def __init__(self):
self.hits = 0
self.private_hits = 0
self.shared_hits = 0
self.misses = 0
self.invalidated = 0
self.lines_invalidated = 0
self.write_backs = 0
self.write_updates = 0
... | PA/coursework_2/models.py | from enum import Enum, unique
import math
class Stats(object):
def __init__(self):
self.hits = 0
self.private_hits = 0
self.shared_hits = 0
self.misses = 0
self.invalidated = 0
self.lines_invalidated = 0
self.write_backs = 0
self.write_updates = 0
... | 0.698844 | 0.219129 |
import numpy as np
from numba import jit, prange, boolean
from pecanpy.graph import SparseGraph, DenseGraph
class Base:
"""Improved version of original node2vec
Parallelized transition probabilities pre-computation and random walks
"""
def __init__(self, p, q, workers, verbose):
super(Base, se... | src/pecanpy/node2vec.py | import numpy as np
from numba import jit, prange, boolean
from pecanpy.graph import SparseGraph, DenseGraph
class Base:
"""Improved version of original node2vec
Parallelized transition probabilities pre-computation and random walks
"""
def __init__(self, p, q, workers, verbose):
super(Base, se... | 0.633864 | 0.369287 |
import logging
import time
from telemetry.results import page_test_results
class GTestTestResults(page_test_results.PageTestResults):
def __init__(self, output_stream):
super(GTestTestResults, self).__init__(output_stream)
self._timestamp = None
def _GetMs(self):
return (time.time() - self._timesta... | tools/telemetry/telemetry/results/gtest_test_results.py |
import logging
import time
from telemetry.results import page_test_results
class GTestTestResults(page_test_results.PageTestResults):
def __init__(self, output_stream):
super(GTestTestResults, self).__init__(output_stream)
self._timestamp = None
def _GetMs(self):
return (time.time() - self._timesta... | 0.203312 | 0.23895 |
from tests.utils import assert_bindings
def test_list_id_pattern_1_nistxml_sv_iv_list_id_pattern_2_1(mode, save_output, output_format):
r"""
Type list/ID is restricted by facet pattern with value
[\i-[:]][\c-[:]]{5} [\i-[:]][\c-[:]]{36} [\i-[:]][\c-[:]]{42}
[\i-[:]][\c-[:]]{37} [\i-[:]][\c-[:]]{23} [\... | tests/test_nist_meta_2000.py | from tests.utils import assert_bindings
def test_list_id_pattern_1_nistxml_sv_iv_list_id_pattern_2_1(mode, save_output, output_format):
r"""
Type list/ID is restricted by facet pattern with value
[\i-[:]][\c-[:]]{5} [\i-[:]][\c-[:]]{36} [\i-[:]][\c-[:]]{42}
[\i-[:]][\c-[:]]{37} [\i-[:]][\c-[:]]{23} [\... | 0.49292 | 0.275045 |
import re
import warnings
from math import inf
from comath.segment import LineSegment
__LOGICAL_OPS = set(('$or', '$and', '$not', '$nor'))
__COMPAR_OPS = set(('$eq', '$gt', '$gte', '$lt', '$lte', '$ne', '$in', '$nin'))
def _contains_logical_op(matchop):
return len(matchop.keys() & __LOGICAL_OPS) > 0
def _va... | mongozen/matchop/_matchop.py |
import re
import warnings
from math import inf
from comath.segment import LineSegment
__LOGICAL_OPS = set(('$or', '$and', '$not', '$nor'))
__COMPAR_OPS = set(('$eq', '$gt', '$gte', '$lt', '$lte', '$ne', '$in', '$nin'))
def _contains_logical_op(matchop):
return len(matchop.keys() & __LOGICAL_OPS) > 0
def _va... | 0.521227 | 0.262931 |
import json
from django.contrib.gis.geos import GEOSGeometry
from stac_api.models import BBOX_CH
from stac_api.utils import fromisoformat
geometries = {
'switzerland': GEOSGeometry(BBOX_CH),
'switzerland-west':
GEOSGeometry(
'SRID=4326;POLYGON(('
'5.710217406117146 47.84846875... | app/tests/sample_data/item_samples.py | import json
from django.contrib.gis.geos import GEOSGeometry
from stac_api.models import BBOX_CH
from stac_api.utils import fromisoformat
geometries = {
'switzerland': GEOSGeometry(BBOX_CH),
'switzerland-west':
GEOSGeometry(
'SRID=4326;POLYGON(('
'5.710217406117146 47.84846875... | 0.4206 | 0.153676 |
import os
import geoip2.database
from django.conf import settings
class Geoip2(object):
def __init__(self):
city_mmdb_dir = os.path.join(settings.BASE_DIR, 'STATICFILES', 'STATIC', 'GeoLite2-City.mmdb')
self.city_reader = geoip2.database.Reader(city_mmdb_dir)
asn_mmdb_dir = os.path.join(s... | Lib/External/geoip2.py | import os
import geoip2.database
from django.conf import settings
class Geoip2(object):
def __init__(self):
city_mmdb_dir = os.path.join(settings.BASE_DIR, 'STATICFILES', 'STATIC', 'GeoLite2-City.mmdb')
self.city_reader = geoip2.database.Reader(city_mmdb_dir)
asn_mmdb_dir = os.path.join(s... | 0.243463 | 0.068819 |
import logging
import os
import unittest
from time import sleep
import redis
from redis.sentinel import Sentinel
from open_redis.deployment import RedisDeployment, RedisSentinel
file_dir = os.path.realpath(__file__).rsplit('/', 1)[0] + "/"
class TestRedisDeploy(unittest.TestCase):
def setUp(self):
for ... | tests/basic_usage.py | import logging
import os
import unittest
from time import sleep
import redis
from redis.sentinel import Sentinel
from open_redis.deployment import RedisDeployment, RedisSentinel
file_dir = os.path.realpath(__file__).rsplit('/', 1)[0] + "/"
class TestRedisDeploy(unittest.TestCase):
def setUp(self):
for ... | 0.166879 | 0.344361 |
from typing import Callable, Optional, Tuple
import cv2 as cv
import numpy as np
def resize(
image: np.array,
shape: Optional[Tuple[int, int]] = None,
min_dim: Optional[int] = None,
**kwargs,
) -> np.array:
"""
Resize input image
`shape` or `min_dim` needs to be specified with `partial` ... | wildebeest/ops/image/transforms.py | from typing import Callable, Optional, Tuple
import cv2 as cv
import numpy as np
def resize(
image: np.array,
shape: Optional[Tuple[int, int]] = None,
min_dim: Optional[int] = None,
**kwargs,
) -> np.array:
"""
Resize input image
`shape` or `min_dim` needs to be specified with `partial` ... | 0.961534 | 0.704109 |
from app import app
from flask_wtf import FlaskForm
from wtforms import (
StringField,
TextAreaField,
SubmitField,
IntegerField,
SelectField,
HiddenField,
PasswordField,
BooleanField
)
from wtforms.validators import DataRequired, Optional
from flask_babel import lazy_gettext as _l
from ... | flask_app/app/forms/radius.py | from app import app
from flask_wtf import FlaskForm
from wtforms import (
StringField,
TextAreaField,
SubmitField,
IntegerField,
SelectField,
HiddenField,
PasswordField,
BooleanField
)
from wtforms.validators import DataRequired, Optional
from flask_babel import lazy_gettext as _l
from ... | 0.554953 | 0.098773 |
from __future__ import print_function
import datetime
import requests
from bs4 import BeautifulSoup
import sys
import time
import unicodecsv as csv
MAXLIMIT = 20000
url = "http://www.woolworths.co.za/store/cat/Food/_/N-1z13sk4?No={start_index}&Nr=NOT%28isSkuActive%3A0%29&Nrpp=1000"
def exstr(tag):
if tag:
... | scrape_all.py | from __future__ import print_function
import datetime
import requests
from bs4 import BeautifulSoup
import sys
import time
import unicodecsv as csv
MAXLIMIT = 20000
url = "http://www.woolworths.co.za/store/cat/Food/_/N-1z13sk4?No={start_index}&Nr=NOT%28isSkuActive%3A0%29&Nrpp=1000"
def exstr(tag):
if tag:
... | 0.191857 | 0.078184 |
# X86 registers
X86_REG_INVALID = 0
X86_REG_AH = 1
X86_REG_AL = 2
X86_REG_AX = 3
X86_REG_BH = 4
X86_REG_BL = 5
X86_REG_BP = 6
X86_REG_BPL = 7
X86_REG_BX = 8
X86_REG_CH = 9
X86_REG_CL = 10
X86_REG_CS = 11
X86_REG_CX = 12
X86_REG_DH = 13
X86_REG_DI = 14
X86_REG_DIL = 15
X86_REG_DL = 16
X86_REG_DS = 17
X86_REG_DX = 18
X... | bindings/python/capstone/x86_const.py |
# X86 registers
X86_REG_INVALID = 0
X86_REG_AH = 1
X86_REG_AL = 2
X86_REG_AX = 3
X86_REG_BH = 4
X86_REG_BL = 5
X86_REG_BP = 6
X86_REG_BPL = 7
X86_REG_BX = 8
X86_REG_CH = 9
X86_REG_CL = 10
X86_REG_CS = 11
X86_REG_CX = 12
X86_REG_DH = 13
X86_REG_DI = 14
X86_REG_DIL = 15
X86_REG_DL = 16
X86_REG_DS = 17
X86_REG_DX = 18
X... | 0.333612 | 0.112893 |