id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1604149
<reponame>girleffect/ge-sm import json from pathlib import Path from ge_sm.common.secrets import * pathname = Path(os.path.join(os.path.abspath(''))) channelsdict = { os.environ.get('YT_CHANNEL', ''): { 'name': 'Chajaa', 'analyticsdat': 'analytics_CJ.dat', 'playlist': os.environ.get('YT_PLAYLIST', ''), 'you...
StarcoderdataPython
1761661
<filename>exposure.py #Main code for SDOptimizer import time import cv2 import numpy import os def exposureBenchmark(imageDir): image = cv2.imread(imageDir) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # compute a grayscale histogram hist = cv2.calcHist([image], [0], None, [256], [0, 256]) #print("this ima...
StarcoderdataPython
1688438
<reponame>bopopescu/cc<filename>nova/endpoint/images.py<gh_stars>0 # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2010 <NAME>, LLC # # Licensed unde...
StarcoderdataPython
55440
from setuptools import setup, find_packages import os version = '0.0' requires = [ "setuptools>=0.7", "pyramid", ] tests_require = [ "pytest", "testfixtures", "webtest", ] long_description = ( open('README.rst').read() + '\n' + 'Contributors\n' '============\n' + '\n' + o...
StarcoderdataPython
1766031
<reponame>kipyin/phanpy #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, sys import pytest file_path = os.path.dirname(os.path.abspath(__file__)) root_path = file_path.replace('/phanpy/tests', '') sys.path.append(root_path) if root_path not in sys.path else None from phanpy.core.tables import which_ability,...
StarcoderdataPython
3377288
nome=input('Qual e o seu nome') idade=input('Qual e a sua idade') peso=input('Qual e o seu peso') print(nome,idade,peso, 'Nossa voce voce e muito inteligente')
StarcoderdataPython
130567
<filename>Advent2021/3.py<gh_stars>0 from typing import Tuple def CountOnes(lines: list[str], position: int) -> int: count = 0 for line in lines: if line[position] == "1": count += 1 return count def ConvertBinary(line: str) -> int: power = len(line) - 1 result = 0 for po...
StarcoderdataPython
1682125
import numpy as np from math import cos, sin, sqrt import math class Joint(object): def __init__(self, d=0, theta=0, a=0, alpha=0, prevLink=None, **kwargs): super().__init__(**kwargs) self.d = d self.theta = theta self.a = a self.alpha = alpha if not isins...
StarcoderdataPython
3268404
<reponame>rajevac/deitel-intro-to-python-exercises from Point import Point class Circle: def __init__(self, radius, point=None): if point is None: point = [0, 0] self.radius = radius self.point = point @property def radius(self): return self._radius @radi...
StarcoderdataPython
40219
from timing import timing @timing def concat(nums): ans = list(range(2*len(nums))) for i, value in enumerate(nums): ans[i] = value ans[i + len(nums)] = value return ans @timing def concat2(nums): ans = nums for i in range(len(nums)): ans.append(nums[i]) return ...
StarcoderdataPython
20823
<reponame>mceSystems/node-windows-pac-resolver { "targets": [ { "target_name": "binding", "sources": [ "native\\winhttpBindings.cpp" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")" ], "libraries": [ "WinHTTP.lib", "-DelayLoad:node.exe"...
StarcoderdataPython
1688855
""" Descrição Nesta atividade você deve criar uma classe simples chamada Pessoa com o mesmos atributos da atividade anterior Pessoa com Pai e Mãe, mas adicionando mais 3 métodos: Atributos nome rg pai mae Métodos adiciona_pai - já feito na atividade anterior adiciona_mae - já feito na atividade anterior eh_mesma_pe...
StarcoderdataPython
1688082
<filename>note9/data/prepare_voc_data.py # coding=utf-8 import os import re import random # 根据数据集的路径和年份和数据类型拼接路径 def get_dir(devkit_dir, year, type): return os.path.join(devkit_dir, 'VOC' + year, type) def walk_dir(devkit_dir, year): # 获取所有类别的训练和测试的文件名的文件夹路径 filelist_dir = get_dir(devkit_dir, year, 'Imag...
StarcoderdataPython
3274589
<reponame>mota/email-lib """ Work on hashtags """ import re HASHTAG_PATTERN=re.compile(r'(^|\s)#([^\d\s]\w+\b)') def extract_hashtags(content): """ Extract twitter-like hashtags from a given content """ return [ matches[1] for matches in HASHTAG_PATTERN.findall(content) ]
StarcoderdataPython
1780296
<filename>sqlshare_rest/test/api/user_search.py<gh_stars>0 from django.test import TestCase from unittest2 import skipIf from django.db import connection import json from datetime import datetime from dateutil import parser from django.utils import timezone from sqlshare_rest.util.db import get_backend from sqlshare_re...
StarcoderdataPython
52661
import csv """Set of functions used to import from csv into the FIDO model. The import is specified as a dictionary, defining the model, the name of the primary key and the list of fields. Recursions are used to defind foreign keys.""" IMPORT_CSV_MODEL_KEY = "model" IMPORT_CSV_PK_NAME_KEY = "pk_name" IMPORT_CSV_PK_KE...
StarcoderdataPython
3395545
#!/usr/bin/env python3 # URL: https://python-gtk-3-tutorial.readthedocs.io/en/latest/treeview.html # URL: https://github.com/jamalex/notion-py import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk from gi.repository import Gdk from notion.client import NotionClient import threading # Global variab...
StarcoderdataPython
4821195
#!/usr/bin/python #--------------------------------------------------------------# # DESCRIPTION # # Takes a csv with lines in the format 'x y v' representing# # the data from a 640x480 gs image. v is then scaled into # # the drawable range to get a full sp...
StarcoderdataPython
3346312
<filename>backend/app/literature/models/reference_comment_and_correction_model.py """ reference_comment_and_correction_model.py ========================================== """ from typing import Dict from sqlalchemy import Column, Enum, ForeignKey, Integer from sqlalchemy.orm import relationship from literature.data...
StarcoderdataPython
1700139
import os import cv2 import numpy as np from PIL import Image from random import shuffle import torch import torch.utils.data import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor import utils import transforms as...
StarcoderdataPython
3395149
from optparse import make_option import datetime from django.contrib.sessions.models import Session from django.core.management.base import LabelCommand, CommandError import time import maintenance.api as api import logging logger = logging.getLogger("maintenance") class Command(LabelCommand): opts = ('on', 'off...
StarcoderdataPython
3314555
#!/usr/bin/env python # -*- coding: utf-8 -*- modelChemistry = "CBS-QB3" useHinderedRotors = True useBondCorrections = True species('H', 'H.py') statmech('H') thermo('H', 'Wilhoit')
StarcoderdataPython
3287035
import pathlib import os def current_path(): return os.getcwd()
StarcoderdataPython
3261461
# from django.views import ListView from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.http import Http404, HttpResponse, HttpResponseRedirect from django.views.generic import ListView, DetailView, View from django.shortcuts import render, get_object_or_404, redire...
StarcoderdataPython
3262291
<reponame>CNES/Pandora_plugin_libSGM #!/usr/bin/env python # coding: utf8 # # Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES). # # This file is part of Pandora plugin LibSGM # # https://github.com/CNES/Pandora_plugin_libsgm # # Licensed under the Apache License, Version 2.0 (the "License"); # you may n...
StarcoderdataPython
100564
<gh_stars>1-10 from .card import Card from ..squares import Square from ..utility import Logger class AdvanceTo(Card): ''' Represents an "Advance to..." card, including checking whether the player passes go and collects £200. ''' def __init__(self, square_name): ''' The 'construct...
StarcoderdataPython
3278494
<gh_stars>1-10 import requests import settings_secret TOKEN = settings_secret.TELEGRAM_TOKEN def send_message(text, chat_id): url = "https://api.telegram.org/bot{0}/sendMessage".format(TOKEN) data = {'chat_id' : chat_id, 'text' : text} response = requests.post(url, data=data)
StarcoderdataPython
1736555
#!/usr/bin/env python2 # -*- coding: utf8 -*- import re import requests from bs4 import BeautifulSoup from taemin import plugin class TaeminNiceBot(plugin.TaeminPlugin): def __init__(self, taemin): plugin.TaeminPlugin.__init__(self, taemin) self.mapping = [ (r"""((?:http[s]?://)?(?:www...
StarcoderdataPython
3329366
"""Cloud storage abstract IO classes Theses abstract classes are used as base to implement storage specific IO classes""" from airfs._core.io_base_raw import ObjectRawIOBase from airfs._core.io_base_buffered import ObjectBufferedIOBase from airfs._core.io_base_system import SystemBase from airfs._core.io_random_write...
StarcoderdataPython
1675940
<filename>profile_settings/views.py from django.shortcuts import render,redirect from accounts.models import * from django.core.files.storage import FileSystemStorage from django.contrib import messages import os from dashboard.forms import * from django.core.exceptions import ObjectDoesNotExist from django.shortcuts i...
StarcoderdataPython
124669
from doctest import testmod import unittest from julius import resample, fftconv, lowpass, bands, utils class DocStringTest(unittest.TestCase): def test_resample(self): self.assertEqual(testmod(resample).failed, 0) def test_fftconv(self): self.assertEqual(testmod(fftconv).failed, 0) def...
StarcoderdataPython
1669378
import bpy from . import list_helper, collapsible, base from .. import registry from ..utils import is_helper_object from ..details import ui as det_ui from ..version_utils import assign_props, IS_28 items = ( ('copy', '', '', 'COPYDOWN', 0), ('paste', '', '', 'PASTEDOWN', 1), ('clear', '', '', 'X', 2) )...
StarcoderdataPython
50894
def reverse(n): reversed = 0 while n > 0: reversed = 10*reversed + n%10 n = n/10 return reversed def isPalindrome(n): return n == reverse(n) largestPalindrome = 0 a = 999 while a >= 100: b = 999 while b >= a: if a*b <= largestPalindrome: break if isPa...
StarcoderdataPython
1717705
class Push(): def __init__(self, **kwargs): self.author = kwargs.get('author') self.content = kwargs.get('content') self.datetime = kwargs.get('datetime') self.push = kwargs.get('push') def __str__(self): return '<Push> %s %s' % (self.push, self.author) class Post(): ...
StarcoderdataPython
33813
<reponame>gauravkmr/swagaf<gh_stars>100-1000 # First make the vocabulary, etc. import os import pickle as pkl import random import simplejson as json from allennlp.common.util import get_spacy_model from allennlp.data import Instance from allennlp.data import Token from allennlp.data import Vocabulary from allennlp.d...
StarcoderdataPython
3336558
arquivo = open("dados/contatos-escrita.csv", mode="a+") contatos = [ "11,Carol,<EMAIL>\n", "12,Ana,<EMAIL>\n", "13,Tais,<EMAIL>\n" ] for contato in contatos: arquivo.write(contato) arquivo.flush() arquivo.seek(28) arquivo.write("12,Ana,<EMAIL>\n".upper()) arquivo.flush() arqui...
StarcoderdataPython
89415
<reponame>dclark87/pytools # test/unit/sort_search/hash_tables_test # # Author: <NAME>, 2016 ''' Unit test module to perform testing on sorting module ''' # Import packages import unittest class SortingTestCase(unittest.TestCase): ''' TestCase for the sorting module ''' # Set up test case def s...
StarcoderdataPython
10739
<filename>matches/tests/test_view_index.py from django.urls import resolve, reverse from django.test import TestCase from matches.views import matches_index from matches.models import Match class AllMatchesTests(TestCase): def setUp(self): self.match = Match.objects.create( match_id=1, ...
StarcoderdataPython
192250
<reponame>rsamit26/Euler_Project<gh_stars>10-100 """ Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ ...
StarcoderdataPython
1661408
import base64 import os import argparse import sys def encode_file(file_path): """ Base64 encode a file. :param file_path: File path. :return: Base64 encoded file. """ with open(file_path, 'rb') as f: s = base64.b64encode(f.read()) return s.decode('utf-8') def get_output_path(file_path): """ ...
StarcoderdataPython
1632763
<reponame>k-tahiro/tahiremovision from PIL import Image import torch import torch.nn as nn from torchvision import models, transforms class Predictor: def __init__(self, model_file: str, input_size: int): self._set_model(model_file) self._set_transform(input_size) def _set_model(self, model_f...
StarcoderdataPython
3215405
from grb.dataset import Dataset if __name__ == '__main__': # Load data dataset_name = 'grb-cora' dataset = Dataset(name=dataset_name, data_dir="../data/", mode='full', feat_norm='arctan') adj = dataset.adj features = dataset.feature...
StarcoderdataPython
97276
x = int (input('Digite um numero :')) for x in range (0,x): print (x) if x % 4 == 0: print ('[{}]'.format(x))
StarcoderdataPython
150452
from app.horoscope.model import TextModel from app.horoscope.text_enhancer import TextEnhancer __all__ = [ 'HoroscopeGenerator', ] class HoroscopeGenerator: __STOP_START = ('Однако', 'Но') def __init__(self, model: TextModel, enhancer: TextEnhancer): self.__model = model self.__enhancer ...
StarcoderdataPython
3391692
import pandas as pd import gzip import os from concurrent import futures def divide_name(filename): #home-made os.path.splitext, for it can't handle "name.a.b.c" properly basename = os.path.basename(filename) parts = basename.split(".") #split return >= 1 length list if len(parts) == 1: return p...
StarcoderdataPython
3249188
from django.test import TestCase from .services import * class NormalizePhoneTestCase(TestCase): def test_normalize_phone(self): self.assertEqual(normalize_phone("+38-0975896547"), '380975896547') self.assertEqual(normalize_phone("+38-097-5896-547,+38-09758-96547"), '380975896547') self.as...
StarcoderdataPython
1710891
import sys import time import urllib from urllib.parse import quote from urllib.parse import quote_plus import hmac import hashlib import base64 def get_auth_token(eh_namespace, eh_name, eh_key): uri = quote_plus("https://{0}.servicebus.windows.net/{1}".format(eh_namespace, eh_name)) eh_key = eh_key.encode...
StarcoderdataPython
1610290
<reponame>psiexperiment/psiaudio import pytest from collections import deque from functools import partial import numpy as np from scipy import signal from psiaudio import pipeline from psiaudio.pipeline import normalize_index @pytest.fixture def data1d(fs): md = {'foo': 'bar'} data = np.random.uniform(siz...
StarcoderdataPython
1668809
<filename>examples/render_pointcloud.py from pathlib import Path import rospy from sensor_msgs.msg import PointCloud2 from griffig import Griffig, Pointcloud, Renderer if __name__ == '__main__': base = Path(__file__).parent rospy.init_node('pointcloud_renderer', anonymous=True) # Orthographic image ren...
StarcoderdataPython
1663182
<reponame>antopen/alipay-sdk-python-all<filename>alipay/aop/api/domain/AlipayCommerceIotSdarttoolMessageSendModel.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayCommerceIotSdarttoolMessageSendModel(object): def __init__(self): ...
StarcoderdataPython
3231602
#-*- coding: utf-8 -*- """ Playlists package """ from .guesser import library_guesser
StarcoderdataPython
3201056
<filename>spine/classification/cls_dataset_dict.py # Copyright 2021 Medical Imaging Center, Vingroup Big Data Insttitute (VinBigdata), Vietnam # # 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 ...
StarcoderdataPython
1736573
""" <NAME> <EMAIL> Implements the Igniter class """ import RPi.GPIO as GPIO import time from multiprocessing import Process class Igniter(): """ Igniter object, capable of sending a pulse down a specified GPIO pin on a raspberry pi """ def __init__(this, pin): """ Igniter(pin) | creates...
StarcoderdataPython
47077
from pyparsing import LineEnd, LineStart, SkipTo, Regex from regparser.grammar import atomic, unified section = ( atomic.section_marker.copy().leaveWhitespace() + unified.part_section + SkipTo(LineEnd()) ) par = ( atomic.section.copy().leaveWhitespace() + unified.depth1_p + SkipTo(LineEnd()...
StarcoderdataPython
146193
import matplotlib from collections import defaultdict, OrderedDict, Counter from plots.DotSetPlot import DotSetPlot processToTitle = { "targetMirsECA": "EC activation and inflammation", "targetMirsMonocyte": "Monocyte diff. & Macrophage act.", "targetMirsFCF": "Foam cell formation", "targetMi...
StarcoderdataPython
1716543
<gh_stars>1-10 from pandas import read_csv from pandas import DataFrame from pandas import concat import pandas as pd from sklearn.metrics import mean_squared_error from math import sqrt from matplotlib import pyplot from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from t...
StarcoderdataPython
95962
# # Copyright (c) 2006-2013, Prometheus Research, LLC # from . import command, locate from ...core.addon import Addon, Parameter from ...core.validator import StrVal, PIntVal class TweakShellAddon(Addon): name = 'tweak.shell' prerequisites = ['tweak.resource'] hint = """add in-browser editor for HTSQL"...
StarcoderdataPython
1673278
VERSION = "v2" BASE_URL = "https://api.guildwars2.com/%s/" % VERSION LANGUAGES = { "en": "English", "es": "Spanish", "de": "German", "fr": "French", "ko": "Korean", "zh": "Chinese" } from .endpoint import Endpoint, BuildEndpoint, LocaleAwareEndpoint from .recipes import RecipeSearchEndpoint fr...
StarcoderdataPython
1610561
# pylint: disable=invalid-name,no-self-use,protected-access from numpy.testing import assert_almost_equal import torch from torch.autograd import Variable from allennlp.common import Params from allennlp.common.testing import AllenNlpTestCase from allennlp.models.semantic_parsing.wikitables.wikitables_decoder_state im...
StarcoderdataPython
3311066
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class djandoAdminTestClass(TestCase): def setUp(self): """django admin and user setup""" self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email = '<E...
StarcoderdataPython
1601312
import time import math class FakeTime: def __init__(self): self.delta = 0 self.epoch = time.time() def sleep(self, s): self.delta += s def time(self): t = self.epoch # time.time() t += round(self.delta, 5) return t def ms_sleep(self, s): ...
StarcoderdataPython
1710633
<filename>lti_tool/ags.py from datetime import datetime from pytz import utc from urllib.parse import urlsplit, urlunsplit def ts2str(ts): """Generates LTI conformant date-time string. :param ts: datetime object :rtype: date-time (utc) string in ISO 8601 representation with millisecond precision...
StarcoderdataPython
1692354
<gh_stars>0 from .auth import AuthApp
StarcoderdataPython
1755063
<reponame>arvindm95/unladen-swallow<filename>Demo/parser/simple.py def f(): "maybe a docstring"
StarcoderdataPython
1660140
import torch.nn as nn import torch.nn.functional as F from ..utils import ConvModule class SSDNeck(nn.Module): def __init__(self, in_channels = [1024,2048],out_channels = 256,out_map=None,start_level = 0,end_level = None): super(SSDNeck,self).__init__() self.in_channels = in_channels if is...
StarcoderdataPython
54234
import multiprocessing as mp import os import subprocess import time import pytest from solarforecastarbiter.io import fetch def badfun(): raise ValueError def bad_subprocess(): subprocess.run(['cat', '/nowaythisworks'], check=True, capture_output=True) @pytest.mark.asyncio @pytest.mark.parametrize('ba...
StarcoderdataPython
3352586
<reponame>sanket4373/keystone<filename>keystone/tests/matchers.py # Copyright 2013 OpenStack Foundation # # 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...
StarcoderdataPython
1680747
import numpy as np def maxLocation(preds,bbox,dims): deltaX = (bbox[2]-bbox[0]+1)/dims[0] deltaY = (bbox[3]-bbox[1]+1)/dims[1] W return W
StarcoderdataPython
4812111
s=input() c=0 r=[] for _ in range(int(input())): x=input() fail=False for i in range(9): if s[i]!=x[i] and s[i]!="*": fail=True break if not fail: c+=1 r.append(x) print(c) for i in r: print(i)
StarcoderdataPython
39999
<filename>bin/iris.py #!/usr/bin/python import RPi.GPIO as GPIO import time import sys GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) p = GPIO.PWM(12, 50) p.start(7.5) if sys.argv[1] == 'close': p.ChangeDutyCycle(7.5) time.sleep(1) else: p.ChangeDutyCycle(12.5) time.sleep(1) p.stop() GPIO.cleanup()
StarcoderdataPython
4822871
<filename>lambdas/run_code/tests/unit/test_handler.py<gh_stars>0 import json import pytest from run_code import lambda_function def test_lambda_handler(): with open('testsLocal/test1.json') as f: d = json.load(f) ret = lambda_function.lambda_handler(d, None) print(ret) def test_lambda_update_sta...
StarcoderdataPython
12156
<reponame>fernandoleira/lps-platform import csv from pathlib import Path from datetime import datetime from lps.models import * from lps.schemas import * SEED_FOLDER_PATH = Path("db/seeds/") def import_from_csv(csv_filename): with open(SEED_FOLDER_PATH / csv_filename) as csv_file: csv_read = csv.DictRe...
StarcoderdataPython
1637801
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models from neurve.core.models import load_from_folder class TorchvisionEmbed(nn.Module): def __init__(self, backbone, embedding_dim, *args, **kwargs): super().__init__() self.backbone = getattr(models, bac...
StarcoderdataPython
3317253
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organizer', '0001_initial'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ...
StarcoderdataPython
1700462
<reponame>NiccoloSalvi/Self-Driving-Car<filename>code/rasp/modules/tl.py # Traffic Light Recognition ## Link to yt video: https://youtu.be/6PDmYAtLAKQ?t=164 import sys import os sys.path.append(os.path.join(os.path.dirname(sys.path[0]), "classes")) from romi import Romi from camera import Camera from servo impor...
StarcoderdataPython
3223102
<reponame>nemalysis/rotordetection import os from pprint import pprint as pp import os import cv2 as cv import numpy as np import matplotlib.pyplot as plt from pyzbar import pyzbar as zbar from pprint import pprint as pp from barcode.rotation import get_rotation import time import csv def detect_from_image(imag...
StarcoderdataPython
1723871
<reponame>javiertelioz/ms-mailings # View Set's from .template import TemplateViewSet from .brand import BrandViewSet from .mail import MailViewSet
StarcoderdataPython
3202802
import os import re import logging import traceback from subprocess import call from time import time from pyramid.view import view_config from pyramid.response import Response from mist.monitor import config from mist.monitor import methods from mist.monitor import graphite from mist.monitor.model import get_all_ma...
StarcoderdataPython
3236098
<reponame>ssdorsey/udify-xlmr from udify.modules.bert_pretrained import UdifyPretrainedBertEmbedder, WordpieceIndexer, PretrainedBertIndexer, BertEmbedder from udify.modules.xlmr_pretrained import UdifyPretrainedXlmrEmbedder, WordpieceIndexer, PretrainedXlmrIndexer, XlmrEmbedder from udify.modules.residual_rnn import R...
StarcoderdataPython
3206488
import click import json import sys import logging from flask import Flask from db_communicate import load_db, add_user, update_state from config import C app = Flask(__name__) SwellDB = load_db() # Logging is not working :( logging.basicConfig(stream=sys.stdout) log = logging.getLogger('swell-backend.' + __name__) ...
StarcoderdataPython
3232290
<reponame>hi-weijun/pydatas-leecode # 定义一个单链表过程. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :"头指针"类型: ListNode :n的类型: int :返回类型: ListNode """ dummy = ListNode(-1) dum...
StarcoderdataPython
1709467
import json import critiquebrainz.db.license as db_license import critiquebrainz.db.review as db_review import critiquebrainz.db.users as db_users from critiquebrainz.db.user import User from critiquebrainz.ws.testing import WebServiceTestCase class ReviewViewsTestCase(WebServiceTestCase): def setUp(self): ...
StarcoderdataPython
184006
<filename>Python/FizzBuzz(O(n)).py for i in range(1,101): if(i%3==0 and i%5==0): print("FizzBuzz") if(i%3==0): print("Fizz") if(i%5==0): print("Buzz") else: print(i)
StarcoderdataPython
4800616
#!/usr/bin/env python import os import sys from I3Tray import I3Tray from os.path import expandvars from icecube import dataclasses from icecube import phys_services from icecube import dataio tray = I3Tray() tray.AddModule("I3Reader", Filename=expandvars("$I3_TESTDATA/dataio/olddata/string-21/MacOSX-libstdc++6-...
StarcoderdataPython
34275
#importing lib import pandas as pd import numpy as np #Take data df = pd.DataFrame({"Name":['Kunal' , 'Mohit' , 'Rohit' ] ,"age":[np.nan , 23, 45] , "sex":['M' , np.nan , 'M']}) #check for nnull value print(df.isnull().sum()) print(df.describe()) # ignore the nan rows print(len(df.dropna()) , df.dropna()) #for ...
StarcoderdataPython
1788426
## NOTES: ## Example Airflow DAG for running a unit test job ## against a feature group in the Feature Store and ## fetch the validation result. If the validation was ## unsuccessful then it will fail the rest of the pipeline ## ## It assumes that you have already populated your Feature Store ## and composed some valid...
StarcoderdataPython
3351415
import unittest from tests.lib.client import SingletonClient from tests.lib.card_products import CardProducts from marqeta.errors import MarqetaError class TestCardProductsFind(unittest.TestCase): """Holds tests for the card_products.find endpoint""" @classmethod def setUpClass(cls): """Setup fo...
StarcoderdataPython
129360
from django.forms.models import ModelForm from add_blog.models import Blog from django import forms class Update_form(ModelForm): content = forms.CharField(widget=forms.Textarea) class Meta: model = Blog fields = [ "title", "sub_title", "...
StarcoderdataPython
14457
<filename>tcp_tls_tunnel/hyper_http2_adapter.py import ssl import socket from typing import Tuple from hyper.common.util import to_native_string from urllib.parse import urlparse from hyper import HTTP11Connection, HTTPConnection from hyper.common.bufsocket import BufferedSocket from hyper.common.exceptions import TLS...
StarcoderdataPython
1662550
<gh_stars>1-10 from smsreg_python.smsreg import SmsReg from smsreg_python.dataclasses import Services def main(): service = Services.TELEGRAM print(f'Requesting number for {service}') sms_client.request_number(Services.TELEGRAM) print(f'Waiting for number') number = sms_client.wait_number_from_tr...
StarcoderdataPython
1788479
import os import subprocess from .check import Check, MessageType class SystemService(Check): origin = 'System service' states = { True: 'running', False: 'not running', None: 'unknown' } state2mgstype = { True: MessageType.INFO, False: MessageType.WARNING, ...
StarcoderdataPython
4830225
import torch from torchvision import datasets, transforms MNIST_PATH = '/home/dingxiaohan/datasets/torch_mnist/' CIFAR10_PATH = '/home/dingxiaohan/datasets/cifar-10-batches-py/' CH_PATH = '/home/dingxiaohan/datasets/torch_ch/' SVHN_PATH = '/home/dingxiaohan/datasets/torch_svhn/' class InfiniteDataLoader(torch.utils....
StarcoderdataPython
100374
<reponame>jkoelker/quark<filename>quark/tests/plugin_modules/test_ip_policies.py # Copyright 2013 Openstack Foundation # 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 #...
StarcoderdataPython
1663220
# :coding: utf-8 # Project Modules from kid.core.kobject import KObject from kid.core.kkeyframe import KKeyTangent, KKeyFrame # Python Modules class KAnimCurve(KObject): """ """ def __init__(self): self._keys = list() self._fps = 24.0 if __name__ == '__main__': pass
StarcoderdataPython
197329
from flask import current_app, render_template from flask_mail import Message from smtplib import SMTPException from main.repositories import DBRepository from main.models import UserModel, SensorModel from main.extensions import out_server_sender as mail_sender class Mail(DBRepository): def __init__(self, sess...
StarcoderdataPython
3268919
<reponame>sajjadt/competitive-programming<gh_stars>1-10 from math import tan, acos pi = acos(-1) def to_radian(degrees): degrees = degrees % 360 return (pi * degrees) / 180 while True: try: l, w, h, theta = list(map(int, input().split())) # convert to radians theta = to_radian(theta) h_prim = ...
StarcoderdataPython
195587
<filename>lms/services/launch_verifier.py """LTI launch request verifier service.""" from oauthlib.oauth1 import RequestValidator, SignatureOnlyEndpoint from lms import models from lms.services import ConsumerKeyError, LTILaunchVerificationError, LTIOAuthError __all__ = ["LaunchVerifier"] class LaunchVerifier: ...
StarcoderdataPython
3261258
#!/usr/bin/env python3 # # Copyright (c) 2020 <NAME> # # 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 applicable law or...
StarcoderdataPython
3238046
''' code = resnet 50,101,152 framework = pytorch author= <NAME> email= <EMAIL> ''' import torch import torch.nn as nn class block(nn.Module): def __init__(self, in_channels, out_channels, identity_downsample=None,stride=1): super(block,self).__init__() self.expansion = 4 self.conv1 = nn.C...
StarcoderdataPython
4825593
<filename>arrview/ellipse_test.py from PySide.QtGui import (QApplication, QGraphicsView, QGraphicsScene, QMainWindow, QPixmap, QPainter) from PySide.QtCore import Qt import sys if __name__ == '__main__': app = QApplication(sys.argv) scene = QGraphicsScene() view = QGraphicsView(sc...
StarcoderdataPython