id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
1766600 | """
Code that processes SQL files and returns modules of database functions.
"""
from . import parser, context
from .exceptions import NoConnectionError
from contextlib import contextmanager
from glob import glob
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import threading
imp... | StarcoderdataPython |
1690895 | <reponame>Syunkolee9891/Mayan-EDMS<filename>mayan/apps/document_states/links.py
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from mayan.apps.documents.permissions import permission_document_type_edit
from mayan.apps.navigation.classes import Link
from .permissions i... | StarcoderdataPython |
1778709 | """
process_your_images.py (author: <NAME> / git: ankonzoid)
Process your images in the `input` directory using any of the following techniques.
The results
Standard techniques:
1) Force resizing (ypixels, xpixels) -> (ypixels_force, xpixels_force)
2) Grey scaling (3 rgb channels -> 1 greyscale channel)
... | StarcoderdataPython |
4835148 | <reponame>hamed1361554/recipe-app-api
from django.contrib.auth import get_user_model
from django.test import TestCase
from rest_framework.reverse import reverse
from rest_framework.test import APIClient
import rest_framework.status as status
TOKEN_URL = reverse('users:token')
def create_user(**kwargs):
return ... | StarcoderdataPython |
6514978 | from pyridge.generic.scaler import Scaler
import numpy as np
class StandardScaler(Scaler):
"""
Scaler for data, similar to StandardScaler from
sklearn but avoiding shape restrictions.
"""
def __init__(self):
self.mean_: np.float
self.std_: np.float
def get_params(self):
... | StarcoderdataPython |
5003504 | # -*- coding: utf-8 -*-
# Created on Sun Jul 19 18:10:11 2020
#
# Copyright 2020 <NAME>. 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/li... | StarcoderdataPython |
3406764 | <filename>api/cron.py<gh_stars>1-10
import redis
from .models import Patch
from django.db import transaction
@transaction.atomic
def store_from_redis():
pool = redis.ConnectionPool(host="127.0.0.1", port=6379, max_connections=10)
rds = redis.Redis(connection_pool=pool)
for patch in Patch.objects.select_f... | StarcoderdataPython |
1909989 | import argparse
import sys
from typing import List, Tuple, Set, Union
# Part 1
def two_sum(lst: List[int], total: int) -> Union[Tuple[int, int], None] :
container: Set[int] = set()
for num in lst:
if total - num in container:
return (num, total - num)
else:
container.a... | StarcoderdataPython |
8002957 | import time
while(True):
print 'hello'
time.sleep(2)
| StarcoderdataPython |
5099748 | <reponame>terop/latexbot
#!/usr/bin/env python3
"""A program (bot) for rendering short snippets of LaTeX code as an image.
A LaTeX distribution needs to be installed on the machine where this code
is ran."""
import sys
from io import BytesIO
from tempfile import NamedTemporaryFile
from os.path import basename
from os ... | StarcoderdataPython |
3473684 | <reponame>ManuelAlvarezC/keyboard-anywhere
# -*- coding: utf-8 -*-
"""Top-level package for keyboard_anywhere."""
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.0.0.dev0'
| StarcoderdataPython |
4863915 | '''
URL: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
Time complexity: O(n)
Space complexity: O(1)
'''
class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
if len(p... | StarcoderdataPython |
9714069 | import hashlib
import json
import time
from command import buildcmd
from common import *
def sifchain_denom_hash(network_descriptor, token_contract_address):
assert on_peggy2_branch
assert token_contract_address.startswith("0x")
s = str(network_descriptor) + token_contract_address.lower()
return "sif"... | StarcoderdataPython |
9722709 | from abc import ABCMeta, abstractmethod
class BaseInsSegModel(metaclass=ABCMeta):
"""Base model. The model object must inherit form this class."""
def __init__(self, project_id, data_dir, **kwargs):
"""
:param project_id: The project id that use this model.
:param trai... | StarcoderdataPython |
6621735 | <gh_stars>1-10
import sys
sys.path.append(__path__[0])
from mef90EXODUS import *
from mef90ABAQUS import *
from mef90GMSH import *
from mef90MSC import * | StarcoderdataPython |
8087013 | #!/bin/env/python
#-*- encoding: utf-8 -*-
"""
"""
from __future__ import print_function, division
import os
def main():
# OSX Cleanup
dirpath = os.path.dirname(os.path.abspath(__file__))
for root, dirs, files in os.walk(dirpath):
for d in dirs:
if d in ['__pycache__']:
... | StarcoderdataPython |
3256178 | from django.urls import reverse
from django.test import TestCase
from sso.organisations.models import OrganisationCountry
from sso.test.client import SSOClient
class AccountsTest(TestCase):
fixtures = ['roles.json', 'test_l10n_data.json', 'app_roles.json', 'test_organisation_data.json', 'test_app_roles.json', 'te... | StarcoderdataPython |
8175030 | from __future__ import print_function
from traceback import print_tb
from tk_utils import *
from imutils.video import VideoStream
import time,subprocess
out = "/home/nishantg96/ZeMA/"
rospy.init_node('myNodeName')
# cam = VideoStream(src=0,resolution=(1280,720)).start()
# cam2 = VideoStream(src=1,resolution=(1280,720)... | StarcoderdataPython |
4821129 | <reponame>jsatt/python-catalog
#!/usr/bin/env python
from setuptools import setup
long_description = open('README.rst').read()
setup_args = dict(
name='pycatalog',
version='1.2.0',
description='Data structure for complexe enumeration.',
long_description=long_description,
author='<NAME>',
auth... | StarcoderdataPython |
3576024 | <filename>addons/website_sale_stock/controllers/main.py
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_sale.controllers.main import WebsiteSale
from odoo import http,_
from odoo.http import request
from odoo.exceptions import ValidationError
... | StarcoderdataPython |
5122028 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from scipy.sparse import csr_matrix, identity, kron
from scipy.sparse.linalg import eigs, eigsh
import itertools
from scipy.linalg import block_diag, eig, expm, eigh
from scipy.sparse import save_npz, load_npz, csr_matrix, csc_matrix
import scipy.spar... | StarcoderdataPython |
5106749 | """Miscellaneous API handlers."""
import copy
from typing import Dict, Any, AnyStr
from aiohttp import web
from dependency_injector.wiring import Provide
from newsfeed.containers import Container
async def get_status_handler(_: web.Request) -> web.Response:
"""Handle status requests."""
return web.json_res... | StarcoderdataPython |
8077303 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 10:02:05 2019
@author: yoelr
"""
import biosteam as bst
__all__ = ('load_process_settings',)
# %% Process settings
def load_process_settings():
bst.process_tools.default_utilities()
bst.CE = 607.5 # 2019
bst.PowerUtility.price = 0.065
HeatUtility = b... | StarcoderdataPython |
3399385 | <filename>armory/scenarios/multimodal_so2sat_scenario.py
"""
Multimodal image classification, currently designed for So2Sat dataset
"""
import copy
import logging
import numpy as np
from armory.utils import metrics
from armory.scenarios.scenario import Scenario
logger = logging.getLogger(__name__)
class So2SatCla... | StarcoderdataPython |
3565642 | <reponame>mamaheux/bass-amplifier<filename>tools/signal_processing/ui/utils/gain_plot_widget.py
import matplotlib.pyplot as plt
from PySide2.QtWidgets import QWidget, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
class GainPlotWidget(QWidget):
def __init__(self, min_frequency=10, m... | StarcoderdataPython |
1649018 | <filename>akill.py
from __future__ import print_function
__module_name__ = 'AKILL script'
__module_version__ = '0.1'
__module_description__ = 'AKILL oper script for Atheme and forks services packages'
__author__ = '<NAME>.'
import hexchat
help_hook = "\"/sakill <nick|hostmask> <public reason> | <private oper reason... | StarcoderdataPython |
68172 | class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if len(grid) <= 0 or grid is None:
return 0
rows = len(grid)
cols = len(grid[0])
for r in range(rows):
for c in range(cols):
if r==0 and c==0:
con... | StarcoderdataPython |
6539102 | """
This script makes Figure 2: a dial plot of the microburst width as a
function of L and MLT
Parameters
----------
catalog_name: str
The name of the catalog in the config.PROJECT_DIR/data/ directory.
r2_thresh: float
The adjusted R^2 threshold for the fits. I chose a default value of 0.9.
max_width_ms: floa... | StarcoderdataPython |
5044313 | <filename>thortils/utils/math.py
import random
import numpy as np
import math
from scipy.spatial.transform import Rotation as scipyR
# Operations
def remap(oldval, oldmin, oldmax, newmin, newmax, enforce=False):
newval = (((oldval - oldmin) * (newmax - newmin)) / (oldmax - oldmin)) + newmin
if enforce:
... | StarcoderdataPython |
8084108 | """Unit test package for gpdre."""
| StarcoderdataPython |
1665527 | <reponame>samarthg/jira-scrum-update-automation<filename>fabfile.py
from fabric.api import local
def hello():
print("hi there")
def prepare_patch():
local("bumpversion patch")
def prepare_minor():
local("bumpversion minor")
def prepare_major():
local("bumpversion major")
def release():
local("g... | StarcoderdataPython |
6487218 | """
==========================================================================
TorusRouterFL.py
==========================================================================
FL route unit that implements dimension order routing.
Author : <NAME>
Date : June 30, 2019
"""
from pymtl3 import *
from .directions import *
fr... | StarcoderdataPython |
1646657 | """
Entendendo o *args
- O *args é um parâmetro, como outro qualquer. Isso significa que você poderá
charmar de qualquer coisa, desde que começe com asterisco.
Exemplo:
*xis
Mas por convenção, utilizamos *args para definí-lo
Mas o que é o *args?
O parâmetro *args utilizado em uma função, coloca os valores extras... | StarcoderdataPython |
1821094 | """
Print inconsistencies to give to and try to force mods to fix
"""
import json
from pathlib import Path
import process_artists.config1_exceptions
song_database = Path("../app/data/expand_mapping.json")
with open(song_database, encoding="utf-8") as json_file:
song_database = json.load(json_file)
for exception... | StarcoderdataPython |
68053 | # -*- mode: python -*-
#!/usr/bin/env sage
import sys
from sage.all import *
def usage():
print("Usage: {0} Lmax [precision]".format(sys.argv[0]))
def gen_gaunt_table(lmax, prec = None):
tmpl = "{0:4d} {1:4d} {2:4d} {3:4d} {4:4d} {5:5d} {6:23.15e}\n"
with open("gaunt_lmax{0}".format(lmax), 'w') as out:... | StarcoderdataPython |
1661368 | <reponame>mintproject/mint_cli
from unittest import TestCase
from dame.modelcatalogapi import get_setup
from dame.utils import obtain_id
SETUP_FULL_INFO = "cycles-0.10.2-alpha-collection-oromia-single-point"
SETUP_PARTIAL_INFO = "dsi_1.0_cfg"
testing = "testing"
class Test(TestCase):
def test_get_setup(self):
... | StarcoderdataPython |
184314 | # For Keystone Engine. AUTO-GENERATED FILE, DO NOT EDIT [systemz_const.py]
KS_ERR_ASM_SYSTEMZ_INVALIDOPERAND = 512
KS_ERR_ASM_SYSTEMZ_MISSINGFEATURE = 513
KS_ERR_ASM_SYSTEMZ_MNEMONICFAIL = 514
| StarcoderdataPython |
3560110 | # Generated by Django 3.2.9 on 2021-11-10 21:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('djasana', '0023_alter_attachment_url_download_length'),
]
operations = [
migrations.AddField(
m... | StarcoderdataPython |
1987925 | import os
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc, func
from flask_cors import CORS
import random
from models import setup_db, Question, Category
QUESTIONS_PER_PAGE = 10
def format_categories(categories):
return {category.id : category.ty... | StarcoderdataPython |
92660 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.internal.platform.tracing_agent import chrome_tracing_agent
class FakePlatformBackend(object):
pass
class FakeDevtoolsC... | StarcoderdataPython |
1802514 | <reponame>vietbm-hcm/modoboa
"""SimpleUsers views."""
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required
from reversion import revisions as reversion
from modoboa.lib.web_utils import render_to_json_respons... | StarcoderdataPython |
6486793 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 ... | StarcoderdataPython |
1998486 | <reponame>wlbksy/robotics
import numpy as np
import pytest
from numpy.testing import assert_almost_equal, assert_array_almost_equal
import robotics as rbt
class TestConversions:
def test_rotation3D_axis_angle(self):
axis_z = np.array([0, 0, 1])
assert_array_almost_equal(np.eye(3), rbt.rotation3D... | StarcoderdataPython |
5072878 | <filename>database_schema.py
from sqlalchemy import UniqueConstraint
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, Table, Boolean, Text
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.decla... | StarcoderdataPython |
3366980 | class Assembly:
def __init__(self, yaml):
self.yaml = yaml
def apply(self, ind):
pass
class Gibson(Assembly):
def __set_junction_size(self):
self.junction_size = self.yaml["Algorithm"]["assemblies"][
"mooda.assembly.Gibson"
]["junction_size"]
def initialis... | StarcoderdataPython |
1970764 | <reponame>JianyuTANG/GB-To-UTF8<gh_stars>0
import sys
import os
origin_name = sys.argv[1]
if len(sys.argv) == 3:
to_name = sys.argv[2]
elif len(sys.argv) == 2:
to_name = origin_name
else:
print("ERROR: wrong arg number")
os._exit(0)
def write_to_file(data, filename):
with open(filename, 'wb') as... | StarcoderdataPython |
6409946 | #!/usr/bin/python
"""
@brief Run QuickBot class for Beaglebone Black
@author <NAME> (<EMAIL>)
@date 02/07/2014
@version: 1.0
@copyright: Copyright (C) 2014, Georgia Tech Research Corporation see the
LICENSE file included with this software (see LINENSE file)
"""
import sys
import argparse
DESCRIPTION = ... | StarcoderdataPython |
8022031 | import pytest
from .helpers import utils, speke_element_assertions
import xml.etree.ElementTree as ET
@pytest.fixture(scope="session")
def widevine_response(spekev2_url):
return utils.send_speke_request(utils.TEST_CASE_1_P_V_1_A_1, utils.PRESETS_WIDEVINE, spekev2_url)
@pytest.fixture(scope="session")
def playre... | StarcoderdataPython |
8027776 | <reponame>tgodzik/intellij-community
from scapy import all as scapy
print('TEST SUCEEDED!') | StarcoderdataPython |
18565 | <filename>src/planet_box_extractor/extractor.py
from .geo_utils import boundingBox
import time
import PIL.Image
import urllib.request
import mercantile
import numpy as np
class PlanetBoxExtractor:
"""
Extract bounding boxes from satellite images using Planet Tiles API
@radius: distance from the cen... | StarcoderdataPython |
1864584 | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import json
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from huxley.accounts.models import User
f... | StarcoderdataPython |
3466747 | from features.fetch import DataSet
from features.output import ExchangesOutput
from model.exchanges import ExchangesSolver
import numpy as np
def solve_all(dataset, verbose=False, with_redistribution=True, output_file = None):
exchangesOutput = ExchangesOutput()
grids = dataset.list_grids()
for _, g in g... | StarcoderdataPython |
6441349 | import cv2
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
from skimage.feature import blob_dog, blob_log, blob_doh
import imutils
import argparse
import os
import math
from classification import training, getLabel
SIGNS = ["nouvelle",
"STOP",
"TURN LEFT",
"TURN RIGHT"... | StarcoderdataPython |
215326 | # 游戏统计的信息
import json
class GameStats():
def __init__(self, set):
self.set = set
self.reset_stats()
self.game_active = False
with open("high_score.json", "r") as h_s:
self.high_score = json.load(h_s)
"""让初始化可以在创建对象后随时发生"""
"""初始化一次放上面,重复初始化放下面 """
... | StarcoderdataPython |
6503064 | #
# \file generator.py
#
# \brief Generates the CUTLASS Library's instances
#
import enum
import os.path
import shutil
import argparse
import platform
from library import *
from manifest import *
###################################################################################################
#
def CudaToolkitVers... | StarcoderdataPython |
6596871 | # Find common tracks.
def run(plists, outfile):
print(f"Finding common tracks...")
track_name_sets = []
# Collect data.
for plist in plists:
names = set()
tracks = plist['Tracks']
for (id, track) in tracks.items():
try:
names.add(track['Name'])
... | StarcoderdataPython |
8092787 | <filename>statsmodels/regression/tests/results/results_grunfeld_ols_robust_cluster.py
import numpy as np
class Bunch(dict):
def __init__(self, **kw):
dict.__init__(self, kw)
self.__dict__ = self
for i,att in enumerate(['params', 'bse', 'tvalues', 'pvalues']):
self[att] = self.... | StarcoderdataPython |
4858389 | <gh_stars>1-10
num1 = 11
num2 = 22
num3 = 33333333
num3 = 333
num4 = 4444
| StarcoderdataPython |
11243112 | <gh_stars>10-100
import matplotlib.pyplot as plt
import geneview as gv
df = gv.utils.load_dataset("gwas")
gv.qqplot(df.loc[:, "P"])
plt.tight_layout()
plt.show()
| StarcoderdataPython |
4828363 | from fastapi import Response
from fastapi.routing import APIRouter
import hashlib
import os
from bootstrap import db, CONFIG
import time
from util import *
from pydantic import BaseModel
from starlette.status import *
from tinydb import Query, where
import secrets
router = APIRouter(prefix="/login")
@router.get("/in... | StarcoderdataPython |
3349582 | <gh_stars>0
from aocd import submit
#-------------------------------Run once!---------------------
# get data from aocd
#import os
#os.system('del day7.txt')
#os.system('aocd 7 2020 >> day7.txt')
#--------------------------------------------------------------
def unique_colors(target_bag, d, lines, seen):
... | StarcoderdataPython |
6663123 | <reponame>Comcast/Fred-Framework
from ovsdb_client import OVSDBConnection
import variables as names
import sys
import argparse
def main(argv):
ap = argparse.ArgumentParser()
ap.add_argument("-t", "--table_name", type=str, required=False, help="FSM table name to be updated")
ap.add_argument("-q", "--updat... | StarcoderdataPython |
3545660 | <filename>teddix-common/teddix/TeddixHPUX.py
#!/usr/bin/env python
#
import os
import re
import sys
import time
import psutil
import platform
import subprocess
# Syslog handler
import TeddixLogger
# Config parser
import TeddixConfigFile
class TeddixHPUX:
# Get installed packages
def getpkgs(self):
... | StarcoderdataPython |
6529519 | <reponame>sqoor/SeqGenSQL-ui
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField
from wtforms.validators import DataRequired
from markupsafe import Markup
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()]... | StarcoderdataPython |
8037504 | from django.db import models
class HashSha(models.Model):
frag1 = models.CharField(max_length=254)
frag2 = models.CharField(max_length=254)
frag3 = models.CharField(max_length=130)
frag4 = models.CharField(max_length=4)
frag5 = models.CharField(max_length=2)
resource = models.OneToOneField(
... | StarcoderdataPython |
6610940 | import os
import socket
import zmq
import constants
class RTPPacketUDPSender:
def __init__(self, ip, port=9529):
self.ip = ip
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("video RTP packet UDP sender created, pid = %d, target = %s:%d" % (os.... | StarcoderdataPython |
1993308 | <filename>desktop/core/src/desktop/lib/test_runners.py
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under th... | StarcoderdataPython |
8015718 | import logging
from qolsys.exceptions import QolsysGwConfigIncomplete
from qolsys.exceptions import QolsysGwConfigError
LOGGER = logging.getLogger(__name__)
class QolsysGatewayConfig(object):
_SENTINEL = object()
_DEFAULT_CONFIG = {
'panel_host': _SENTINEL,
'panel_port': None,
'pan... | StarcoderdataPython |
6659023 | ############################################################
### Forked from https://github.com/cmhcbb/attackbox
############################################################
from __future__ import absolute_import, division, print_function
import numpy as np
class HSJA(object):
def __init__(self,model,constraint=2... | StarcoderdataPython |
6591050 | import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import argparse
from app.db import Document
import os
def parseargs():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--database', type=str, required=True, help="Database.")
parser.add_ar... | StarcoderdataPython |
1781334 | <gh_stars>1-10
from __future__ import annotations
from numpy.typing import ArrayLike
from sklearn.linear_model import LinearRegression
from .regression_model import RegressionModel
class LinearModel(RegressionModel):
def __init__(self):
self._lin_regressor: LinearRegression | None = None
def learn(... | StarcoderdataPython |
5131894 | import tensorflow as tf
from tf_transformers.core import LegacyLayer, LegacyModel
from tf_transformers.utils import tf_utils
class Similarity_Model_Pretraining(LegacyLayer):
def __init__(
self,
encoder,
projection_dimension,
decoder=None,
is_training=True,
use_drop... | StarcoderdataPython |
6486984 | <reponame>mariajmolina/hysplit_applications<filename>alaska_storms/run_hysplit_ens.py
import pandas as pd
import datetime
import numpy as np
import argparse
import math
from pysplit.trajectory_generator import generate_bulktraj
############################################################################
##############... | StarcoderdataPython |
11215006 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import dataclasses
import gzip
import json
from dataclasses import dataclass, Field, MISSING
from typing impor... | StarcoderdataPython |
4941423 | import requests
import json
def login(useremail, userpassword):
url = "http://127.0.0.1:8000/api/login"
payload = {'username': useremail,
'password': <PASSWORD>}
files = [
]
headers = {
'Cookie': 'csrftoken=<KEY>; sessionid=5g4v77efjv0r99nziiourrzqocruyasl'
}
res... | StarcoderdataPython |
4873292 | from ..core import Entity as L10nEntity, Structure
class LOL(Structure):
def add(self, element):
if element is not None:
self.add_element(element)
def add_element(self, element, pos=None):
"""
overwrite silme.core.L10nObject.add_element
"""
if element == Non... | StarcoderdataPython |
6438488 | from setuptools import setup, find_packages
setup(
packages=find_packages(exclude=['tests', 'tests.*']),
)
| StarcoderdataPython |
242116 | # Copyright 2020 SAS Project 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 requ... | StarcoderdataPython |
1657694 | from src.utils.utils import open_json_file, open_html_file, open_csv_file # noqa
| StarcoderdataPython |
3429048 | import arcade
from constants import *
class MainHand(arcade.Sprite):
def __init__(self, filename, icon_image, player, stats, scale=HELMET_SCALE):
super().__init__(filename, scale)
self.filename = filename
self.icon_image = icon_image
self.player = player
self.stats = stats
... | StarcoderdataPython |
6583189 | <reponame>vla3089/adventofcode<gh_stars>0
#!/usr/bin/env python
score = 0
nesting_level = 0
is_garbage_mode = False
garbage_count = 0
skip_next = False
def process_in_garbage_mode(c):
global score
global nesting_level
global is_garbage_mode
global skip_next
global garbage_count
if skip_n... | StarcoderdataPython |
8176971 | from setuptools import setup, find_packages
setup(
name='vtkrishn',
version='0.1.0',
description='Simple Project',
url='https://github.com/vtkrishn/pythonHelper',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :... | StarcoderdataPython |
1927922 | <filename>features/steps/check_if_contains_schema_version.py
from behave import then
from pgmigrate import _is_initialized
@then("database contains schema_version")
@then('database contains schema_version in schema "{schema}"')
def step_impl(context, schema='public'):
cur = context.conn.cursor()
assert _is_in... | StarcoderdataPython |
9678246 | <gh_stars>0
import nextcord
from .constant import ARBITRE_ID, CIVFR_GUILD_ID
from util.exception import ALEDException
def is_arbitre(member : nextcord.Member, client=None):
if member.guild is None:
if client is None:
raise ALEDException("Client not given for checking if the member is Arbitre")
... | StarcoderdataPython |
11275453 | '''
Author: Jecosine
Date: 2021-01-22 05:43:45
LastEditTime: 2021-01-22 05:44:02
LastEditors: Jecosine
Description: Test
'''
s = """- Creational
- AbstractFactory
- Builder
- FactoryMethod
- Prototype
- Singleton
- Structural
- AdapterBridge
- Composite
- Decorator
- Facade
- Flyweight
- Prox... | StarcoderdataPython |
11242529 | from .reqmethods import Req, Arrange
class Account(Req, Arrange):
slug = 'account'
def __init__(self, token):
self.setToken(token)
def account(self):
data = self.get(self.slug)
if 'id' in data:
return data
return self.arrangeData(data)
| StarcoderdataPython |
3344637 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009, <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""psutil is a cross-platform library for retrieving information on
running processes and system utilization (CPU, mem... | StarcoderdataPython |
1795123 | <reponame>icemac/icemac.ab.importer<filename>src/icemac/ab/importer/browser/wizard/tests/test_reader.py
from icemac.addressbook.interfaces import IPhoneNumber
import zope.component.hooks
def test_reader__ReaderSettings__1(address_book, browser, ImportFileFactory):
"""It has an empty import file readers list on em... | StarcoderdataPython |
6427710 | from pprint import pprint
points = [
(10, 41, 23),
(22, 30, 29),
(11, 42, 5),
(20, 32, 4),
(12, 40, 12),
(21, 36, 23)
]
print('points', points)
| StarcoderdataPython |
5040953 | <reponame>BDI-ENIB/hermin-I<gh_stars>1-10
#import python Module
import os
import os.path
import csv
import time
import shutil
#import Dolmen Module
import Windows
import Widgets
import Graph
import Config
import Sensors
import Error
count=0 # current line in CSV
state_communication=False #if True => start decoding
d... | StarcoderdataPython |
239419 | <filename>ServidorSenha/ServidorSenha.py<gh_stars>1-10
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
"""
Servidor de Senha
Módulo com classe senha.
"""
from pymongo import MongoClient
from hmac import compare_digest as comparador
import crypt
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client
import soc... | StarcoderdataPython |
1997433 | <filename>tests/components/rfxtrx/test_init.py
"""The tests for the Rfxtrx component."""
from unittest.mock import call
from homeassistant.components.rfxtrx import DOMAIN
from homeassistant.components.rfxtrx.const import EVENT_RFXTRX_EVENT
from homeassistant.core import callback
from homeassistant.helpers.device_regi... | StarcoderdataPython |
6512284 | # <NAME>'s Solution:
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums) == 0:
return 0
nums.sort()
sum = 0
for i in range(0,len(nums)-1,2):
sum += min(nums[i... | StarcoderdataPython |
11328733 | <filename>share_file/__init__.py
# -*- coding: utf-8 -*-
import threading
from os import path
from mimetypes import types_map
from urllib import request
from urllib.error import URLError
from urllib.parse import quote
from fman import (
DirectoryPaneCommand,
show_alert,
show_status_message,
clear_s... | StarcoderdataPython |
11293852 | """
Framework-specific classes/functions/objects that rely on the `ply` framework.
"""
from . import lex, yacc
import traceback
__all__ = [
"lex",
"yacc",
"start_console",
]
def _check_lexer_interface(x):
if not hasattr(x, 'token'):
return False
if not hasattr(x.token,... | StarcoderdataPython |
3434431 | <reponame>litxio/ptghci-engine
from pygments import highlight
from pygments.lexers.haskell import HaskellLexer
from pygments.formatters import Terminal256Formatter
from pygments.styles import get_style_by_name
def hl(s, config, style_name=None):
if style_name:
style = get_style_by_name(style_name)
el... | StarcoderdataPython |
8162030 | import difflib
import filecmp
from dataclasses import dataclass
from pathlib import Path
from typing import List
@dataclass
class ComparisonResult:
diffs: List[str]
class FileComparator:
def compare(self, file1: Path, file2: Path) -> ComparisonResult:
equal = filecmp.cmp(str(file1), str(file2))
... | StarcoderdataPython |
346403 | <reponame>lim0606/pytorch-ardae-vae
import torch
import torch.autograd
from torch.autograd import Function
import torch.nn.functional as F
'''
https://pytorch.org/docs/stable/notes/extending.html
'''
class AuxLossForGradFunction(Function):
# Note that both forward and backward are @staticmethods
@staticmethod... | StarcoderdataPython |
178688 | <gh_stars>0
from django.conf.urls import patterns, include, url
from account import views
urlpatterns = patterns('',
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.user_logout, name='user_logout'),
) | StarcoderdataPython |
11363307 | """
Test on images split into directories. This assumes we've split
our videos into frames and moved them to their respective folders
and trained our model.
Based on:
https://keras.io/preprocessing/image/
and
https://keras.io/applications/
"""
from train_custom_cnn import get_model
from tensorflow.keras.optimizers imp... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.