id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1751781 | #!/bin/python
#coding:utf-8
import roomai
class Stage:
firstStage = 1
secondStage = 2
thirdStage = 3
fourthStage = 4
AllCardsPattern = dict()
#0 1 2 3 4 5 6
#name, isStraight, isPair, isSameSuit, [SizeOfPair1, SizeOfPair2,..](des... | StarcoderdataPython |
3200169 | import sys
import traceback
__author__ = 'xshu'
# global variables
symbolsFound = []
geneSymbol2IDMapping = {}
geneSymbol2SynonymsMapping = {}
def showHelp():
print\
'''
This program creates the initial gene2uniprot by updating aliases in hgncSymbolAlias2Uniprot with NCBI gene-info file
Usage: %s
... | StarcoderdataPython |
4830259 | from output.models.ms_data.identity_constraint.id_g029_xsd.id_g029 import (
Root,
T,
)
__all__ = [
"Root",
"T",
]
| StarcoderdataPython |
1768253 | #!/usr/bin/python -W all
"""
findRoute.py: find longest route with an index of the available train rides
usage: findRoute.py [-b beam-size] [-f firstStation] [-h] [-H history-file] [-i] [-n] [-s time] [-S] < traintrips.txt
note: expected input line formats:
1. hash sign distance start-station end-station
... | StarcoderdataPython |
32993 | import numpy as np
import random
N = 10
def null(a, rtol=1e-5):
u, s, v = np.linalg.svd(a)
rank = (s > rtol*s[0]).sum()
return rank, v[rank:].T.copy()
def gen_data(N, noisy=False):
lower = -1
upper = 1
dim = 2
X = np.random.rand(dim, N)*(upper-lower)+lower
while True:
Xsa... | StarcoderdataPython |
3382400 | <gh_stars>0
# coding=utf-8
# Copyright 2020 <NAME>.
"""TF2 Qtran Implementation."""
# Import all packages
from catch_prey.utils import batched_index
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Lambda
from catch_prey import replay2
import tensorflow as tf
class Qtran(object):
... | StarcoderdataPython |
102704 | <filename>main/plugins/simsimi.py
#!/usr/bin/python
# coding=utf-8
import time
from datetime import datetime
from main import redis
from ..models import get_user_info, save_user_info
# 数据录入
def check_in(openid, benchpress,deadlift,squat,
ytxs,fwc,gwxl,shoulderpress):
current_milli_time = int(round(t... | StarcoderdataPython |
1723028 | <reponame>firefly2442/aoc-2018<gh_stars>0
from modules import console
from modules.config.enums import Actions, SleepState
from modules.guard import GuardProcessor
from .state import State
from .state_machine import FiniteStateMachine
class SleepingState(State):
@staticmethod
def execute(fsm: FiniteStateMachi... | StarcoderdataPython |
1629511 | import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import layers
import numpy as np
import csv
import sys
import os
# Import utility functions from 'utils.py' file
from utils import checkFolders, show_variables, add_suffix, backup_configs
# Import convolution layer definitions from 'convolution l... | StarcoderdataPython |
1798592 | # Imports
# ============================================================================
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import re
import os
from ansible.errors import AnsibleError
def startswith(string, prefix):
'''
>>> startswith('bigfoot'... | StarcoderdataPython |
192127 | <reponame>NorthernForce/frisbee-to-raspberry-pi
# This class provides a way to drive a robot which has a drive train equipped
# with separate motors powering the left and right sides of a robot.
# Two different drive methods exist:
# Arcade Drive: combines 2-axes of a joystick to control steering and driving speed.
#... | StarcoderdataPython |
1768257 | <reponame>flopezag/fiware-tsc-dashboard
from github import Github
from config.settings import GITHUB_TOKEN
__author__ = '<NAME>'
gh = Github(login_or_token=GITHUB_TOKEN)
repo = gh.get_user('telefonicaid').get_repo("fiware-orion")
releases = repo.get_releases()
download_count = n_assets = 0
for rel in releases:
as... | StarcoderdataPython |
1731144 | import os
from PIL import Image
import numpy as np
from scipy.interpolate import griddata
import cv2
import argparse
def getSymXYcoordinates(iuv, resolution=256, dp_uv_lookup_256_np=None):
if dp_uv_lookup_256_np is None:
dp_uv_lookup_256_np = np.load('util/dp_uv_lookup_256.npy')
xy, xyMask = getXYcoor(... | StarcoderdataPython |
73873 | <filename>test_op_detect.py
import unittest
import operation_detection
class TestOpDetect(unittest.TestCase):
def testIsListTrue(self):
test_string = "(a b)"
ret_val = operation_detection.isList(test_string)
self.assertTrue(ret_val)
def testIsListFalse(self):
test_string =... | StarcoderdataPython |
7122 | <filename>src/ITN/srmg/core/RiemannianRight.py
#!/usr/bin/env python
# coding=utf-8
'''
Author: <NAME> / Yulv
Email: <EMAIL>
Date: 2022-03-19 10:33:38
Motto: Entities should not be multiplied unnecessarily.
LastEditors: <NAME>
LastEditTime: 2022-03-23 00:52:55
FilePath: /Awesome-Ultrasound-Standard-Plane-Detection/src/... | StarcoderdataPython |
67234 | <reponame>atksh/datasets
# coding=utf-8
# Copyright 2019 The TensorFlow Datasets 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
#
... | StarcoderdataPython |
1724148 | import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class TrfJitter(BaseEstimator, TransformerMixin):
def __init__(self, snrdb, p=1, verbose=0):
self.snrdb = snrdb
self.snr = 10 ** (self.snrdb/10)
self.p = p
self.verbose = verbose
def fit(self, X, y=None... | StarcoderdataPython |
1652542 | #!/usr/bin/python
def imageVel(east_grd_path):
import matplotlib;
import matplotlib.pyplot;
import os;
from scipy.io import netcdf;
assert os.path.exists(east_grd_path), "\n***** ERROR: " + east_grd_path + " does not exist\n";
north_grd_path = east_grd_path.replace("east", "north");
mag_grd_path = east_gr... | StarcoderdataPython |
1736678 | <gh_stars>1-10
import glob
import math
import os
import pickle as pkl
import random
import shutil
import datetime
from collections import deque
from hashlib import sha1
from os.path import join, isfile
import cv2
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
import networkx as nx
fr... | StarcoderdataPython |
100874 | <reponame>ellisonch/kinc
import sys
n = sys.argv[1]
s = 0
while (not(n <= 0)):
s = s + n
n = n + -1
print s
| StarcoderdataPython |
1654766 | <filename>algo/lis.py
arr = [1, 6, 3, 5, 9, 7]
ans = [1]
for i in range(1, len(arr)):
t = []
for j in range(i):
if arr[i] > arr[j]:
t.append(ans[j]+1)
else:
t.append(ans[j])
ans.append(max(t))
print max(ans)
| StarcoderdataPython |
4808414 | <filename>service/service_voice_authenticator.py
import sys
import os
import json
import time
from pathlib import Path
from breaker_core.datasource.jsonqueue import Jsonqueue
from breaker_core.datasource.bytessource import Bytessource
from breaker_core.common.service_jsonqueue import ServiceJsonqueue
from breaker_a... | StarcoderdataPython |
3345565 | <reponame>xxiro/UBC_Triumf_Workshop
# Copyright 2020 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | StarcoderdataPython |
1686124 | import os
from typing import List
from typing import Tuple
import logging
from collections import defaultdict
from collections import Counter
import json
import torch
import numpy as np
from GroundedScan.dataset import GroundedScan
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logger = logging... | StarcoderdataPython |
3315574 | import cv2
import numpy as np
import os
from utils import *
class CircleDetector:
def __init__(self):
pass
class SimpleTemplateDetector:
def __init__(self, symdir="data/data_SI/symbols_png"):
self.symdir = symdir
symbols = [
os.path.join(symdir, x) for x in os.listdir(symd... | StarcoderdataPython |
87394 | from utils.object_detection import *
from utils.pose_estimation import *
from utils.utils import *
| StarcoderdataPython |
77476 | """Initial models
Revision ID: b41a0816fcda
Revises:
Create Date: 2020-04-14 07:29:41.924866
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated ... | StarcoderdataPython |
111241 | <gh_stars>0
class A187:
pass
| StarcoderdataPython |
3394046 | <gh_stars>10-100
import uuid
from functools import lru_cache
from io import BytesIO
from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse_lazy
from django.views.generic import TemplateView, FormView, View
from dj... | StarcoderdataPython |
184826 | from model.gcn import GCN
from torch import nn
import torch
if __name__ == '__main__':
gcn = GCN(1, 1024)
node = torch.randn((2, 10, 1024))
labels = torch.cat([torch.ones((2, 4)), torch.zeros((2, 6))], dim=-1)
coords = torch.randn((2, 10, 4))
image_shapes = (224, 224)
node_list, human... | StarcoderdataPython |
3303111 | <reponame>almonds0166/BCN
import sys; sys.path.append("../")
from pathlib import Path
import re
from matplotlib import pyplot as plt
import numpy as np
from bcn import Results, Dataset, Connections
#from bcn.branches import DirectOnly
#from bcn.branches.uniform import (NearestNeighbor, NearestNeighborOnly,
# ... | StarcoderdataPython |
1732621 | #
# Tests for the lithium-ion half-cell SPMe model
# This is achieved by using the {"working electrode": "positive"} option
#
import pybamm
import unittest
from tests import BaseUnitTestLithiumIonHalfCell
class TestSPMeHalfCell(BaseUnitTestLithiumIonHalfCell, unittest.TestCase):
def setUp(self):
self.mode... | StarcoderdataPython |
1772905 | <reponame>dexy/cashew
### "import"
from example.classes import Data
### "plugins"
Data.plugins
import example.classes1
Data.plugins
### "example-data"
example_data = [{
"foo" : 123,
"bar" : 456
}]
### "json-example-type"
json_data = Data.create_instance('json', example_data)
type(json_data)
### "csv-exa... | StarcoderdataPython |
3324675 | <filename>Energy Transport/Heat Diffusion/simple_1d_transient_diffusion.py<gh_stars>0
from math import *
import matplotlib.pyplot as plt
from matplotlib import style
style.use('seaborn')
from live_plot import LivePlot
live_plot = LivePlot(window_title='Unidimensional Transient Diffusion', xlabel='Width', ylabel='Tem... | StarcoderdataPython |
186433 | """
An underground railway system is keeping track of customer travel times between different stations.
They are using this data to calculate the average time it takes to travel from one station to another.
Implement the UndergroundSystem class:
- void checkIn(int id, string stationName, int t)
A customer ... | StarcoderdataPython |
107667 | from pathlib import Path
import numpy as np
import pandas as pd
import nibabel as nib
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
color_tables_dir = Path(__file__).parent
class Parcellation:
def __init__(self, parcellation_path):
self.parcellation_path = Path(parcellation_path)
... | StarcoderdataPython |
1761475 | <reponame>woodenCaliper/UpdateFusionPathForLogicool
#Author-woodenCaliper
#Description-fusion360がアップデートをするたびにexeのファイルパスが変わり、そのたびにlogicoolのプロファイルのリンクを修正する作業を自動化
import adsk.core, adsk.fusion, adsk.cam, traceback
import xml.etree.ElementTree as ET
import glob
import shutil, datetime
def serchTargetFile():
# logic... | StarcoderdataPython |
1655244 | <reponame>TheSampaio/DesktopVirtualAssistant
from os import truncate
from Includes import os, shutil, sleep
from AssistantConfig import voice, USERPATH
TIME = 10
def extension_type(event): # Get file's extension
if event.src_path[event.src_path.rindex('.') + 1:] != 'tmp' or 'crdownload':
return event.src_... | StarcoderdataPython |
3322157 | <gh_stars>0
from torchvision import transforms
from dataset.mscoco import MSCOCO
from torch.utils.data import DataLoader
from pytorch_lightning import LightningDataModule
from torch import tensor
class BaselineDataModule(LightningDataModule):
def __init__(self, batch_size):
super().__init__()
self.batch_size... | StarcoderdataPython |
73890 | import json
import re
import ast
all_courses_file = "../vue-app/data/allCourses.json"
major_reqs_file = "../vue-app/data/course_requirements.json"
def read_data_files(all_courses_file, major_reqs_file):
with open(all_courses_file, 'r') as f:
all_courses = json.load(f)
with open(major_reqs_file, 'r') ... | StarcoderdataPython |
3211290 | #!/usr/bin/env python3
def write_todo(open_file, todo):
line = ' - ' + todo + '\n'
open_file.write(line)
def write_todos_for_module(open_file, todo_list):
for todo in todo_list:
write_todo(open_file, todo)
def write_newline(open_file):
open_file.write('\n')
def format_as_detail... | StarcoderdataPython |
152680 | #!/usr/bin/python3
import sys
# stream processing
# streams have groups and garbage.
# groups are delimited by {}.
# groups can contain other groups and garbage.
# garbage is delimited by <>.
# garbage can't contain groups.
# any character followed by ! is cancelled.
# goal is to find total score for all groups.
# g... | StarcoderdataPython |
3267512 | <reponame>w60083/SocialNetworkAPI
from django.urls import path, include
from . import views
urlpatterns = [
path('', include('User.urls')),
]
| StarcoderdataPython |
3293748 | from random import *
N = 100
n = randrange(2,N+1)
m = randrange(1,1+(n*(n+1)))
print n,m
for i in xrange(m):
a = randrange(1,n+1)
b = randrange(1,n+1)
print a, b
| StarcoderdataPython |
1639028 | <reponame>qfgaohao/keras-io
"""
Title: Using pre-trained word embeddings
Author: [fchollet](https://twitter.com/fchollet)
Date created: 2020/05/05
Last modified: 2020/05/05
Description: Text classification on the Newsgroup20 dataset using pre-trained GloVe word embeddings.
"""
"""
## Setup
"""
import numpy as np
impo... | StarcoderdataPython |
1727758 | # -*- coding: utf-8 -*-
from datetime import datetime
try:
import requests
except ImportError:
from .packages import requests
DEFAULT_LOGPLEX_URL = 'https://east.logplex.io/logs'
DEFAULT_LOGPLEX_TOKEN = None
DETAULT_LOGPLEX_TIMEOUT = 2
class Logplex(object):
"""A Logplex client."""
def __init__(se... | StarcoderdataPython |
3280980 | <filename>superset/databases/filters.py<gh_stars>1-10
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... | StarcoderdataPython |
82624 | import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter, num2date
from matplotlib import patches
import matplotlib.patches as mpatches
from matplotlib import ticker, cm, colors
import sys
sys.path.insert(0, ... | StarcoderdataPython |
191915 | <reponame>scramjetorg/framework-python<gh_stars>10-100
from scramjet.pyfca import Pyfca, DropChunk
import asyncio
from scramjet.ansi_color_codes import *
from os import environ
import scramjet.utils as utils
from collections.abc import Iterable, AsyncIterable
import re
DEBUG = 'DATASTREAM_DEBUG' in environ or 'SCRAMJE... | StarcoderdataPython |
25232 | <gh_stars>0
test_index = ("2019-05-01", "2020-04-30")
train_index = ("2016-01-02", "2019-04-30")
val_index = ("2018-10-01", "2019-04-30")
| StarcoderdataPython |
1697171 | <reponame>saurabhchardereal/kernel-tracker
import json
from urllib.request import Request, urlopen
class TelegramUtils:
def __init__(self, API: str) -> None:
self.API = API
self.API_URL = f"https://api.telegram.org/bot{self.API}/sendMessage"
self.url_data = {}
def send_to_tg(self, cha... | StarcoderdataPython |
66609 | ################################################################################
# Copyright (C) 2016-2019 Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... | StarcoderdataPython |
3225143 | <reponame>sumedhpb/testrunner<filename>pytests/upgrade/xdcr_upgrade_collections.py
import queue
import copy, json
from .newupgradebasetest import NewUpgradeBaseTest
from remote.remote_util import RemoteMachineShellConnection, RemoteUtilHelper
from couchbase_helper.documentgenerator import BlobGenerator
from membase.api... | StarcoderdataPython |
56085 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import regex as re
fontmap_directory = os.path.dirname(__file__) + '/fontmaps/'
fontmaps = {}
for font in ['JG_Pahawh_Third_Version', 'JG_Pahawh_Final_Version']:
fontmaps['{}.ttf'.format(font)] = json.load(open(fontmap_directory + '{}.json'.for... | StarcoderdataPython |
4814028 | <gh_stars>0
from tkinter import *
from tkinter.filedialog import askopenfilename
import xlrd
import pandas as pd
from tkinter.ttk import Combobox
from PIL import Image,ImageTk
import clusters1
dendogram_file_name='clusters.jpg'
class PoliCluster:
def __init__(self,data_center):
self.data_center=data_cente... | StarcoderdataPython |
3302628 | <gh_stars>0
import logging
from datetime import datetime, timezone
from queue import Queue
from threading import Lock
from dateutil import parser as dateparser
from google.api_core.exceptions import BadRequest
from google.cloud import bigquery, storage
LOG = logging.getLogger("smart_archiver." + __name__)
def event... | StarcoderdataPython |
1785410 | #!/usr/bin/env python
#
# textpanel.py - A panel for displaying horizontal or vertical text.
#
# Author: <NAME> <<EMAIL>>
#
"""This module provides the :class:`TextPanel` class, for displaying
some text, oriented either horizontally or vertically.
"""
import wx
class TextPanel(wx.Panel):
"""A :class:`wx.PyPanel... | StarcoderdataPython |
52572 | import hammer as h
signals = h.choice(
h.token("hmi.signal1"),
h.token("hmi.signal2"),
h.token("hmi.signal3"))
| StarcoderdataPython |
143518 | <reponame>lyskevin/cpbook-code
import math
INF = 10**9
EPS = 1e-9
def DEG_to_RAD(d):
return d*math.pi/180.0
def RAD_to_DEG(r):
return r*180.0/math.pi
class point_i:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def ... | StarcoderdataPython |
3350102 | <gh_stars>0
class Properties:
"""
Keys to access structure properties in `schnetpack.data.AtomsData`
"""
# geometry
Z = "_atomic_numbers"
charge = "_charge"
atom_mask = "_atom_mask"
position = "_positions"
R = position
cell = "_cell"
pbc = "_pbc"
neighbors = "_neighbors"... | StarcoderdataPython |
112079 | import os
import pytest
from torchvision.transforms import Resize, ToTensor
from continuum.datasets import CUB200
from continuum.scenarios import ClassIncremental
DATA_PATH = os.environ.get("CONTINUUM_DATA_PATH")
'''
Test the visualization with instance_class scenario
'''
@pytest.mark.slow
def test_scenario_CUB200_... | StarcoderdataPython |
1670598 | <gh_stars>1-10
from foo import Foo
print(Foo().scope) | StarcoderdataPython |
105378 | from oauth.oauth import OAuthRequest, OAuthServer, build_authenticate_header,\
OAuthSignatureMethod_PLAINTEXT, OAuthSignatureMethod_HMAC_SHA1
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
import ast
OAUTH_REALM_KEY_NAME = getattr(settings, 'OAUTH_REALM_KEY_NAM... | StarcoderdataPython |
3278057 | <filename>order_fulfillment/order_fulfillment_multi_item.py
# This code contains all heuristics for multi-item orders, namely LSC, SPS and Greedy.
# It takes the data as input and returns the cost and store assignment as output.
import itertools
from functools import reduce
import operator
from pyomo.environ import *
... | StarcoderdataPython |
1650236 | <reponame>zalanborsos/coresets
from __future__ import division, absolute_import
from coresets.coreset import Coreset
from coresets.k_means_coreset import KMeansLightweightCoreset, KMeansCoreset, KMeansUniformCoreset
from coresets.sensitivity import kmeans_sensitivity | StarcoderdataPython |
4826178 | <gh_stars>10-100
#!/usr/bin/python3
import requests
import argparse
from pprint import pprint
from time import sleep
def get_ticker(sym_pair, init=False):
url = 'https://arbitrage-logger.firebaseio.com/log_{}.json?orderBy="$key"&limitToLast=1'.format(sym_pair)
while True:
r = requests.get(url)
... | StarcoderdataPython |
4823053 | #!/usr/bin/python3.6
"""Calculations for a single TIMD.
TIMD stands for Team In Match Data. TIMD calculations include
consolidation of (up to) 3 tempTIMDs (temporary TIMDs) into a single
TIMD, and the calculation of data points that are reflective of a team's
performance in a single match.
Consolidation is the proce... | StarcoderdataPython |
1601436 | """
*A - Level 2*
"""
from .._pitch import Pitch
__all__ = ["A_2"]
class A_2(
Pitch,
):
pass
| StarcoderdataPython |
1619622 | from dialog_bot_sdk.bot import DialogBot
from config.config import bot
import db.db as core_db
def add_event(peer: str, command: str):
print("!", command)
core_db.add_event(int(peer.id), command)
send_message(
peer,
'added event'
)
def add_review(peer: str, command: str):
str1, s... | StarcoderdataPython |
1706430 | #!/usr/bin/env python3
import datetime
import json
import os
import pathlib
import re
from typing import Any, Callable, Dict, List, Optional, cast
from urllib.request import urlopen
def get_disabled_issues() -> List[str]:
pr_body = os.getenv("PR_BODY", "")
commit_messages = os.getenv("COMMIT_MESSAGES", "")
... | StarcoderdataPython |
3266264 | <filename>calc_hpi.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
calc_hpi.py
===========
Compute the auroral hemispheric power from an SWMF IDL file.
Created on Wed Dec 2 03:45:37 2020
@author: <NAME>
University of Michigan
Ann Arbor, MI
"""
import numpy as np
from spacepy.pybats import ri... | StarcoderdataPython |
1622043 | <filename>finite-mdp/setup.py
from setuptools import setup, find_packages
setup(
name='finite-mdp',
version='1.0.dev0',
description='Gym environment for MDPs with finite state and action spaces',
url='https://github.com/eleurent/finite-mdp',
author='<NAME>',
author_email='<EMAIL>',
classifi... | StarcoderdataPython |
1755002 | <reponame>steingabelgaard/reportlab
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
from tools.docco.rl_doc_utils import *
heading1("Graphics")
heading2("Introduction")
disc("""
ReportLab Graphics is one of the sub-packages to the ReportLab
library. It started off ... | StarcoderdataPython |
3398200 | #!/usr/bin/env python3
import re
import json
import os
import numpy as np
import matplotlib.pyplot as plt
from itertools import tee
def parse_data(folder):
data = []
for filename in os.listdir(folder):
fullname = os.path.join(folder, filename)
if fullname.endswith('.txt'):
with op... | StarcoderdataPython |
4839748 | #estrutura de repetição for;
#Criei uma função sem parâmetros;
#Declarei variável com o comando FOR para colocá-la dentro de um intervalo;
#Para criar um intervalo usa o comando range;
#Os valores impressos irão de 5 até 9, pois o limite do intervalo não entra.
def estruturaFor():
for x in range(5,10):
pr... | StarcoderdataPython |
9677 | <reponame>piotr-karon/realworld-starter-kit
#!/usr/bin/env python3
import json
import os
from pathlib import Path
import numpy as np
from natsort import natsorted
try:
from docopt import docopt
from marko.ext.gfm import gfm
import pygal
from pygal.style import Style, DefaultStyle
except ImportError a... | StarcoderdataPython |
3327415 | <gh_stars>0
from base64 import b64encode
import json
import requests
import sys
__docformat__ = 'sphinx en'
class Pyrate(object):
"""This is the main class
:param list http_methods: List of available HTTP methods for this service
:param list return_formats: List of available return formats for this servi... | StarcoderdataPython |
3253589 | <gh_stars>1-10
import os
import shutil
import time
def get_metadata_paths(CONFIG, ARGS):
print("Creating experiment enviroment")
metadata_path = "{}/{}/{}".format(CONFIG.network.metadata.path, CONFIG.network.parameters.model_name, time.strftime("%d-%m-%Y"))
n_experiment = "1"
if os.path.exists(metadat... | StarcoderdataPython |
1617227 | <reponame>Davy-71993/MySchool<gh_stars>0
from django.contrib import admin
from .models import Calendar, Event, Term
admin.site.register(Calendar)
admin.site.register(Event)
admin.site.register(Term)
# Register your models here.
| StarcoderdataPython |
1624336 | <reponame>movermeyer/django-contact-form-site<filename>django_contact/__init__.py
from django_contact.forms import ContactForm
__all__ = ['ContactForm']
default_app_config = 'django_contact.apps.ContactFormConfig' | StarcoderdataPython |
1702107 | from GameElementBase import GameElementBase
class LivingThings(GameElementBase):
def __init__(self,position,beingid):
self.beingid=beingid
self.position = position
self.mapsize=[3,3]
self.inventory=[]
def move(self,direction):
flag=False
if direction=="n":
... | StarcoderdataPython |
3288199 | import logging,time
log_filename = r'./log/rg' + time.strftime('_%Y%m%d') + '.log'
logger = logging.getLogger('rg_log')
logger.setLevel(logging.INFO)
# 调用模块时,如果错误引用,比如多次调用,每次会添加Handler,造成重复日志,这边每次都移除掉所有的handler,后面在重新添加,可以解决这类问题
while logger.hasHandlers():
for i in logger.handlers:
logger.removeHandler(i)... | StarcoderdataPython |
139323 | <reponame>pjreed/rr_control_input_manager<gh_stars>0
#!/usr/bin/env python
# Author: <NAME>
# Description: This script manages cmd_vel from multiple sources so that they don't over-ride eachother, and so that soft E-stop can works from multiple sources.
import rospy
import time
from std_msgs.msg import Bool, String... | StarcoderdataPython |
3294251 | import logging
from dotenv import find_dotenv, dotenv_values
def load_config():
""" Load the variables from the .env file
Returns:
.env variables(dict)
"""
logger = logging.getLogger(__name__)
dot_env_path = find_dotenv(raise_error_if_not_found=True)
logger.info(f"Found config in {do... | StarcoderdataPython |
3263412 | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
P = [0]
for x in A: P.append(P[-1] + x)
count = collections.Counter()
ans = 0
for x in P:
ans += count[x]
count[x + S] += 1
return ans
| StarcoderdataPython |
1687006 | <reponame>Guo-T-W/Tacotron-WaveRNN
import tensorflow as tf
# Default hyperparameters
hparams = tf.contrib.training.HParams(
# Comma-separated list of cleaners to run on text prior to training and eval. For non-English
# text, you may want to use "basic_cleaners" or "transliteration_cleaners".
cleaners='eng... | StarcoderdataPython |
1744367 | import sys, os
base_path = os.path.dirname(os.path.realpath(__file__)).split('reproduce_results')[0]
sys.path.append(base_path)
from helper_functions import wilcoxon_statistical_test
import json
import warnings
warnings.filterwarnings('ignore')
path = base_path+"Datasets/mutagenesis/Results"
print()
print('#'*50)
p... | StarcoderdataPython |
37043 | class Stack():
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.item... | StarcoderdataPython |
4821060 | import logging
from flask import jsonify, request
import flask_login
import mediacloud.error
from server import app, mc
import server.views.apicache as base_apicache
from server.auth import user_mediacloud_client, user_mediacloud_key
from server.util.request import form_fields_required, api_error_handler, json_error_r... | StarcoderdataPython |
1627270 | from setuptools import setup
import braces
setup(
name="django-braces",
version=braces.__version__,
description="Reusable, generic mixins for Django",
long_description="Mixins to add easy functionality to Django class-based views, forms, and models.",
keywords="django, views, forms, mixins",
a... | StarcoderdataPython |
1793559 | <filename>purdy/colour/plainco.py
from purdy.parser import FoldedCodeLine
# =============================================================================
# Plain Colourizer: the colourizer that doesn't do colour, handles plain text
# augmentation like line numbers for uncolourized display
class PlainColourizer:
@... | StarcoderdataPython |
3312566 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: srinath.h
#
# Created: 13/05/2012
# Copyright: (c) srinath.h 2012
# Licence: <your licence>
#----------------------------------------------------------------------------... | StarcoderdataPython |
1787178 | <gh_stars>1-10
import os
import shutil
from . import asciifileparser
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def parse(filePath):
"""
Returns a full parsed Maya ASCII file.
:type filePath: str
:rtype: mason.asciiscene.AsciiScene
"""
... | StarcoderdataPython |
160497 | import MySQLdb
from Model.pessoa_model import PessoaModel
class PessoaDao:
# --- Inicialização da conecção com o servidor local
# --- Inicialização do cursor para manter conecção
def __init__(self):
self.connection = MySQLdb.connect(host='mysql.padawans.dev',database='padawans16',user='padawans16'... | StarcoderdataPython |
19674 | <reponame>maxburke/arrow<gh_stars>0
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version ... | StarcoderdataPython |
23187 | # from pipet.core.sql.query_interface import *
from pypipet.core.operations.inventory import *
import pytest
from pprint import pprint
_supplie_id = 1
def test_update_invs(session, obj_classes, shop_conn):
invs = [ {'sku':'s22456', 'supplier_id':_supplie_id, 'qty':20}]
update_inventory_bulk(obj_classes, sess... | StarcoderdataPython |
3333768 | <filename>scripts/install_on_ubuntu.py
#!/usr/bin/env python3
import json
import os
import shutil
import sys
from os import path
sys.path.append("src")
# noinspection PyPep8
from fvttmv.config import Keys
# noinspection PyPep8
from cli_wrapper.__constants import app_name, path_to_config_file_linux
path_to_executable... | StarcoderdataPython |
1730580 | # Remove Element
#
# Given an array and a value, remove all instances of that value in-place and return the new length.
#
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#
# The order of elements can be changed. It doesn't matter what you l... | StarcoderdataPython |
18766 | class BaseFunction:
def __init__(self, name, n_calls, internal_ns):
self._name = name
self._n_calls = n_calls
self._internal_ns = internal_ns
@property
def name(self):
return self._name
@property
def n_calls(self):
return self._n_calls
@property
def... | StarcoderdataPython |
132843 | <filename>PhotoNAS/dataset.py
import numpy as np
import os
import cv2
from torch.utils.data import Dataset
from torchvision import transforms
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
from matplotlib import pyplot as plt
class TransferDataset(Dataset):
def __init__(self, content_dir):
super(Tra... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.