id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9673198 | # Generated by Django 2.2.7 on 2019-11-23 15:04
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gobabygo', '0002_hotel_country'),
]
operations = [
migrations.AddField(
model_name='... | StarcoderdataPython |
8013254 | <reponame>edzya/Python_RTU_08_20
my_name = "Valdis" # string data type
# # in Python we need to specifiers for variables
# # DRY - Do not repeat yourself
print(my_name)
print(f"Why hello there {my_name}!") # formatted string from Python 3.6+
print("How are you", my_name, "?")
print(type(my_name))
print("my_name", my_na... | StarcoderdataPython |
1799715 | <reponame>forxhunter/ComputingIntro<gh_stars>1-10
'''
OJ18224: 找魔数 (math), cs10118 Final Exam
http://cs101.openjudge.cn/practice/18224/
'''
m = int(input())
squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961]
magics =... | StarcoderdataPython |
1952798 | <filename>pyccel/parser/syntax/basic.py
# coding: utf-8
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license ... | StarcoderdataPython |
11318384 | <reponame>hassanmohsin/xray-model
import os
import pandas as pd
import torch
from PIL import Image as Im
from torch.utils.data import Dataset
class XrayImageDataset(Dataset):
def __init__(self, annotations_file, img_dir, transform, test_data=False):
self.img_labels = pd.read_csv(annotations_file, dtype={... | StarcoderdataPython |
4828396 | import random
same_list = [[0, 0], [1, 1], [2, 2]]
win_list = [[0, 1], [1, 2], [2, 0]]
lose_list = [[0, 2], [1, 0], [2, 1]]
computer = random.randint(0, 2)
player = input()
if player == "Goo":
player_number = 0
elif player == "Chii":
player_number = 1
elif player == "Par":
player_number = 2
else:
print(... | StarcoderdataPython |
9699980 | <filename>adaptive_interpolation/adapt.py
"""
New adaptive interpolation with better adaptive method
"""
from __future__ import division
import copy
import numpy as np
import numpy.linalg as la
import scipy.special as spec
import scipy.optimize as optimize
class Tree:
def __init__(self, root=0):
... | StarcoderdataPython |
11258533 | <reponame>Voltra/prodLogPy<filename>mainLG.py<gh_stars>0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
sys.path.append("data_analysis/LG/")
sys.path.append("exos/LG")
from writeCsvToSqlite import createTableFromData
import sqlite3
rscPath = "exos/rsc/data/"
csvPath = rscPath + "/csv"
csvFile = lambda x: csvP... | StarcoderdataPython |
1709182 | # pylint: disable=too-few-public-methods
"""
.. module:: test.symbol.elements
:synopsis: Symbol elements test
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import unittest
import pykicadlib.symbol.elements
class TestSymbolElementPinValue(unittest.TestCase):
"""Test function pykicadlib.symbol.elements.pin_value"""
... | StarcoderdataPython |
60178 | <filename>openprescribing/gcutils/tests/test_bigquery.py
import csv
import tempfile
from decimal import Decimal
from google.cloud.exceptions import NotFound
from django.test import TestCase
from gcutils.bigquery import Client, TableExporter, build_schema
from gcutils.storage import Client as StorageClient
from dmd.m... | StarcoderdataPython |
1697890 | <gh_stars>10-100
import psspy_import
import power_system
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib import gridspec
import dyntools
import numpy
import random
from scipy import misc
def getFrequencyDeviation(channel_file):
chan = dyntools.CHNF(channel_file)
short_title, chanid_dict, ... | StarcoderdataPython |
1753722 | <filename>src/day7/day7.py
# --- <Do not edit> ---
def getInputLines():
import sys
if len(sys.argv) < 1:
raise ValueError('Path of this script not available in sys.argv')
lines = []
inputFilePath = sys.argv[0].replace('day7.py', 'input.txt')
with open(inputFilePath) as f:
lines = [... | StarcoderdataPython |
3361313 | <reponame>ManishShah120/news-scrap
from django.shortcuts import render , redirect
from .forms import UserForm
from django.contrib.auth import logout, authenticate
from django.contrib import messages
def register(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_... | StarcoderdataPython |
6482256 | import ast
import builtins
from typing import List, Set, Dict, Any
__all__ = ['CheckUsedGlobals']
class CheckUsedGlobals(ast.NodeVisitor):
builtins = dir(builtins)
def __init__(self):
self.modules: Set[str] = set()
self.imported: Set[str] = set()
self.args: Set[str] = set()
s... | StarcoderdataPython |
9686200 | <reponame>jbochi/python-zombie
from pythonzombie.proxy.server import ZombieProxyServer
from simplejson import loads, dumps
from unittest import TestCase
import cStringIO
import fudge
import subprocess
import os
class FakeNode(object):
def __json__(self):
retu... | StarcoderdataPython |
6684496 | <gh_stars>0
import os
import time
from selenium.webdriver.support.select import Select
from Data.parameters import Data
from get_dir import pwd
from reuse_func import GetData
class DistrictBlockCluster_donwloadcsv():
def __init__(self, driver):
self.driver = driver
def remove_csv(self):
os.r... | StarcoderdataPython |
6450671 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
3392224 | from django.utils.translation import gettext_lazy as _
import logging
from smsapi.client import SmsApiPlClient
from smsapi.exception import SmsApiException
from trench.backends.base import AbstractMessageDispatcher
from trench.responses import (
DispatchResponse,
FailedDispatchResponse,
SuccessfulDispatch... | StarcoderdataPython |
6656157 | <filename>waferscreen/inst_control/inactive/serial_instrument.py
'''
Created on Feb 17, 2010
@author: schimaf
@version: 1.0.1
1.0.1 Show warning if serial port does not actually exist.
'''
#import time
import instrument
from named_serial import Serial
import serial
import numpy as np
import time
class SerialInstr... | StarcoderdataPython |
5042899 | <reponame>saheedniyi02/flask-<filename>blog/models.py
from datetime import datetime
from flask_login import UserMixin,current_user
from blog import db,login_manager,app
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
@login_manager.user_loader
def load_user(user_id):
return User.query.get(in... | StarcoderdataPython |
1675463 | import numpy as np
import pandas as pd
import sys
from sklearn import preprocessing
from sklearn import linear_model
from sklearn.grid_search import GridSearchCV
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics impo... | StarcoderdataPython |
9794305 | <filename>solutions/Remove Outermost Parentheses/solution.py<gh_stars>1-10
class Solution:
def removeOuterParentheses(self, S: str) -> str:
res, opened = [], 0
for c in S:
if c == '(' and opened > 0: res.append(c)
if c == ')' and opened > 1: res.append(c)
opened +... | StarcoderdataPython |
9683111 | <reponame>Erotemic/misc
def benchmark_math_vs_numpy():
import math
import numpy as np
import timerit
ti = timerit.Timerit(100000, bestof=100, verbose=2)
for timer in ti.reset('np.isclose'):
x = np.random.rand() * 1000
with timer:
np.isclose(x, 0)
for timer in ti.r... | StarcoderdataPython |
3575246 | from itertools import combinations, chain
from collections import defaultdict
f = open("input.txt")
d = f.readlines()
boss_dict = {}
for l in d:
s = l.split(":")
if ("Hit" in s[0]):
boss_dict["HP"] = int(s[1])
else:
boss_dict[s[0]] = int(s[1])
shop_txt = """Weapons: Cost Damage Armor
D... | StarcoderdataPython |
1979586 | """Constants for the Logbook Cache integration."""
DOMAIN = "logbook_cache"
NAME = "Logbook Cache"
CACHE_DAYS = "cache_days"
ONLY_CACHE = "only_cache"
DEFAULT_CACHE_DAYS = 2
DEFAULT_ONLY_CACHE = False
| StarcoderdataPython |
6468614 | import json
from django.db import transaction
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View... | StarcoderdataPython |
8188189 | #!/usr/local/bin/python3
"""Task
You are in charge of the cake for your niece's birthday and have decided the cake will have one candle for each year of her total age.
When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blo... | StarcoderdataPython |
4925747 | <filename>src/04/sign_message_der.py<gh_stars>0
# Created by always0ne on 2020.09.24
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA
def sign_message_der():
# generate RSA Key
key_pair = RSA.generate(3072)
# save private/public key on DER
with open("private.de... | StarcoderdataPython |
6666006 | <reponame>ChrisUnsworth/Life
from UI.Life_window import LifeWindow
LifeWindow.new(LifeState.random_state(25, 0.4))
| StarcoderdataPython |
383675 | from heapq import heappush, heappop
from typing import Dict, List, Any
from mapfmclient import MarkedLocation
from src.util.coordinate import Coordinate
from src.util.grid import Grid
class Heuristic:
"""
Contains the precomputed heuristic function. Values are computed when instance is constructed.
"""
... | StarcoderdataPython |
1843232 | import torch
from torch.utils.data import Dataset
"""
This file is to be removed in a coming fix. Don't use any of its methods.
"""
def train(epoch, tokenizer, model, device, loader, val_loader, optimizer, testing=True):
model.train()
running_loss = 0.0
for _, data in enumerate(loader, 0):
y = da... | StarcoderdataPython |
6647295 | <filename>source/FnAssetAPI/ui/dialogs/TabbedBrowserDialog.py
from __future__ import with_statement
import types
from ... import logging
from ...SessionManager import SessionManager
from ..toolkit import QtGui, QtWidgets
from ..constants import kBrowserWidgetId, kBrowserWidgetName
from ...core.decorators import debu... | StarcoderdataPython |
5023715 | <filename>quex/engine/analyzer/examine/TEST-later/test-prepare_cautious_recipes.py<gh_stars>0
#! /usr/bin/env python
#
# PURPOSE: Test the production of a cautious recipe for acceptance considerations.
#
# Details on 'cautious recipes' see [DOC]. Brief: A cautious recipe is a recipe
# for a mouth state, that actually h... | StarcoderdataPython |
11292673 | <filename>matrix.py
"""
@author: descentis
http://sccilabs.org/amit_verma.html
"""
a,b=map(int,input().split())
count=1
m = []
for i in range(1,a+1):
l = []
for j in range(1,b+1):
l.append(count)
count+=1
m.append(l)
for i in range(a):
for j in range(b):
if(j==b-1):
... | StarcoderdataPython |
5048106 | import torch.nn as nn
import torch.nn.functional as F
#Idea comes from Dreamer v2
#https://arxiv.org/pdf/2010.02193.pdf, page 3
#They used stochastic neuron, Following code is deterministic
class BinaryLayer(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
#First return is no... | StarcoderdataPython |
344942 | <reponame>parkerwray/smuthi-1<filename>smuthi/version.py
major = 1
minor = 0
micro = None
pre_release = ".alpha"
post_release = None
dev_release = None
__version__ = '{}'.format(major)
if minor is not None:
__version__ += '.{}'.format(minor)
if micro is not None:
__version__ += '.{}'.format(micro)
if pre_r... | StarcoderdataPython |
3524792 | # %% [markdown]
"""
# Obstacle Avoid
_Coming Soon_
To run the example, use the following command:
```shell
python examples/control/obstacle_avoid.py
```
"""
| StarcoderdataPython |
3315522 | <gh_stars>10-100
## Transfer cifar10 lmdb data to mat
import sys
import lmdb
import numpy as np
from array import array
import scipy.io as sio
import os
if os.path.exists('../caffe'):
sys.path.append('..')
else:
print 'Error : caffe(pycaffe) could not be found'
import caffe
from caffe.proto import caffe_pb2
#T... | StarcoderdataPython |
3295758 | <filename>tests/unit/test_builder.py
from unittest import TestCase
from design_patterns.builder.html_builder import HtmlBuilder
from design_patterns.builder.html_element import HtmlElement
class TestHtmlBuilder(TestCase):
def setUp(self) -> None:
self.html_builder = HtmlBuilder(HtmlElement("ul"))
... | StarcoderdataPython |
3223899 | from minibench import Benchmark
from faker import Faker
from flask import Flask
from flask_restplus import fields, Api, Resource
from flask_restplus.swagger import Swagger
fake = Faker()
api = Api()
person = api.model('Person', {
'name': fields.String,
'age': fields.Integer
})
family = api.model('Family', ... | StarcoderdataPython |
6666517 | import os
import nappy.nc_interface.na_to_nc
import nappy.nc_interface.nc_to_na
import cdms2 as cdms
print "Converting NAFile to NC file 1010.na"
ncfile = os.path.join(os.path.dirname(__file__), "../test_outputs/1010.nc")
nafile = os.path.join(os.path.dirname(__file__), "../data_files/1010.na")
ncOutFile = os.path.jo... | StarcoderdataPython |
210584 | <filename>codewars/8kyu/dinamuh/TotalAmount/test.py
from main import points
def test_points(benchmark):
assert benchmark(points, ['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']) == 30
assert benchmark(points, ['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']) == 10
... | StarcoderdataPython |
5069998 | <reponame>youwol/flux-backend
import os
from config_common import on_before_startup, cache_prefix
from youwol_flux_backend import Configuration, Constants
from youwol_utils import StorageClient, DocDbClient, AuthClient, CacheClient, get_headers_auth_admin_from_env
from youwol_utils.clients.assets_gateway.assets_gate... | StarcoderdataPython |
143671 | <filename>insights/components/rhel_version.py<gh_stars>0
"""
IsRhel6, IsRhel7 and IsRhel8
===============================
The ``IsRhel*`` components each use the ``RedhatRelease`` combiner to
retrieve the RHEL version information.
Each component checks if the release version matches the version it represents,
if the v... | StarcoderdataPython |
8031997 | #! /usr/bin/env python3
import os
import sys
# add pymol to the python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib/python3.7/site-packages'))
import pymol
def hamming(s1, s2):
'''Calculate the Hamming distance between two strings.
:param str s1: the first string.
:param str s2: ... | StarcoderdataPython |
5119038 | <filename>tools/prepare_mac_stm32cubeide_env.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
hdirs = [
"tiny/osal/cmsis_os",
"tiny/arch/arm/arm-v7m/common/include",
"tiny/arch/arm/arm-v7m/cortex-m0+/gcc",
"tiny/arch/arm/arm-v7m/cortex-m3/gcc",
"tiny/arch/arm/arm-v7m/cortex-m4... | StarcoderdataPython |
5135573 | <filename>django_cowhite_cms/tests.py
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from .models import *
import datetime
class Common(TestCase):
def setUp(self):
User = get_user_model()
... | StarcoderdataPython |
6474530 | """
Tests for xmodule.x_module.ResourceTemplates
"""
import unittest
from xmodule.x_module import ResourceTemplates
class ResourceTemplatesTests(unittest.TestCase):
"""
Tests for xmodule.x_module.ResourceTemplates
"""
def test_templates(self):
expected = {
'latex_html.yaml',
... | StarcoderdataPython |
5066920 | <filename>plot.py<gh_stars>0
import sys
import pandas as pd
import matplotlib.pyplot as plt
def _plot_latency_data(src_file: str, dst_file: str) -> None:
df = pd.read_csv(src_file, index_col='datetime', parse_dates=True).fillna(0)
df['lte_modem_latency'].plot(label='lte_modem_latency')
df['5G_modem_latenc... | StarcoderdataPython |
5116125 | <filename>examples/notebooks-py/tesedmlExample.py
# coding: utf-8
# Back to the main [Index](../index.ipynb)
# ### tesedml
# Simulations can be described within SED-ML, the Simulation Experiment Description Markup Language (http://sed-ml.org/). SED-ML is an XML-based format for encoding simulation setups, to ensure ... | StarcoderdataPython |
4860138 | import json
from json import JSONDecodeError
from typing import Dict, Union
from dataclasses import dataclass, asdict
@dataclass
class GroovyScriptRequestModel(object):
name: str
content: str
type: str = "groovy"
def to_dict(self):
return asdict(self)
@dataclass
class GroovyScriptResponseM... | StarcoderdataPython |
11255540 | from app.databases import MongoDB
import random
class MongoFuncs(MongoDB):
def __init__(self, con_str):
super().__init__(con_str)
# обьявим словарь с дефолтными данными для выборки из бд
self.params = {
'order': '_id',
'offset': 0,
'limit': 5
}... | StarcoderdataPython |
3469104 | <reponame>kroniidvul/mpiigaze_project
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 16:14:34 2019
@author: iamav
"""
import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as F
import torch
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
... | StarcoderdataPython |
6458523 | from __future__ import absolute_import
from .lib.v2_0 import V2_0
from .lib.lite import Lite
def ContextIO(consumer_key, consumer_secret, **kwargs):
if kwargs.get("api_version") == "lite":
return Lite(consumer_key, consumer_secret, **kwargs)
elif kwargs.get("api_version") == "app":
return App(co... | StarcoderdataPython |
6443012 | <filename>python/phonenumbers/data/region_BO.py
"""Auto-generated file, do not edit by hand. BO metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BO = PhoneMetadata(id='BO', country_code=591, international_prefix='00(1\\d)?',
general_desc=PhoneNumberDesc(national_n... | StarcoderdataPython |
12822426 | import json
import os
import time
from gym import error
from gym.utils import atomic_write
class StatsRecorder(object):
def __init__(self, directory, file_prefix):
self.initial_reset_timestamp = None
self.directory = directory
self.file_prefix = file_prefix
self.episode_lengths = [... | StarcoderdataPython |
257120 | <reponame>PPM-Robotics-AS/blackbox_main
#!/usr/bin/python
"""
BLACKBOX
Version 0.0.1, March 2019
http://rosin-project.eu/ftp/blackbox
Copyright (c) 2019 PPM Robotics AS
This library is part of BLACKBOX project,
the Focused Technical Project BLACKBOX - an automated trigger-based
reporting, data recording and playbac... | StarcoderdataPython |
358429 | <gh_stars>1-10
import os,sys
import numpy as np
from tensorflow.python.keras.applications.resnet50 import ResNet50
from tensorflow.python.keras.preprocessing import image
from tensorflow.python.keras.applications.resnet50 import preprocess_input, decode_predictions
def GetLabel(path):
file = open(path)
filena... | StarcoderdataPython |
166717 | <filename>user/models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from common.currencies import CURRENCIES
class UserProfile(models.Model):
"""User profile for extending default django User model"""... | StarcoderdataPython |
6549710 | <gh_stars>0
import os
import numpy as np
import h5py
import datetime
import multiprocessing as mp
def XY2LONLAT(x, y, a=6378137.0, e=0.08181919, phi_c_deg=70.0, lambda_0_deg=-45.0):
"""
This is a Python version of the MATLAB code from
https://www.mathworks.com/matlabcentral/fileexchange/32907-polar-stereo... | StarcoderdataPython |
211176 | import pytest
from web3.utils.abi import (
function_abi_to_4byte_selector,
)
@pytest.fixture(autouse=True)
def wait_for_first_block(web3, wait_for_block):
wait_for_block(web3)
@pytest.fixture()
def math_contract(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME, MATH_SOURCE,
wait_for_transaction):
... | StarcoderdataPython |
1953838 | # coding: utf-8
import sys
import logging
import sublime
# set up some logging
logging.basicConfig(level=logging.WARNING, format="[%(asctime)s - %(levelname)-8s - %(name)s] %(message)s")
logger = logging.getLogger('SublimeLegit')
# reload modules if necessary
LOAD_ORDER = [
# base
'',
'.util',
'.cmd'... | StarcoderdataPython |
4961783 | from ..models import Item
from .. import Session
class ItemsMethods:
def __init__(self):
self.__session = Session()
def add_item(self, item: Item) -> Item:
self.__session.add(item)
self.__session.commit()
return item
def get_item(self, **kwargs) -> Item:
... | StarcoderdataPython |
8026228 | #!/usr/bin/env python
#
# File: $Id: forms.py 1557 2008-07-25 01:24:03Z scanner $
#
"""
This module defines some forms fields that we want to centralize
in one area.
"""
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django import f... | StarcoderdataPython |
3524321 | #!/usr/bin/python3
from urllib.parse import urlparse
from gmapi import api
import gmapi, shlex, sys, http.client, http.server, json, cmd
def fetchPastebin(fileId):
conn = http.client.HTTPSConnection('pastebin.com')
conn.request('GET', '/raw/%s' % fileID, None, {'User-agent': 'gmapi',
'Accept': '*/*'})... | StarcoderdataPython |
1874103 | import socket
import struct
import sys
if len(sys.argv) != 3:
sys.exit(0)
ip = sys.argv[1]
port = int(sys.argv[2])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "[+] Attempting connection to " + ip + ":" + sys.argv[2]
sock.connect((ip, port))
dsi_payload = "\x00\x00\x40\x00" # client quantum
dsi_pa... | StarcoderdataPython |
3338365 | """Data Templates"""
def makeDataFrame(accuracy, altitude, latitude, longitude, provider ,timestamp ,pulse ,temperature, humidity, pressure):
"""Generate JSON data frame of detector event"""
frame = {
"accuracy": accuracy,
"altitude": altitude,
"latitude": latitude,
"longitude": ... | StarcoderdataPython |
3499130 | import torch
import torch.distributions as td
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.distributions import constraints
from torch.distributions.exp_family import ExponentialFamily
from itertools import product
import numpy as np
class MaskedDirichlet(td.D... | StarcoderdataPython |
5177737 | <gh_stars>0
from distutils.core import Extension
from astropy_helpers import setup_helpers
def get_extensions():
exts = []
cfg = setup_helpers.DistutilsExtensionArgs()
cfg['include_dirs'].append('gala')
cfg['extra_compile_args'].append('--std=gnu99')
cfg['sources'].append('gala/cconfig.pyx')
e... | StarcoderdataPython |
5059860 | import tensorflow as tf
from model import Model, TwoHot
from loss_funcs import softmax_cross_entropy_with_logits_loss
class CNT(Model):
def __init__(self, hps, verbose=False, logdir=None,
loss_func=softmax_cross_entropy_with_logits_loss):
self.restore = False
self.learning_rate = ... | StarcoderdataPython |
3401056 | <reponame>ashish-greycube/bglstore<filename>bglstore/item_controller.py
from __future__ import unicode_literals
import frappe
from frappe import throw, _
import io
from barcode import Code128
from barcode.writer import SVGWriter
from frappe.model.naming import make_autoname
# from bglstore.item_controller import reset... | StarcoderdataPython |
1916650 | <filename>metric_wsd/models/context_encoder.py<gh_stars>1-10
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from transformers import BertTokenizerFast, BertModel, BertConfig
from metric_wsd.config import Config
config = Config()
def get_subtoken_indecies(text_tokens, offset_ma... | StarcoderdataPython |
380951 | """
The SQLite table definitions. See the [Schema](../Schema.md) documentation for more details.
"""
import sys
import argparse
from pppf_databases import database_handles
from pppf_accessories import color
def define_genome_table(conn, verbose=False):
"""
Define the genome table
:param conn: The databas... | StarcoderdataPython |
3254700 | import pytest
from pytestqt.qt_compat import qt_api
from random import random
from app import MainWindow
# TODO: Add this when project saves stack too
# def test_stack(app, qtbot, delay=25):
# test_poly_tool(app, qtbot, delay=10)
# for _ in range(0, 100):
# app.interface.scene.stack.setIndex(int(rando... | StarcoderdataPython |
3329904 | # import argparse
import csv
# import datetime
# import difflib
# import os
# import pprint
import re
import time
# import timeit
# import warnings
from time import sleep
# import matplotlib.pyplot as plt
# import matplotlib.ticker as ticker
import numpy as np
import pandas as pd
import requests
from bs4 import Beauti... | StarcoderdataPython |
11334766 | #!/usr/bin/env python3
from datetime import timedelta
import arrow
import dateutil
import pandas as pd
import requests
from parsers.lib.config import refetch_frequency
@refetch_frequency(timedelta(days=1))
def fetch_production(zone_key='TW', session=None, target_datetime=None, logger=None) -> dict:
if target_date... | StarcoderdataPython |
11261532 | <filename>examples/agorabackend.py
import json
import urllib2
from bs4 import BeautifulSoup
from flask import Flask
from flask import request
import requests
from PIL import Image
import pytesseract
import cv2
import os
import re
from autocorrect import spell
from binascii import a2b_base64
from flask_cors import CORS,... | StarcoderdataPython |
8132190 | <gh_stars>1-10
import matplotlib.pyplot as plt
import numpy as np
from structure_factor.point_processes import ThomasPointProcess
from structure_factor.spatial_windows import BallWindow
point_process = ThomasPointProcess(kappa=1 / (20 * np.pi), mu=20, sigma=2)
window = BallWindow(center=[-20, -10], radius=50)
point_... | StarcoderdataPython |
4904790 | """Test for the client module."""
import pytest
import theoneapi_sdk
def test_missing_token_client_init():
"""Test the client init."""
with pytest.raises(ValueError) as excinfo:
theoneapi_sdk.Client()
assert str(excinfo.value) == "Token is required."
| StarcoderdataPython |
369801 | class ControllerToWorkerMessage(object):
"""
Class defines the message sent from the controller to the workers. It takes
a task as defined by the user and then sends it. This class assumes that the
generated tasks are PICKLEABLE although it does not explicitly check.
"""
TASK_KEY = "task"
... | StarcoderdataPython |
1822039 | <reponame>angelitabrg/lih_lab_python2
'''
Exercício 1: Lista ordenada
Escreva a função ordenada(lista), que recebe uma lista com números inteiros como parâmetro e
devolve o booleano True se a lista estiver ordenada e False se a lista não estiver ordenada.
''' | StarcoderdataPython |
1677230 | """
Question 61 :
Write a special comment to indicate a python source code file is
in unicode.
"""
# Solution :
# _*_ coding: utf-8 _*_
| StarcoderdataPython |
1670409 | import datetime
import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(user='root', password='<PASSWORD>',
host='127.0.0.1',
database='northwind')
except mysql.connector.Error as err:
if er... | StarcoderdataPython |
5106458 | fh = open('Python/romeo.txt')
lst = list()
for line in fh:
word= line.rstrip().split()
for element in word:
if element in lst:
continue
else :
lst.append(element)
... | StarcoderdataPython |
4866868 | <filename>algorithm/insertion_sort/insertion_sort.py
#input: crumble array
#ouput: sort array
#algorithm : Insertion Sort
#complexity : O(n2)
"""
the first element is considered as sorted
Ok now, you get the second element
la idea es tomar un numero y compararlo con el anterior hasta encontrarle un lugar
"""
... | StarcoderdataPython |
12841517 | <reponame>alstn2468/Django_Airbnb_Clone
from core.management.commands.custom_command import CustomCommand
from rooms.models import Amenity
class Command(CustomCommand):
help = "Automatically create amenities"
def handle(self, *args, **options):
try:
amenities = [
"Air cond... | StarcoderdataPython |
6646298 | <gh_stars>1000+
# Generated by Django 3.1.12 on 2021-08-20 16:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ml', '0003_auto_20210309_1239'),
]
operations = [
migrations.AddField(
model_name='mlbackend',
name... | StarcoderdataPython |
1876795 | import pandas as pd
import xgboost
from xgboost import XGBRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from learntools.core import *
# Load the data
X = pd.read_csv('../input/train.csv', index_col='Id')
X_test_full = pd.read_csv('../input/test.csv', in... | StarcoderdataPython |
5193382 | print "|-------------------------------------------------|"
print "| retarget-motions-toolkit.py |"
print "|-------------------------------------------------|"
def remapSkeleton(skelName, jointMapName):
remapSkel = scene.getSkeleton(skelName)
jointMapManager = scene.getJointMapManager()
j... | StarcoderdataPython |
5107916 | <filename>forceDAQ/daq/_daq_read_Analog_dummy.py
__author__ = '<NAME>'
import numpy as np
import logging
from .._lib.timer import Timer
from ._config import NUM_SAMPS_PER_CHAN, TIMEOUT, NI_DAQ_BUFFER_SIZE
class DAQReadAnalog(object):
NUM_SAMPS_PER_CHAN = NUM_SAMPS_PER_CHAN
TIMEOUT = TIMEOUT
NI_DAQ_BUFFER... | StarcoderdataPython |
32034 | <reponame>reinzor/selfieboot2016
'''
Selfiebooth <NAME> 2016 - CameraPuzzle
===========================
This demonstrates using Scatter widgets with a live camera.
You should see a shuffled grid of rectangles that make up the
camera feed. You can drag the squares around to see the
unscrambled camera feed or double cli... | StarcoderdataPython |
3549410 | <gh_stars>0
import os
import numpy as np
import skimage.io
import matplotlib.pyplot as plt
from scipy.ndimage import binary_dilation
from utils.cmaps import default_cmap
from utils.windows import normalize_data
from utils.inference import center_crop, pad_if_needed
FOV = 256
PRED_DIR = r"E:\Dropbox\Work\Other projects... | StarcoderdataPython |
8187162 | # -*- coding: utf-8 -*-
#
# django-codenerix
#
# Codenerix GNU
#
# Project URL : http://www.codenerix.com
#
# 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/LI... | StarcoderdataPython |
4964070 | #!coding=utf8
from __future__ import print_function
import sys, codecs
import tensorflow as tf
from argparse import ArgumentParser
from tagger import Model
class FlushFile:
"""
A wrapper for File, allowing users see result immediately.
"""
def __init__(self, f):
self.f = f
def write(self... | StarcoderdataPython |
391926 | from numpy.lib.financial import nper
from pandas.core.frame import DataFrame
from engine.core.SystemEntity import SystemEntity
from engine.core.JourneyEntity import journeys_to_features_sources_dataframe
from engine.core.SourceEntity import sources_to_dataframe
from engine.core.SquadEntity import squads_to_features_dat... | StarcoderdataPython |
5079644 | from typing import Optional, Tuple
import numpy as np
import torch
from torch import nn, Tensor
from conformer.modules.attention import MultiHeadAttention
class ConformerDecoder(nn.Module):
""" Conformer decoder """
def __init__(
self,
vocab_size: int,
hidden_size: int =... | StarcoderdataPython |
4886325 | from skyjump.config import MUTED, SOUND_VOLUME, DATA_DIR
import time
import pygame
from os import path
from threading import Thread
def play_sound(sound_file: str, pause: bool = False):
"""play the sound file if the volume is on
:param sound_file: the file of the sound
:param pause: if the music should b... | StarcoderdataPython |
104116 | <reponame>KI-cker/Ki-cker
import logging
from kicker.storage.storage import Storage
def storage_worker(queue, config, filename='games.h5'):
s = Storage(config, filename=filename)
while True:
frame, action = queue.get(True)
if frame is None:
logging.debug('break')
break... | StarcoderdataPython |
8017762 | import unittest
import os
from generate_io_classes_file_from_source import *
from mapping_classes import OutputClass
import sqlalchemy as sa
class TestClassGeneration(unittest.TestCase):
def setUp(self):
if os.path.exists("./test/test.db3"):
os.remove("./test/test.db3")
with open("... | StarcoderdataPython |
1648576 | <filename>framework/generated/vulkan_generators/vulkan_replay_consumer_body_generator.py
#!/usr/bin/python3 -i
#
# Copyright (c) 2018-2020 Valve Corporation
# Copyright (c) 2018-2020 LunarG, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documenta... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.