id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
4849459 | WIDTH = 200
HEIGHT = 200
PIXELSIZE = 4
BRUSHSIZE = 1
# COLORS
BACKGROUND = (0, 0, 0)
CURSOR = (90, 90, 90)
CURSORALPHA = 90
GRID = (30, 30, 30)
DEFAULTTEMP = 297.5
GLOBAL_TEMP_FACTOR = 0.2
GLOBAL_TEMP_RATE = 0.6
MAXUPDATE = 60 # frames that an element needs to be stationary before it freezes
BORDER = [2, 2, 2, ... | StarcoderdataPython |
6516545 | import binascii
import struct
import hashlib
import math
import bittensor
import rich
import time
import torch
import numbers
import pandas
from typing import Tuple, List, Union, Optional
def indexed_values_to_dataframe (
prefix: Union[str, int],
index: Union[list, torch.LongTensor],
values:... | StarcoderdataPython |
9732547 | # Generated by Django 3.0.10 on 2020-09-11 16:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djcelery_model', '0003_auto_20200713_1254'),
]
operations = [
migrations.AlterField(
model_name='modeltaskmeta',
na... | StarcoderdataPython |
9710100 | #!/usr/bin/env python -tt
"""
unittests.test_security
"""
try:
import unittest2 as unittest
except ImportError:
import unittest
import logging
import os
# import sys
import dbsign.logger as L
import dbsign.security as S
import dbsign.shell as sh
log = L.get_logger(__name__)
@unittest.skip("need to mock i... | StarcoderdataPython |
4853787 | <gh_stars>1-10
# -*- coding: utf-8 -*-
#
# urls.py for app 'page'
#
from django.conf.urls import patterns, include, url
from notice.views import ListNoticeView
urlpatterns = patterns('',
# notice list view
url(r'^list/$', ListNoticeView.as_view(),
name='list_notice'),
)
| StarcoderdataPython |
140139 | <filename>webapp/apps/test_assets/utils.py
import json
import os
import sys
from ..taxbrain.compute import MockCompute
from ..taxbrain.models import TaxSaveInputs, OutputUrl
from ..taxbrain.forms import PersonalExemptionForm
from ..dynamic import views
from ..taxbrain import views
from django.core.files.uploadedfil... | StarcoderdataPython |
11354918 | import Currency
n = float(input('Please, type a value (R$): '))
Currency.Resume(n)
| StarcoderdataPython |
301430 | #!/usr/bin/env python3
"""
Plotting routines dedicated to time-series or temporal trends
"""
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
# import seaborn as sns
#--------------------------------------
# Time-Series Plots
#--------------------------... | StarcoderdataPython |
17295 | <gh_stars>1-10
from open_anafi.models import Indicator, IndicatorParameter, IndicatorLibelle
from open_anafi.serializers import IndicatorSerializer
from .frame_tools import FrameTools
from open_anafi.lib import parsing_tools
from open_anafi.lib.ply.parsing_classes import Indic
import re
from django.db import transactio... | StarcoderdataPython |
6656411 | <reponame>daniele-sartiano/biaffine-parser
# -*- coding: utf-8 -*-
import argparse
from datetime import datetime
from parser import Model
from parser.cmds.cmd import CMD
from parser.utils.corpus import Corpus, TextCorpus
from parser.utils.data import TextDataset, batchify
import torch
class Predict(CMD):
def a... | StarcoderdataPython |
6660929 | <reponame>chavarera/Selenium_Screenshot
import os
import sys
import time
DATA_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.abspath(os.path.dirname(DATA_DIR)))
from Screenshot.Screenshot_Clipping import Screenshot
from selenium import webdriver
iedriver_path = os.path.abspath(DATA_DIR +... | StarcoderdataPython |
4967622 | <reponame>Waytoaniket/Myguard
import boto3
import csv
import os
import random
import string
import shutil
import time
import datetime
import base64
from dotenv import load_dotenv
from flask import Blueprint, current_app, render_template, url_for, redirect, request, session, flash
from werkzeug.utils import secure_filen... | StarcoderdataPython |
3379699 | import shutil
import pytest
from pytest import approx
import pandas as pd
import calliope
from calliope.test.common.util import check_error_or_warning
class TestModelPreproccesing:
def test_preprocess_national_scale(self):
calliope.examples.national_scale()
def test_preprocess_time_clustering(self)... | StarcoderdataPython |
4973656 | <gh_stars>0
x, y, z = 2, 5, 107
# ÖDÜLLÜ SORULAR - ÖDÜL 20 TL PARA
# 1- Kullanıcıdan aldığınız 2 sayının çarpımı ile x,y,z toplamının farkı nedir
# a = int(input('1.sayı: '))
# b = int(input('2.sayı: '))
# result = (a*b) - (x+y+z)
# 2- y' nin x' e kalansız bölümünü hesaplayınız
result = y // x
# ... | StarcoderdataPython |
3288433 | # This example assumes servers to load balance
# already exist and will be pool members
import libcloud
from libcloud.loadbalancer.base import Algorithm
def create_load_balancer():
# Compute driver to retrieve servers to be pool members (the nodes)
cls = libcloud.get_driver(libcloud.DriverType.COMPUTE,
... | StarcoderdataPython |
8062849 | <reponame>John1001Song/Big-Data-Robo-Adviser<gh_stars>1-10
import os
from os.path import isfile, join
from os import listdir
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
N_fs_growth_ann_path = '../datasets/NASDAQ/financial_statement/growth/annual/'
N_fs_growth_qua_path = '../datasets... | StarcoderdataPython |
1640128 | # Get the first n-digit pandigital prime.
# FAST (<1.1s)
#
# APPROACH:
# - Use the permutations that are genererated by itertools.permutation
# to generate them sorted.
# - Generate primes only until sqrt(987654321), the max possible n-digit pandigital prime,
# so it can be checked that the numbers are pri... | StarcoderdataPython |
5140301 | from ddpg import *
#from new_ddpg import *
#from pretrained_ddpg import *
import rec_env
import sys
import gc
gc.enable()
EPISODES = 100000
TEST_NUM = 10
flag_test = False
def main():
env = rec_env.Env()
agent = DDPG(env.state_space, env.action_dim)
for episode in range(EPISODES):
env.reset()
... | StarcoderdataPython |
5041234 | """
Modules in this directory smooth over importing functionality that may be
present in different libraries, depending on the users' system.
"""
| StarcoderdataPython |
1972604 | from dataflows import Flow, update_package
from dgp.core.base_enricher import enrichments_flows, BaseEnricher
from dgp.config.consts import RESOURCE_NAME, CONFIG_PRIMARY_KEY
from dgp_server.log import logger
class LoadMetadata(BaseEnricher):
def test(self):
return self.config._unflatten().get('extra', {... | StarcoderdataPython |
113857 | import dnd.parse
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Optional, Any
import dnd.table
_EMPTY_DICT = dict()
class Template(object):
def __init__(self, text: "str") -> None:
self._text = text
self._parts = list()
self._values = None # type: Optiona... | StarcoderdataPython |
3303384 | # encoding: utf-8
import sys
import re
import argparse
from workflow.workflow import MATCH_ATOM, MATCH_STARTSWITH, MATCH_SUBSTRING, MATCH_ALL, MATCH_INITIALS, MATCH_CAPITALS, MATCH_INITIALS_STARTSWITH, MATCH_INITIALS_CONTAIN
from workflow import Workflow, ICON_WEB, ICON_WARNING, ICON_BURN, ICON_SWITCH, ICON_HOME, ICON... | StarcoderdataPython |
5117430 | print('-=-=-=-=-= DESAFIO 95 -=-=-=-=')
print()
print('=-='*15)
print(f'{"APROVEITAMENTO DO JOGADOR":^45}')
print('=-='*15)
jogador = {}
time = []
while True:
gols = []
jogador['nome'] = str(input('Nome: ')).title()
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
for c in range(1... | StarcoderdataPython |
5177830 | <gh_stars>1-10
import sys
import time
import pdb
from copy import deepcopy
from multiprocessing import Pool
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
import pandas as pd
from sklearn.preprocessing import StandardScaler
from scipy.stats import multivariate_normal
from sc... | StarcoderdataPython |
5108300 | <gh_stars>0
#print('__init__')
import sys
import importlib
def reload():
# print('reload')
importlib.reload(formatter)
importlib.reload(functionmaker)
importlib.reload(logger)
importlib.reload(mawk)
from . import arguments, formatter, functionmaker, logger, mawk, utils
#from .__main__ import main
#p... | StarcoderdataPython |
213600 | <filename>OSINT-Reconnaissance/nwatch/nwatch.py
#!/usr/bin/python
#GNU GPLv3
# nWatch.py - handy tool for host discovery, portscanning and operating system fingerprinting.
# Copyright (C) <2016> <<NAME>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU ... | StarcoderdataPython |
4859078 | <gh_stars>10-100
#!/usr/bin/env python3
# reproduce_character_models.py
# Reproduce predictive modeling of characters.
# This script assumes that you have subset.tar.gz
# in the parent directory of the /train_models directory
# directory. It also expects to have a /temp directory
# as a sibling (at the same level as... | StarcoderdataPython |
12827184 | from tenx_missile import MissileLauncher
_VALID_CODES = ['DPRK', 'BOOM', 'ACME']
class Missile:
def __init__(self):
self._launcher = MissileLauncher()
def fire(self):
self._launcher.fire()
def launch_missile(missile, code):
if check_code(code):
missile.fire()
def check_code(c... | StarcoderdataPython |
12816046 | <filename>test/crs/test_crs_maker.py<gh_stars>1-10
import pytest
from pyproj.crs import (
BoundCRS,
CompoundCRS,
DerivedGeographicCRS,
GeographicCRS,
ProjectedCRS,
VerticalCRS,
)
from pyproj.crs.coordinate_operation import (
AlbersEqualAreaConversion,
LambertConformalConic2SPConversion,... | StarcoderdataPython |
1922838 | <reponame>veritaem/Twitoff
"""
Initializes directory for Flask app
"""
from .app import create_app
APP = create_app()
| StarcoderdataPython |
6601417 | <gh_stars>0
from flask import Blueprint, render_template
blueprint = Blueprint("viewer", __name__)
@blueprint.route("/viewer")
def viewer():
return render_template("viewer/viewer.html")
| StarcoderdataPython |
8002230 | import time
import chipwhisperer as cw
def cwconnect(offset=1250, totalsamples=3000):
scope = cw.scope()
target = cw.target(scope)
# setup scope parameters
scope.gain.gain = 45
scope.adc.samples = int(totalsamples)
scope.adc.offset = int(offset)
scope.adc.basic_mode = "rising_edge"
sc... | StarcoderdataPython |
11255846 |
# from web.web1.web3 import cal
#from web.web1.web3.cal import add
# from web.web1 import web3 #执行web3的__init__文件,唯一不支持的调用方式
# print(web3.cal.add(2,6))
from web.web1.web3 import cal
cal.add(3,8)
| StarcoderdataPython |
6444175 | <filename>make_animation.py<gh_stars>0
from __future__ import print_function
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import tifffile
import skimage.exposure
import scipy.ndimage.filters as filters
def ani_frame(images,firstIm,lastImage,subtract_first=True,f... | StarcoderdataPython |
5040578 | <filename>sdk/python/pulumi_alicloud/ess/attachment.py
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapp... | StarcoderdataPython |
9690876 | <filename>cpgan_model.py
# <NAME>, March 2020
# Common code for PyTorch implementation of Copy-Pasting GAN
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from cpgan_data import *
from cpgan_tools import *
def create_gaussian_filter(blur_sigma):
bs_r... | StarcoderdataPython |
1621086 | <reponame>kancurochat/mcx
import jax.numpy as np
from jax import random, scipy
from mcx.distributions import constraints
from mcx.distributions.distribution import Distribution
from mcx.distributions.shapes import broadcast_batch_shape
class StudentT(Distribution):
parameters = {"df": constraints.strictly_positi... | StarcoderdataPython |
208506 | from __future__ import print_function
try:
import argparse
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from torch.autograd import Variable
from torch.autograd import grad as torch_grad
import torch
import torchvi... | StarcoderdataPython |
11388443 | from flask import current_app
from testAuxiliaryFuncs import decryptAES, getDecryptor, encryptAES
from bson import json_util, ObjectId
def test_allsites(client, auth, app):
token = auth.login('test1', '<PASSWORD>')
response = client.get('/api/AllSites', headers={"token": token})
with app.app_context():
... | StarcoderdataPython |
11201120 | # !/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Author: <NAME> - <EMAIL>
# Blog: zhouyichu.com
#
# Python release: 3.6.0
#
# Date: 2020-03-20 10:56:58
# Last modified: 2020-12-28 15:30:23
"""
Data structure for probing.
"""
# import logging
from collections import Counter
from functools import total_ordering
impor... | StarcoderdataPython |
1702271 | <reponame>carmenchilson/BirdRoostDetection
"""Read in csv and create train, test, and validation splits for ML."""
import BirdRoostDetection.LoadSettings as settings
import os
import pandas
def ml_splits_by_date(csv_input_path,
csv_output_path,
k=5):
"""Split labeled da... | StarcoderdataPython |
1679004 | from binaryninja.architecture import Architecture
from binaryninja.function import RegisterInfo, InstructionInfo, InstructionTextToken
from binaryninja.enums import Endianness, InstructionTextTokenType, BranchType, SegmentFlag, SectionSemantics
from binaryninja.log import log_info
from .view import Chip8View
from .disa... | StarcoderdataPython |
1975308 | # -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['test_schema[updateMap-all-options] 1'] = {
'data': {
'updateMap': {
'map': {
'mapId': '1001',
... | StarcoderdataPython |
13917 | #!/usr/bin/env python
# Copyright 2018-present Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
9722580 | <gh_stars>0
from product_details import product_details
def current_firefox_regexp():
current_firefox = int(product_details.firefox_versions['LATEST_FIREFOX_VERSION'].split('.')[0])
versions = ['%s' % i for i in range(current_firefox, current_firefox + 4)]
return '|'.join(versions)
| StarcoderdataPython |
388815 | """
ddtrace.vendor
==============
Install vendored dependencies under a different top level package to avoid importing `ddtrace/__init__.py`
whenever a dependency is imported. Doing this allows us to have a little more control over import order.
Dependencies
============
six
---
Website: https://six.readthedocs.io/... | StarcoderdataPython |
124760 | <filename>Trolls/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-13 07:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]... | StarcoderdataPython |
8095979 | from django.shortcuts import render
from rest_framework import viewsets, status, generics , permissions, authentication
# Create your views here.
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import api_view
from rest_framework.generics import ListAPIView
from rest_framew... | StarcoderdataPython |
8125232 | from dataclasses import dataclass, field
from functools import partial
from operator import le
from typing import Optional
from more_properties import cached_property
from toposort import toposort
__all__ = ["RefinementDict", "AmbiguousKeyError"]
class AmbiguousKeyError(KeyError):
pass
@dataclass
class Refine... | StarcoderdataPython |
12845383 | texts = {
"browse":"🗂️ Browse categories",
"orders":"📥 My orders",
"cart":"🛒 My cart",
"settings":"⚙ Settings",
"contact":"📞 Contact us",
"home":"🏠 Home",
"contact1":"{Store_name} - {store_phone}",
} | StarcoderdataPython |
364924 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | StarcoderdataPython |
5027322 | <gh_stars>1-10
"""Functions to Plot RoboJam Performances
"""
import matplotlib.pyplot as plt
from robojam import divide_performance_into_swipes
input_colour = 'darkblue'
gen_colour = 'firebrick'
def plot_2D(perf_df, name="foo", saving=False, figsize=(8, 8)):
"""Plot a 2D representation of a performance 2D"""
... | StarcoderdataPython |
98642 | from typing import Final
from django.db import models
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
class Choice(models.Model):
title = models.CharField(max_length=4096)
def __str__(self):
return self.title
class Meta:
verbose_name =... | StarcoderdataPython |
9679407 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
app = Flask(__name__)
#import os
#print os.environ.keys()
#print os.environ.get('FLASKR_SETTINGS')
#加载配置文件内容
app.config.from_object('myWeb.setting') #模块下的setting文件名,不用加py后缀
app.config.from_envvar('FLASKR_... | StarcoderdataPython |
3576637 | <reponame>AR0EN/film-exif<gh_stars>0
# References
# [Exchangeable Image File Format] | (http://www.cipa.jp/std/documents/e/DC-008-2012_E.pdf)
# [Piexif] | (https://github.com/hMatoba/Piexif)
# Import
import os
import sys
import copy
import piexif as pxf
from PIL import Image
# Constants
TAG = 'Film Exif... | StarcoderdataPython |
4921523 | # Generated by Django 3.2.1 on 2021-05-05 08:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hood', '0005_auto_20210505_0757'),
]
operations = [
migrations.AddField(
model_name='profile',
... | StarcoderdataPython |
9655334 | <gh_stars>1-10
#!/usr/bin/env python
"""
Usage: python num_parameters.py <model_file>.pkl
Prints the number of parameters in a saved model (total number of scalar
elements in all the arrays parameterizing the model).
"""
__author__ = "<NAME>"
import sys
from pylearn2.utils import serial
def num_parameters(model):
... | StarcoderdataPython |
4909934 | """Fix the name of modules
This module is useful when you want to rename many of the modules in
your project. That can happen specially when you want to change their
naming style.
For instance::
fixer = FixModuleNames(project)
changes = fixer.get_changes(fixer=str.lower)
project.do(changes)
Here it renames a... | StarcoderdataPython |
321589 | <reponame>ask/metasyntactic<filename>metasyntactic/themes/muses.py
# -*- coding: utf-8 -*-
'''
##########################
Acme::MetaSyntactic::muses
##########################
****
NAME
****
Acme::MetaSyntactic::muses - Greek Muses
***********
DESCRIPTION
***********
The nine muses from Greek mythology.
*****... | StarcoderdataPython |
11372456 | from django.apps import AppConfig
class StockInquiryConfig(AppConfig):
name = 'stock_inquiry'
| StarcoderdataPython |
6497291 | '''
Desenvolva um que pergunta a distância de uma viagem em KM.
Calcule o preço da passagem. Cobrando R$ 0,50 por KM
para viagens de até 200km e R$ 0,45 para viagens mais longas.
'''
distancia = float(input("Digite a distância que você tem que percorrer: "))
precoCurto = 0.50
precoLongo = 0.45
if distancia <= 200:
... | StarcoderdataPython |
12848923 | <reponame>veqtor/veqtor_keras
import tensorflow as tf
from tensorflow.keras.utils import custom_object_scope
from tensorflow.python.keras.testing_utils import layer_test
from veqtor_keras.layers.time_delay_layers import TimeDelayLayer1D, DepthGroupwiseTimeDelayLayer1D, \
DepthGroupwiseTimeDelayLayerFake2D, TimeDel... | StarcoderdataPython |
152923 | <gh_stars>0
import contextlib
import os
from functools import partial
import click
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg="red", err=True)
@contextlib.contextmanager
def suppress_stdout():
null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
# Save the actual ... | StarcoderdataPython |
1999887 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | StarcoderdataPython |
9649229 | <reponame>stefanlack/ods-project-quickstarters
#!/usr/bin/env python
import setuptools
setuptools.setup(name='airflow-dag-dependencies',
version='0.1',
description='DAG dependencies',
url='https://www.python.org/sigs/distutils-sig/',
packages=setuptools.find_packages(),
install_requires=... | StarcoderdataPython |
9693358 | <gh_stars>1-10
Board=[i for i in range(0,9)]
User,Computer='X','O'
Picks=[i for i in range(1,10)]
winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
def print_board():
x=1
for i in Board:
if x%3==0:
if i in('X','O'):print( i ,end='\n' + '---------'+'\n')
else:print( i+1 ,end... | StarcoderdataPython |
5009640 | """Sample API Client."""
from __future__ import annotations
import asyncio
import socket
from typing import Any
import ssl
import aiohttp
import async_timeout
import requests
from requests import adapters
from urllib3 import poolmanager
from .const import LOGGER, REVERSE_GEOCODE_URL, POWER_URL, HEAT_URL
API_HEADERS... | StarcoderdataPython |
5041156 | from time import strftime
import apollocaffe
import numpy as np
import os
class TrainLogger(object):
def __init__(self, display_interval, log_file="/tmp/apollocaffe_log.txt"):
self.display_interval = display_interval
self.log_file = log_file
os.system("touch %s" % self.log_file)
def log... | StarcoderdataPython |
6475356 | import argparse
from typing import List, Optional
import torch
from omegaconf import OmegaConf
from classy.utils.optional_deps import requires
try:
import uvicorn
from fastapi import FastAPI
except ImportError:
uvicorn = None
FastAPI = None
from classy.utils.commons import get_local_ip_address
from ... | StarcoderdataPython |
6704135 | """Implement mixture of probability distribution layers"""
import torch
from torch import Tensor, nn
from torch.nn import Module
import torch.nn.functional as F
from typing import List, Union, Tuple
__all__ = ['MixtureOfGaussian', 'MixtureOfExpert']
class MixtureOfGaussian(nn.Linear):
"""
A layer that gener... | StarcoderdataPython |
158331 | <gh_stars>10-100
from tmu.tsetlin_machine import TMClassifier
import numpy as np
from time import time
number_of_features = 20
noise = 0.1
X_train = np.random.randint(0, 2, size=(5000, number_of_features), dtype=np.uint32)
Y_train = np.logical_xor(X_train[:,0], X_train[:,1]).astype(dtype=np.uint32)
Y_train = np.where... | StarcoderdataPython |
131264 | <filename>python/graphscope/analytical/app/pagerank_nx.py<gh_stars>1000+
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lic... | StarcoderdataPython |
5157030 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
Created By : <NAME> - Bacnv6
Created Date: Mon November 03 10:00:00 VNT 2020
Project : AkaOCR core
_____________________________________________________________________________
This file co... | StarcoderdataPython |
3520224 | <gh_stars>1-10
"""
Module for DishLeafNode utils
"""
# Imports
import enum
import math
import re
import logging
module_logger = logging.getLogger(__name__)
# In future, PointingState class will be moved to a file for all the enum attributes for DishLeafNode.
class PointingState(enum.IntEnum):
"""
Pointing s... | StarcoderdataPython |
8049394 | from setuptools import setup, find_packages
ANALYSIS_PLUGINS = [
"complexity = pordego_complexity.complexity_analysis:analyze_complexity"
]
with open('LICENSE') as f:
LICENSE = f.read()
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OS... | StarcoderdataPython |
181172 | <reponame>lyraxvincent/phones-priceinkenya
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import re
import numpy as np
import pandas as pd
# a function to clean phone titles so their search can yield better results
def cleantitle(phonetitle):
if str(phonetitle).endswith("GB") or "/" in s... | StarcoderdataPython |
1843103 | from selenium import webdriver
from .base import FunctionalTest
from .list_page import ListPage
from .my_lists_page import MyListsPage
def quit_if_possible(browser):
try:
browser.quit()
except:
pass
class SharingTest(FunctionalTest):
def test_can_share_a_list_with_another_user(self):
... | StarcoderdataPython |
8012600 | <filename>code/CM5_racine_main.py
import math
def racine_dicho(x):
min, max, eps = 0, x, 1e-10
while True:
r = (min + max) / 2
if abs(r * r - x) < eps:
break
elif r * r < x:
min = r
else:
max = r
return r
if __name__ == "__main__":
... | StarcoderdataPython |
36771 | """Librerias Importadas"""
from flask import Flask
from flask import render_template
from flask import request
App=Flask(__name__)
@App.route('/')
def index():
"""Pagina Principal en donde se introduce el nombre, apellido, comision"""
return render_template('index.html')
@App.route('/porcentaje',methods=... | StarcoderdataPython |
12858346 | __all__ = ["ComponentTestCase"]
import os
import sys
import yaml
import unittest
from gada import component
from test.utils import TestCaseBase
class ComponentTestCase(TestCaseBase):
def test_load(self):
"""Test loading the testnodes package that is in PYTHONPATH."""
# Load component configuration... | StarcoderdataPython |
8139518 | <reponame>Jingil-Integrated-Management/JIM_backend<filename>apps/drawing/filters.py
import django_filters
from .models import Drawing
class DrawingFilter(django_filters.FilterSet):
created_at = django_filters.DateFilter(
field_name='created_at', lookup_expr='exact')
created_at__lte = django_filters.... | StarcoderdataPython |
3492497 | import coremltools
coreml_model = coremltools.converters.keras.convert('recognizer.h5',
input_names="image",
image_input_names="image",
image_scale=1/255.0,
is_bgr=False,
class_labels = ['Unknown', 'Seat', 'Piece 1', "Piece 2"])
coreml_model.save('FurnitureNet.mlmodel')
| StarcoderdataPython |
70934 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------
# Filename: core.py
# Purpose: plugin for reading and writing Site object into various format
# Author: microquake development team
# Email: <EMAIL>
#
# Copyright (C) 2016 microquake development team
# -------------------... | StarcoderdataPython |
11287882 | <reponame>ebursztein/SiteFab<filename>sitefab/nlp.py<gh_stars>1-10
import numpy as np
from perfcounters import PerfCounters
from tabulate import tabulate
from textacy import TextStats, make_spacy_doc, preprocessing
from textacy.text_stats import readability
from textacy.ke.yake import yake
from textacy.ke.textrank impo... | StarcoderdataPython |
4977574 | <reponame>vaaliferov/119_dls2_nmt
import re
import torch
import telegram
import telegram.ext
import youtokentome as yttm
from plot import *
from config import *
from secret import *
from model import Model
src_tok = yttm.BPE(SRC_TOKENIZER_PATH)
trg_tok = yttm.BPE(TRG_TOKENIZER_PATH)
src_vocab_size = len(src_tok.vocab... | StarcoderdataPython |
3316583 | <gh_stars>10-100
from pathlib import Path
from typing import List
class BaseFileExtractor:
""" Base class for file extraction. """
def __init__(self, extenstion: str) -> None:
self._extenstion = extenstion
@staticmethod
def _check_dir_compliance(path: Path) -> bool:
return all((path.... | StarcoderdataPython |
107531 | PAD = 0
EOS = 1
BOS = 2
UNK = 3
UNK_WORD = '<unk>'
PAD_WORD = '<pad>'
BOS_WORD = '<s>'
EOS_WORD = '</s>'
NEG_INF = -10000 # -float('inf') | StarcoderdataPython |
12838270 | def swap(vet, i, j):
aux = vet[i]
vet[i] = vet[j]
vet[j] = aux
def partition(vet, left, right):
i = left + 1
j = right
pivot = vet[left]
while i <= j:
if vet[i] <= pivot:
i += 1
else:
if vet[j] >= pivot:
j -= 1
else:
... | StarcoderdataPython |
6491695 | import tensorflow as tf
def get_loss_func(phs, prs, pts, nhs, nrs, nts, args):
triple_loss = None
if args.loss == 'margin-based':
triple_loss = margin_loss(phs, prs, pts, nhs, nrs, nts, args.margin, args.loss_norm)
elif args.loss == 'logistic':
triple_loss = logistic_loss(phs, prs, pts, nh... | StarcoderdataPython |
11358641 | #!/usr/bin/env python
from PyZ3950 import zoom
def run ():
conn = zoom.Connection ('amicus.nlc-bnc.ca', 210)
conn.databaseName = 'NL'
q = zoom.Query ('CCL', 'ti="1066"')
ss = conn.scan (q)
for s in ss[0:10]:
print s
if __name__ == '__main__':
run ()
| StarcoderdataPython |
6580893 | import json
import os
from .base_config import BaseConfig
class DiceboxConfig(BaseConfig):
def __init__(self, config_file: str = "dicebox.config"):
super().__init__(config_file=config_file)
###############################################################################
# Data Set Options... | StarcoderdataPython |
4969882 | # Lint as: python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | StarcoderdataPython |
6655927 | <filename>cvpy61.py
print("Gerador de PA")
print("-" * 15)
primeiro_termo = int(input("Primeiro termo: "))
razao_pa = int(input("Razão da PA: "))
soma = primeiro_termo
contador = 10
while contador > 0:
print(f"{soma} -> ", end="")
soma += razao_pa
contador -= 1
if contador == 0:
p... | StarcoderdataPython |
6591106 | <reponame>toxinu/django-bagou
# -*- coding: utf-8 -*-
from message import broadcast
| StarcoderdataPython |
3315576 | #!/usr/bin/env python
from segments.segment import Segment
import vector as vec
import config
import utils
from matplotlib.patches import Arc
from math import sin, cos, radians, degrees, sqrt
def isAngleWithinRange(startAngle, endAngle, pointAngle):
if not (0 <= startAngle <= 360 and 0 <= endAngle <= 360 and 0 <... | StarcoderdataPython |
1934802 | """The django management command sync_from_asana"""
import logging
from asana.error import NotFoundError, InvalidTokenError, ForbiddenError
from django.apps import apps
from django.core.management.base import BaseCommand, CommandError
from djasana.connect import client_connect
from djasana.models import (
Attachm... | StarcoderdataPython |
6575731 | #!/usr/bin/env python
import os
import optparse
from subprocess import Popen
from subprocess import PIPE
class WKOption(object):
"""
Build an option to be used throughout
"""
def __init__(self, name, shortcut, otype=str, action=None, dest=None, default=None, help=None, validate=None, \
... | StarcoderdataPython |
4968007 | Task
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of to , print Not Weird
If n is even and in the inclusive range of to , print Weird
If n is even and greater than , print Not Weird
Input Format
A single line containing a positive ... | StarcoderdataPython |
11295087 | <gh_stars>1-10
##########################################################################
#
# Demonstrate how to create a transaction.
#
# We will need a running bitcoind installation to manage our wallet
# and to retrieve UTXOs
#
# MIT license
#
# Copyright (c) 2018 christianb93
# Permission is hereby granted, free ... | StarcoderdataPython |
5086880 | <gh_stars>0
from django.core.exceptions import ValidationError
class KolibriError(Exception):
pass
class KolibriValidationError(ValidationError, KolibriError):
pass
class KolibriUpgradeError(KolibriError):
"""
Should be used whenever an error arises that is due to an anticipated future incompatibl... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.