id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3290941 | <reponame>pengjunn/KD-GAN<gh_stars>0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from nltk.tokenize import RegexpTokenizer
from collections import defaultdict
from miscc.config import cfg
import torch
... | StarcoderdataPython |
3244236 | import torch
class AnchorGenerator(object):
def __init__(self, anchor_range, anchor_generator_config):
super().__init__()
self.anchor_generator_cfg = anchor_generator_config # list:3
# 得到anchor在点云中的分布范围[0, -39.68, -3, 69.12, 39.68, 1], [0, -40, -3, 70.4, 40, 1]
self.anchor_range =... | StarcoderdataPython |
3378540 | import os
import subprocess
from shulkr.minecraft.source import detect_mappings, generate_sources
class GitTree:
def __init__(self, name: str = None) -> None:
self.name = name
class SubprocessMock:
def __init__(self, returncode=0, stderr=None):
self.returncode = returncode
self.stderr = stderr
def test_d... | StarcoderdataPython |
1681967 | <filename>scripts/filter.py
#!/usr/bin/env python
#--------Include modules---------------
from copy import copy
import rospy
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import PointStamped
import tf
from numpy import array... | StarcoderdataPython |
150763 | import csv
import os
import time
from SignalModel import TrainingModel
from SignalModel import SignalsClassifier
import re
import pandas as pd
import SymSpell
from utils.utils import read_glove_vecs
from Spec import Specification
#0019_DTC, 0027_NET, 0054_HBA, 0057_HRB, 0058_HFC, 0061_HHC, 0062_AVH, 0068_AEB, 0069_CDP... | StarcoderdataPython |
106155 | <reponame>jkingsman/mockmail.io
import smtpd
import random
import pprint
import asyncore
from email.parser import Parser
from twisted.internet import task
from Config import bindingPort, bindingIP, dropSize
staged = []
class MailboxHandler():
def __init__(self, queue):
self.binding = (bindingIP, bindingP... | StarcoderdataPython |
1631103 | <gh_stars>0
from prefixspan import PrefixSpan
w_shot = 2
w_pass = 0.5
w_other = 1
def getweight(e):
if e < 10 :
return w_other
elif e < 35:
return w_pass
else:
return w_shot
# 模式的类
class Pattern:
def __init__(self, freq, flow):
super(Pattern, self).__init__()
... | StarcoderdataPython |
158840 | """Windows base service implementation.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import errno
import functools
import logging
import os
# Disable E0401: unable to import on linux
import win32security # py... | StarcoderdataPython |
3207569 | ###############################################################################
#Author: <NAME>
#Filename: Library.py
#Application: DragonShout
#Date: June 2014
#Description: Contain the class for handling the library file (saving and
# loading)
#
# Class Library:
# _name as string
# Conta... | StarcoderdataPython |
3365702 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import datetime
import os
import pyoozie
import pytest
import pywebhdfs.webhdfs
import six
@pytest.mark.skipif(not bool(os.environ.get(str('INTERACTIVE'))), reason='Requires INTERACTIVE=1 env var')
def test_pyoozie... | StarcoderdataPython |
3359638 | <reponame>xashru/robust-vad<gh_stars>1-10
from .cnn import *
from .dnn import DNN20
from .lstm import LSTM
from .preact_resnet import PreActResNet18
| StarcoderdataPython |
1636186 | <filename>settings/diffractometer/NIH Diffractometer_settings.py
phi_motor_name = 'SamplePhi'
phi_scale = 1.0
rotation_center_x = -1.2333
rotation_center_y = 2.0598
x_motor_name = 'SampleX'
x_scale = 1.0
xy_rotating = False
y_motor_name = 'SampleY'
y_scale = 1.0
z_motor_name = 'SampleZ'
z_scale = 1.0
| StarcoderdataPython |
1667560 | <reponame>NengLu/topopy
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 10 09:32:58 2018
@author: vicen
"""
import warnings
warnings.filterwarnings('ignore')
import sys
import numpy as np
from scipy import ndimage
# Add to the path code folder and data folder
sys.path.append("../")
from topopy i... | StarcoderdataPython |
3358137 | <reponame>psorus/f
from param1 import *
from collector import *
from transform import addtrafo,addinv
import fmath
import math
class atanh(param1):
def __init__(s,p):
param1.__init__(s)
s.q=p
def diff(s,by)->'mult':
return s.q.diff(by)/(fmath.value(1)-fmath.square(s.q))
def eval(s,**v)->float:
... | StarcoderdataPython |
110514 | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
1675332 | class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1
elif n == 1:
return 0
b = "".join("0" if x == "1" else "1" for x in bin(n)[2:])
return int(b, 2)
| StarcoderdataPython |
100170 | # -*- coding: utf-8 -*-
from pyleecan.Classes.NodeMat import NodeMat
import numpy as np
def get_all_node_coord(self, group=None):
"""Return a matrix of nodes coordinates and the vector of nodes tags corresponding to group.
If no group specified, it returns all the nodes of the mesh.
Parameters
-----... | StarcoderdataPython |
3213767 | import gym
env = gym.make('MsPacman-v0')
print(env.action_space)
#> Discrete(2)
print(env.observation_space)
#> Box(4,)
print(env.observation_space.high)
#> array([ 2.4 , inf, 0.20943951, inf])
print(env.observation_space.low)
#> array([-2.4 , -inf, -0.20943951, -inf])
from gy... | StarcoderdataPython |
86376 | <reponame>flyflyinit/GUI-admin-tool
from PyQt5.QtCore import Qt
try:
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QProgressBar, QPushButton, QSpinBox, QLabel, QLineEdit, \
QFormLayout, \
QHBoxLayout, QListWidget, QMessageBox, QCheckBox
except ImportError as e:
print(
f'package PyQt... | StarcoderdataPython |
5463 | <gh_stars>1-10
import re
regex = re.compile(r'[\n\r\t]')
def acm_digital_library(soup):
try:
keywords = set()
keywords_parent_ol = soup.find('ol', class_="rlist organizational-chart")
keywords_divs = keywords_parent_ol.findChildren('div', recursive=True)
for kw_parent in keywords_... | StarcoderdataPython |
147619 | ## data folder: D:\work\project\ITA Refresh\Session4 Oil Prediction
# -*- coding: utf-8 -*-
from __future__ import print_function
import time
import warnings
import numpy as np
import time
import matplotlib.pyplot as plt
from numpy import newaxis
from keras.layers.core import Dense, Activation, Dropout
from keras.la... | StarcoderdataPython |
1782891 | <gh_stars>0
from setuptools import setup
package_name = 'perception_genie'
setup(
name=package_name,
version='0.1.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']... | StarcoderdataPython |
62498 | # Copyright (C) 2018 DataArt
#
# 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 agreed to in writing, ... | StarcoderdataPython |
171543 | #!/usr/bin/env python3
"""scapy-dhcp-listener.py
Listen for DHCP packets using scapy to learn when LAN
hosts request IP addresses from DHCP Servers.
Copyright (C) 2018 <NAME>
https://jcutrer.com/python/scapy-dhcp-listener
License Dual MIT, 0BSD
Extended by jkulawik, 2020
"""
from __future__ import print_function
fro... | StarcoderdataPython |
45293 | <filename>Problems/Dynamic Programming/Easy/BuySellStock1/buy_sell_stock_1.py
from typing import List
def max_profit_1(prices: List[int]) -> int:
min_price, max_profit = prices[0], 0
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_p... | StarcoderdataPython |
101975 | #!/usr/local/bin/python3
from random import randint
def sortea_numero():
return randint(1, 6)
def eh_impar(numero: float):
return numero % 2 != 0
def acertou(numero_sorteado: float, numero: float):
return numero_sorteado == numero
if __name__ == '__main__':
numero_sorteado = sortea_numero()
... | StarcoderdataPython |
1663544 | # !/usr/bin/env python
# encoding: utf-8
"""
@version: 0.1
@author: feikon
@license: Apache Licence
@contact: <EMAIL>
@site: https://github.com/feikon
@software: PyCharm
@file: exceptin_handle.py
@time: 2017/6/8 21:20
"""
import logging
try:
print('try...')
r = 10 / 0
print('result:', r)
except ZeroDi... | StarcoderdataPython |
128266 | <filename>CloudflareAPI/core/base.py
#!/usr/bin/env python3
from requests import Session
from typing import Dict, Optional
from .network import Request
from .configuration import Config
config = Config()
class CFBase:
def verify_token(self, token) -> bool:
url = "https://api.cloudflare.c... | StarcoderdataPython |
1780216 | import requests
import string
url = 'https://cat-step.disasm.me/'
prefix = 'spbctf{'
suffix = '}'
flag = '#' * 28
alpha = string.ascii_letters + string.digits + '_-'
left = 0
while left != len(flag):
for a in alpha:
flag = flag[:left] + a + flag[left + 1:]
attempt = prefix + flag + suffix
... | StarcoderdataPython |
3230368 | from collections.abc import MutableSequence
from typing import Iterable, Union, Sequence
from google.protobuf.pyext._message import RepeatedCompositeContainer
from ...proto.jina_pb2 import DocumentProto
if False:
from ..document import Document
__all__ = ['DocumentSet']
class DocumentSet(MutableSequence):
... | StarcoderdataPython |
39267 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='certbot_adc',
version='0.1',
description="perform certbot auto dns challenge with DNS provider's API",
url='http://github.com/btpka3/certbot-auto-dns-challenge',
author='btpka3',
author_email='<E... | StarcoderdataPython |
46906 | import json
from bson import ObjectId
from pymongo import ReturnDocument
from .exceptions import DBException
class DBActionsMixin:
def __init__(self, model, db):
self._model_cls = model
self._db = db
def add(self, item):
db_obj = self._collection.insert_one(item.prepare_for_db())
... | StarcoderdataPython |
4842928 | import numpy as np
from typing import List, Dict
def calculate_term_frequencies(split_document: List[str], index_map: Dict[str, int]) -> np.ndarray:
occurrences = np.zeros((len(index_map),), dtype=np.uint32)
for word in split_document:
if word in index_map:
occurrences[index_map[word]] += ... | StarcoderdataPython |
3210352 | <reponame>gmjustforfun/code
import time
import matplotlib.pyplot as plt
import numpy as np
from pso.APSO import APSO
from pso.PSO import PSO
import pandas as pd
def sphere2dim(x):
'''
this function is the target funvtion if "population_Distribution_Information_Of_PSO"
r初始为5,在iter==50时,
:param x: variab... | StarcoderdataPython |
3203137 | # -*- coding: utf-8 -*-
# @Time: 2020/3/21 22:48
# @Author: GraceKoo
# @File: 76_minimum-window-substring.py
# @Desc:https://leetcode-cn.com/problems/minimum-window-substring
from collections import Counter
from collections import defaultdict
class Solution:
def minWindow(self, s: str, t: str) -> str:
lef... | StarcoderdataPython |
1620584 | from typing import Generator, Optional, Sequence, Union
from libcst import (
Assign,
AssignTarget,
Decorator,
FlattenSentinel,
ImportFrom,
ImportStar,
Module,
Name,
RemovalSentinel,
)
from libcst import matchers as m
from django_codemod.constants import DJANGO_1_9, DJANGO_2_0
from ... | StarcoderdataPython |
131776 | <reponame>mozillazg/-bustard<gh_stars>10-100
# -*- coding: utf-8 -*-
import json
import os
import pytest
from bustard.app import Bustard
from bustard.utils import to_bytes, to_text
app = Bustard()
current_dir = os.path.dirname(os.path.abspath(__file__))
@pytest.yield_fixture
def client():
yield app.test_client... | StarcoderdataPython |
3378832 | # Copyright 2015-2017, Truveris Inc. All Rights Reserved.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from overpunch import __version__
setup(
name="overpunch",
version=_... | StarcoderdataPython |
168237 | <filename>twitter_axie_giveaway/gift_axie_ocv_lib.py
from __future__ import print_function
from __future__ import division
import cv2 as cv
import numpy as np
import argparse
import os
import config
def compareImages(src, samples_dir):
src_img = cv.imread(src)
hsv_base = cv.cvtColor(src_img, cv.COLOR_BGR2HSV)
... | StarcoderdataPython |
1628817 | <filename>scripts/draw_pics.py
#!/usr/bin/env python
#
# Copyright 2013 <NAME> and <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/LICENS... | StarcoderdataPython |
1787993 | '''
@File :dataloader.py
@Author:Morton
@Date :2020/6/18 16:04
@Desc :The basic loading function to extract raw content and mention graph information from raw data "user_info.xxx.gz".
'''
# -*- coding:utf-8 -*-
import os
import re
import csv
import kdtree
import gensim
import numpy as np
import pandas as pd
import ... | StarcoderdataPython |
187615 | # -*- coding: utf-8 -*-
import pyfits
from pylab import *
import Marsh
import numpy
import scipy
def getSpectrum(filename,b,Aperture,minimum_column,maximum_column):
hdulist = pyfits.open(filename) # Here we obtain the image...
data=hdulist[0].data # ... and we obtain the... | StarcoderdataPython |
1603609 | <reponame>arefmalek/Demographics_Disenfranchisement
# TODO: YES I KNOW THEY BASICALLY ARE ALL THE SAME CODE ITS SUPER REDUNDANT
# ILL FIX SOON
import torch
import torch.nn as nn
import torch.nn.functional as F
class Age(nn.Module):
def __init__(self):
super(Age, self).__init__()
if torch.cuda.is... | StarcoderdataPython |
131176 | <filename>doubly_linked_list_with_tail.py<gh_stars>1-10
"""
Author: PyDev
Description: Doubly Linked List with a Tail consist of a element, where the element is the
skeleton and consist of a value next, and previous variable/element.
There is a Head pointer to refer to the front of the Linked ... | StarcoderdataPython |
44908 | <gh_stars>1-10
#!/usr/bin/env python2
from setuptools import setup
setup(name='indCAPS',
version='0.1',
description='OpenShift App',
author='<NAME>',
author_email='<EMAIL>',
# install_requires=['Flask==0.10.1'],
) | StarcoderdataPython |
3244925 |
class ColumnInfo:
'Data object that holds information about a column and the unique values it has'
def __init__(self, name, dataType, uniqueValues=[]):
self.name=name
self.dataType=dataType
self.uniqueValues=uniqueValues
| StarcoderdataPython |
1771559 | from tensorflow import keras
from tensorflow.keras.models import load_model
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.ince... | StarcoderdataPython |
1726725 | <gh_stars>1-10
# The network config (links to the net) we use for our simulation
sumoConfig = "A9_conf.sumocfg"
# The network net we use for our simulation
sumoNet = "A9.net.xml"
mqttUpdates = False
mqttHost = "localhost"
mqttPort = "1883"
# should it use kafka for config changes & publishing data (else it uses json... | StarcoderdataPython |
3348193 | <reponame>dmartinpro/microhomie
import settings
from homie.constants import FALSE, TRUE, BOOLEAN
from homie.device import HomieDevice
from homie.node import HomieNode
from homie.property import HomieNodeProperty
from machine import Pin
# reversed values for the esp8266 boards onboard led
ONOFF = {FALSE: 1, TRUE: 0, 1... | StarcoderdataPython |
197712 | import argparse
import json
import pandas as pd
from scipy.stats import pearsonr
def main(human_ann_file, metrics_file):
metrics = json.load(open(metrics_file))
metrics['gold_1'] = metrics['g1']
metrics['gold_2'] = metrics['g2']
metrics['gold_3'] = metrics['g3']
human_ann_df = pd.read_csv(human_an... | StarcoderdataPython |
1735820 | <reponame>KyleVaughn/ThermalAnalysisPlots
import matplotlib.pyplot as plt
import matplotlib.font_manager
import numpy as np
import sys
from scipy.signal import savgol_filter
# plots
ExportData_bool = False
plotTempvsMass_bool = False
plotTempvsdmdt_bool = True
plotTempvsdmdt_normalized_bool = False
plotinvKvsdmdt_boo... | StarcoderdataPython |
1785427 | <filename>src/corpus/__init__.py
from corpus.corpus import CorpusAnalyzer
from corpus.cran_corpus import CranCorpusAnalyzer
from corpus.cisi_corpus import CisiCorpusAnalyzer
from corpus.lisa_corpus import LisaCorpusAnalyzer
from corpus.npl_corpus import NplCorpusAnalyzer
from corpus.union_corpus import UnionCorpusAnaly... | StarcoderdataPython |
18554 | <reponame>samuelvp360/Microbiological-Assay-Calculator<filename>MainController.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
from pathlib import Path
from datetime import datetime
from PyQt5 import QtCore as qtc
from PyQt5 import QtWidgets as qtw
from PyQt5 import uic
import numpy as np
from M... | StarcoderdataPython |
3382914 | <gh_stars>0
import csv
import os
class GameState:
def __init__(self):
"""
Initialize game state variables.
"""
self.__quit_game = False
# score parameters
self.__bonus = 20
self.__multiplier = 1
self.__score = 0
self.__nick = 'AAA'
... | StarcoderdataPython |
100517 | from typing import Dict, List, Any
import numpy as np
from overrides import overrides
from .instance import TextInstance, IndexedInstance
from ..data_indexer import DataIndexer
class QuestionPassageInstance(TextInstance):
"""
A QuestionPassageInstance is a base class for datasets that consist primarily of a... | StarcoderdataPython |
1614077 | <filename>DataWrangling/scraping_web.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Please note that the function 'make_request' is provided for
# your reference only.
# You will not be able to to actually use it from within the Udacity web UI.
# Your task is to process the HTML using BeautifulSoup, extract the hid... | StarcoderdataPython |
1711762 | from argparse import ArgumentParser,FileType
import subprocess
import sys
#Var auxs
parser = ArgumentParser("RSolver. SYPER Tool for RSA Challenges")
argumentsinputs = parser.add_argument_group('ARGUMENTS INPUTS')
filesinputs = parser.add_argument_group('FILE INPUTS')
private = parser.add_argument_group('INPUT PRIVA... | StarcoderdataPython |
3276057 | from siteswapClass import siteswap
while True:
swapString = input('siteswap?: ')
if swapString == '':
continue
swap = siteswap(swapString)
if swap.isValid():
print('Valid siteswap: ', end='')
if swap.isMultiplex():
print('M', end='')
if swap.isSync():
... | StarcoderdataPython |
91759 | from __future__ import absolute_import, division, print_function
import cmath
import math
from six.moves import zip
class least_squares:
def __init__(self, obs, calc):
self.obs = obs
self.calc = calc
a, b = self.calc.real, self.calc.imag
self.abs_calc = math.sqrt(a**2 + b**2)
self.delta = self.o... | StarcoderdataPython |
3385875 | <filename>tools/codegen/serialize_json.py
import json
import os
import sys
import re
import glob
from mako import exceptions
from mako.template import Template
from pathlib import Path
class Field(object):
def __init__(self, name, type):
self.name = name
self.type = type
self.getter = None... | StarcoderdataPython |
4808493 | """
do pnet train
"""
import tensorflow as tf
def pnet_train():
print ('do pnet train')
input = tf.keras.layers.Input(shape=[12, 12, 3])
x = tf.keras.layers.Conv2D(10, (3, 3), strides=1, padding='valid', name='conv1')(input)
x = tf.keras.layers.PReLU(shared_axes=[1, 2], name='prelu1')(x)
x = tf.ke... | StarcoderdataPython |
1702501 | <filename>params.py
#environment list for ez switching
envs = ['CartPole-v0', 'Acrobot-v1', 'MountainCar-v0',
'BipedalWalker-v2', 'Pong-v4', 'SpaceInvaders-v0',
'Breakout-v0']
#all retro envs
#retro.list_games()
#retro.list_states(game)
env_name = envs[0]#'SonicTheHedgehog-Genesis'
env_state = 'Gree... | StarcoderdataPython |
12151 | import abc
class SpecSource(abc.ABC):
@abc.abstractmethod
def describe(self) -> str:
"""
Returns:
str to print in case there is an error constructing extractor for tracing back
"""
raise NotImplementedError()
class UnknownSource(SpecSource):
def describe(sel... | StarcoderdataPython |
3304916 | <gh_stars>1-10
from conans import ConanFile, tools
from conans.errors import ConanInvalidConfiguration
required_conan_version = ">=1.33.0"
class DbgMacroConan(ConanFile):
name = "c-dbg-macro"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/eerimoq/dbg-macro"
lice... | StarcoderdataPython |
144336 | from id.trafficmon.objectblob.ObjectBlob import ObjectBlob
import numpy as np
__author__ = 'Luqman'
class ObjectBlobManager(object):
blob_map = None
image_reference = None
max_id = 0
def __init__(self, contour_list, image):
# print type(image)
if (contour_list is None) and (image is ... | StarcoderdataPython |
161072 | import glob
import logging
from . import Reader
LOG = logging.getLogger(__name__)
def load_all(path, recursive=True, scene_type=None, sample=None):
"""Parsed scenes at the given path returned as a generator.
Each scene contains a list of `Row`s where the first pedestrian is the
pedestrian of interest.
... | StarcoderdataPython |
109100 | <reponame>Dawars/stereo-magnification
#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | StarcoderdataPython |
1661988 | <filename>src/gerel/debug/model_validator.py
def validate_model(model, *args, **kwargs):
if not model.inputs:
raise ValueError('Model has no input nodes')
if not model.outputs:
raise ValueError('Model has no output nodes')
| StarcoderdataPython |
172449 | <reponame>vztpv/Python-Study
# 5-5 Problems
print(all([1, 2, abs(-3)-3]))
print(chr(ord('a')) == 'a')
x = [1, -2, 3, -5, 8, -3]
print(list(filter(lambda val: val > 0, x)))
x = hex(234)
print(int(x, 16))
x = [1, 2, 3, 4]
print(list(map(lambda a: a * 3, x)))
x = [-8, 2, 7, 5, -3, 5, 0, 1]
print(max(x)... | StarcoderdataPython |
3329045 | # -*- coding: utf-8 -*-
import os,sys,shutil
import zipfile,glob,subprocess
import traceback
def u(text):
return unicode(text,"utf-8")
def myjoin(*args):
path = os.path.join(*args)
path = os.path.abspath(path)
return path
def luaCompileWithLuac(desc,path):
try:
for dirname, dirnames, filenames in os.walk(path... | StarcoderdataPython |
24031 | <filename>add_admin.py
import sqlite3
from config import DB_PATH
def exe_query(query):
con_obj = sqlite3.connect(DB_PATH)
courser = con_obj.execute(query)
res = courser.fetchall()
con_obj.commit()
con_obj.close()
return res
try:
admin_id = int(input('Enter admin id: '))
exe_query(f'I... | StarcoderdataPython |
185162 | # Author: <NAME>
# E-mail: <EMAIL>
# Author: <NAME>
# E-mail: <EMAIL>
# Author: <NAME>
# E-mail: <EMAIL>
try:
from exam.utils.baseline_studies import EMBEDDINGvsTRAIN_EMBEDDINGS
from exam.utils.baseline_studies import NUM_LAYERSvsHIDDEN_DIM
from exam.utils.baseline_studies import LEARNING_RATEvsDROPOUT
... | StarcoderdataPython |
1678426 | #!/usr/bin/env python
# Copyright 2014-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import unittest
import os
import tempfile
# internal modules:
from yotta.lib.folders import globalInstallDirectory
from yotta.test.cli import cli... | StarcoderdataPython |
4819228 | <reponame>epm0dev/Lens-dev
from django.test import TestCase, Client
# A test case for the contact page's GET and POST requests.
class ContactPageTestCase(TestCase):
# Set up the class for testing.
@classmethod
def setUpClass(cls):
# Call the superclass' setUpClass() method.
super().setUpCl... | StarcoderdataPython |
1621264 | """
=======
License
=======
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy... | StarcoderdataPython |
1610909 | # -*- coding: utf-8 -*-
# Copyright (C) 2012, <NAME>
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import numpy as np
from visvis.wobjects.polygonalModeling import BaseMesh
def combineMeshes(meshes):
""" combineMeshes(meshes)
Given a... | StarcoderdataPython |
1747121 | <reponame>breadtech/interface<gh_stars>0
import json
fp = open('menu.json')
s = fp.read()
# implement security here
# - bad to just pass in a string from a config file
menu = json.loads(s)
| StarcoderdataPython |
110217 | # -*- coding: utf-8 -*-
"""Example for sending batch information to InfluxDB via UDP."""
"""
INFO: In order to use UDP, one should enable the UDP service from the
`influxdb.conf` under section
[[udp]]
enabled = true
bind-address = ":8089" # port number for sending data via UDP
database = "u... | StarcoderdataPython |
3268617 | <gh_stars>0
# -*- mode: python; -*-
# Execute this script using Bash script of the same name but without a file
# extension. Use ../pdbwrapper/pdbwrapper instead of pdb for debugging.
import os
import sys
import argparse
description = r"""
the_name_of_script_goes_here -- Short description line goes here
Multi-line d... | StarcoderdataPython |
104744 | <filename>game.py
import pygame
import time
import random
def game_loop(window):
clock = pygame.time.Clock()
stop = False
circle_coords = [250, 250]
circle_radius = 10
velocity = [0,0]
painted = pygame.Surface((500, 500))
drawing = True
event_vel_map = {
pygame.K_UP: [0, -1]... | StarcoderdataPython |
4808513 | from django.apps import AppConfig
class ProductsalesuiConfig(AppConfig):
name = 'productSalesUi'
| StarcoderdataPython |
1709397 | <reponame>uincore/lane-finder
import sys
sys.path.append("../")
from image_processor import ImageProcessor
from lane_detector import LaneDetector
from camera import Camera
from image_operations.threshold import ColorAndGradientThresholdOperation
from image_operations.color_threshold import WhiteAndYellowColorThreshold... | StarcoderdataPython |
1723061 | <gh_stars>100-1000
import collections
from collections import OrderedDict, namedtuple
class deque:
def __init__(self, iterable, maxlen, flags=0):
assert iterable == ()
self.maxlen = maxlen
self.flags = flags
self.d = collections.deque(iterable, maxlen)
def __len__(self):
... | StarcoderdataPython |
168375 | <gh_stars>0
import sys
import numpy as np
import math
from OpenGL.GL import *
from OpenGL.GL import shaders
from OpenGL.GLUT import *
vao = None
vbo = None
shaderProgram = None
uniColor = None
# gera os vertices do circulo
# retorna um array com os vertices
def circleVertex(raio, cx, cy):
vertices = []
for i in ran... | StarcoderdataPython |
1673512 | # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import uuid
from telemetry.backend.backend import TelemetryBackend
from telemetry.utils.message import Message, MessageType
from telemetry.utils.guid import get_or_generate_uid
class GABackend(TelemetryBackend):
backend_url = 'htt... | StarcoderdataPython |
15361 | import flask
import telebot
import words
from dotenv import load_dotenv
load_dotenv()
app = flask.Flask(__name__)
bot = telebot.TeleBot(environ.get("TG_TOKEN"), threaded=False)
WEBHOOK_URL_PATH = "/%s/" % (environ.get("TG_TOKEN"))
# # Remove webhook, it fails sometimes the set if there is a previous webhook
# bot.re... | StarcoderdataPython |
4822648 | # for backwards compat
from redis_cache import RedisCache
from redis_cache import ShardedRedisCache
from redis_cache.backends.base import ImproperlyConfigured
from redis_cache.connection import pool
| StarcoderdataPython |
90480 | from datetime import timedelta
from django.utils import timezone
from django.contrib.contenttypes.models import ContentType
from rest_framework.test import APITestCase
from blitz_api.factories import UserFactory
from ..models import Membership, Order, OrderLine, Refund
class RefundTests(APITestCase):
@classm... | StarcoderdataPython |
3248795 | <reponame>Sitcode-Zoograf/storyboard<gh_stars>0
# Copyright (c) 2015 Mirantis 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 re... | StarcoderdataPython |
3383896 | <reponame>dtom90/pygotham_boiler_miner
import urllib.request
from bs4 import BeautifulSoup
import os
outputPathBase = os.path.join(os.path.dirname(__file__), 'DEPData/')
urlPrefix = "file://"+outputPathBase
def getDEPData( appNum ):
url = requestToDEPUrl( appNum )
soup = urlToSoup( url )
if hasDEPData( so... | StarcoderdataPython |
1770149 | <filename>spark_auto_mapper_fhir/backbone_elements/plan_definition_target.py
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.e... | StarcoderdataPython |
4809543 | <reponame>danielzhaotongliu/cs348_project<filename>backend/exampleapp/models.py<gh_stars>1-10
from __future__ import unicode_literals
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from phone_field import PhoneField
# Create your models here.
class Customer(mode... | StarcoderdataPython |
1645815 | <filename>retropath2_wrapper/RetroPath2.py
#!/usr/bin/env python3
"""
Created on January 16 2020
@author: <NAME>, <NAME>
@description: Python wrapper to run RetroPath2.0 KNIME workflow
"""
from os import (
mkdir as os_mkdir,
path as os_path,
rename,
devnull,
# geteuid,
# getegid
)
fro... | StarcoderdataPython |
1605830 | from app import db
from app.helpers.graphene_types import BaseSQLAlchemyObjectType
from app.helpers.mail_type import EmailType
from app.models.base import BaseModel
from app.models.utils import enum_column
class Email(BaseModel):
mailjet_id = db.Column(db.TEXT, unique=True, nullable=False)
address = db.Colum... | StarcoderdataPython |
1648699 | <gh_stars>1-10
"""
API calls for flowcharts
"""
from seamm_datastore.database.models import Flowchart
from seamm_datastore.database.schema import FlowchartSchema
from flask import Response
from flask_jwt_extended import jwt_required
from seamm_dashboard import authorize
import json
__all__ = ["get_flowcharts", "get... | StarcoderdataPython |
74018 | default_app_config = "example.apps.ExampleConfig"
| StarcoderdataPython |
111939 | <filename>utilities/utilities.py
import numpy as np
from math import log
# sigmoid activation as per example
def sigmoid_activation(x):
return 1.0 / (1.0+np.exp(-x))
# inverted sigmoid activation
def inv_sigmoid_activation(x):
return -1.0 * np.log((1.0-x)/x) if x > 0.0 else 0.0
# corresponding derivative
... | StarcoderdataPython |
3212747 | """
列表:list
insert(i,x)
remove(x)
sort()
count()
append(x)
reverse()
index(x) 返回列表中第一个值为x的索引,如果没有匹配到返回一个错误
"""
# a=[66.25,333,333,1,1234.5]
# print(a.count(333),a.count(66.25),a.count("x"))
# a.insert(2,-1)
# a.append(333)
# print(a)
#
# print(a.index(333))
# a.remove(333)
# print(a)
# a.reverse()
# print(a)
# a.sort()... | StarcoderdataPython |
1725075 | <filename>discord_dice_roller/main.py
"""Main file for our bot"""
# Built-in
import os
import random
# Third-party
from discord.ext import commands
from dotenv import load_dotenv
# Application
from cogs import DiceRollingCog, GuildConfigCog, UserConfigCog, UtilityCog
from utils.logging import setup_logging
from util... | StarcoderdataPython |
3291236 | # Small alphabet k using function
def for_k():
""" *'s printed in the shape of k """
for row in range(9):
for col in range(9):
if col ==0 or row+col ==5 and row >1 or row -col ==3:
print('*',end=' ')
else:
print(' ',end=' ')
print... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.